refactor(frontend): rename booklore-ui to frontend
- Frontend path: - rename the tracked Angular app tree from `booklore-ui/` to `frontend/` - preserve file contents during the move so this commit stays focused on the path change itself - Frontend docs: - update the moved frontend README and contribution guide where they refer to the renamed folder - keep those edits limited to path references introduced by the directory rename
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
<ng-container *transloco="let t; prefix: 'app'">
|
||||
@if (loading) {
|
||||
<div class="splash-screen">
|
||||
<div class="splash-content">
|
||||
<svg class="logo" viewBox="0 0 126 126" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z" fill="#818cf8"/>
|
||||
<path d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z" fill="white"/>
|
||||
</svg>
|
||||
@if (offline) {
|
||||
<h1>{{ t('offline') }}</h1>
|
||||
<p>{{ t('offlineLoadingDescription') }}</p>
|
||||
<p>{{ t('offlineDescription') }}</p>
|
||||
} @else {
|
||||
<h1>{{ t('loading') }}</h1>
|
||||
<p>{{ t('loadingDescription') }}</p>
|
||||
<div class="loader"></div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
} @else if (offline) {
|
||||
<div class="splash-screen">
|
||||
<div class="splash-content">
|
||||
<svg class="logo" viewBox="0 0 126 126" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z" fill="#818cf8"/>
|
||||
<path d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z" fill="white"/>
|
||||
</svg>
|
||||
<h1>{{ t('offline') }}</h1>
|
||||
<p>{{ t('connectionLost') }}</p>
|
||||
<button class="retry-btn" (click)="reload()">{{ 'common.retry' | transloco }}</button>
|
||||
</div>
|
||||
</div>
|
||||
} @else {
|
||||
<p-confirmDialog />
|
||||
<p-toast></p-toast>
|
||||
<router-outlet></router-outlet>
|
||||
}
|
||||
</ng-container>
|
||||
@@ -0,0 +1,65 @@
|
||||
.splash-screen {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100dvh;
|
||||
background-color: #0e0e10;
|
||||
color: #e5e5e5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.splash-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.logo {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.8rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 1rem;
|
||||
color: #a0a0a0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.loader {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 4px solid #818cf8;
|
||||
border-top: 4px solid transparent;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.retry-btn {
|
||||
margin-top: 1rem;
|
||||
padding: 0.6rem 1.5rem;
|
||||
background-color: #818cf8;
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.95rem;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
|
||||
&:hover {
|
||||
background-color: #6366f1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {signal} from '@angular/core';
|
||||
import {AppComponent} from './app.component';
|
||||
import {AuthInitializationService} from './core/security/auth-initialization-service';
|
||||
import {of} from 'rxjs';
|
||||
import {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||
import {BookService} from './features/book/service/book.service';
|
||||
import {NotificationEventService} from './shared/websocket/notification-event.service';
|
||||
import {AppConfigService} from './shared/service/app-config.service';
|
||||
import {MetadataProgressService} from './shared/service/metadata-progress.service';
|
||||
import {BookdropFileService} from './features/bookdrop/service/bookdrop-file.service';
|
||||
import {TaskService} from './features/settings/task-management/task.service';
|
||||
import {LibraryService} from './features/book/service/library.service';
|
||||
import {LibraryHealthService} from './features/book/service/library-health.service';
|
||||
import {LibraryLoadingService} from './features/library-creator/library-loading.service';
|
||||
import {TranslocoTestingModule} from '@jsverse/transloco';
|
||||
|
||||
describe('AppComponent offline detection', () => {
|
||||
let fixture: ComponentFixture<AppComponent>;
|
||||
let component: AppComponent;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [TranslocoTestingModule.forRoot({langs: {}})],
|
||||
providers: [
|
||||
{provide: AuthInitializationService, useValue: {initialized: signal(false)}},
|
||||
{provide: RxStompService, useValue: {watch: vi.fn(() => of())}},
|
||||
{provide: BookService, useValue: {}},
|
||||
{provide: NotificationEventService, useValue: {}},
|
||||
{provide: AppConfigService, useValue: {}},
|
||||
{provide: MetadataProgressService, useValue: {}},
|
||||
{provide: BookdropFileService, useValue: {}},
|
||||
{provide: TaskService, useValue: {}},
|
||||
{provide: LibraryService, useValue: {largeLibraryLoading: signal({isLoading: false, expectedCount: 0})}},
|
||||
{provide: LibraryHealthService, useValue: {initialize: vi.fn()}},
|
||||
{provide: LibraryLoadingService, useValue: {hide: vi.fn()}},
|
||||
]
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(AppComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should initialize with offline set to false', () => {
|
||||
expect(component.offline).toBe(false);
|
||||
});
|
||||
|
||||
it('should set offline to false when online event fires', () => {
|
||||
component.offline = true;
|
||||
window.dispatchEvent(new Event('online'));
|
||||
expect(component.offline).toBe(false);
|
||||
});
|
||||
|
||||
it('should not show offline when server is reachable despite browser offline event', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 200}));
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(component.offline).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should show offline when server is unreachable on browser offline event', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('Failed to fetch'));
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(component.offline).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should ping server with HEAD method and no-store cache', async () => {
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 200}));
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(fetchSpy).toHaveBeenCalledWith('/api/public/settings', {method: 'HEAD', cache: 'no-store'});
|
||||
});
|
||||
});
|
||||
|
||||
it('should treat server errors as reachable', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, {status: 500}));
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(component.offline).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should treat network timeout as unreachable', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('network timeout'));
|
||||
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(component.offline).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import {Component, effect, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||
import {BookService} from './features/book/service/book.service';
|
||||
import {NotificationEventService} from './shared/websocket/notification-event.service';
|
||||
import {parseLogNotification} from './shared/websocket/model/log-notification.model';
|
||||
import {ConfirmDialog} from 'primeng/confirmdialog';
|
||||
import {Toast} from 'primeng/toast';
|
||||
import {RouterOutlet} from '@angular/router';
|
||||
import {TranslocoDirective, TranslocoPipe} from '@jsverse/transloco';
|
||||
import {AuthInitializationService} from './core/security/auth-initialization-service';
|
||||
import {AppConfigService} from './shared/service/app-config.service';
|
||||
import {MetadataBatchProgressNotification} from './shared/model/metadata-batch-progress.model';
|
||||
import {MetadataProgressService} from './shared/service/metadata-progress.service';
|
||||
import {BookdropFileNotification, BookdropFileService} from './features/bookdrop/service/bookdrop-file.service';
|
||||
import {Subscription} from 'rxjs';
|
||||
import {TaskProgressPayload, TaskService} from './features/settings/task-management/task.service';
|
||||
import {LibraryService} from './features/book/service/library.service';
|
||||
import {LibraryHealthService} from './features/book/service/library-health.service';
|
||||
import {LibraryLoadingService} from './features/library-creator/library-loading.service';
|
||||
import {scan} from 'rxjs/operators';
|
||||
import {AuthService} from './shared/service/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
templateUrl: './app.component.html',
|
||||
styleUrl: './app.component.scss',
|
||||
standalone: true,
|
||||
imports: [ConfirmDialog, Toast, RouterOutlet, TranslocoDirective, TranslocoPipe]
|
||||
})
|
||||
export class AppComponent implements OnInit, OnDestroy {
|
||||
|
||||
loading = true;
|
||||
offline = false;
|
||||
private subscriptions: Subscription[] = [];
|
||||
private subscriptionsInitialized = false;
|
||||
|
||||
private appConfigService = inject(AppConfigService); // DO NOT REMOVE: Used to initialize app config on startup
|
||||
private authInit = inject(AuthInitializationService);
|
||||
private bookService = inject(BookService);
|
||||
private rxStompService = inject(RxStompService);
|
||||
private notificationEventService = inject(NotificationEventService);
|
||||
private metadataProgressService = inject(MetadataProgressService);
|
||||
private bookdropFileService = inject(BookdropFileService);
|
||||
private taskService = inject(TaskService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private libraryHealthService = inject(LibraryHealthService);
|
||||
private libraryLoadingService = inject(LibraryLoadingService);
|
||||
private authService = inject(AuthService);
|
||||
private readonly syncAuthInitializationEffect = effect(() => {
|
||||
const ready = this.authInit.initialized();
|
||||
this.loading = !ready;
|
||||
|
||||
if (ready && !this.subscriptionsInitialized) {
|
||||
this.setupWebSocketSubscriptions();
|
||||
this.libraryHealthService.initialize();
|
||||
this.subscriptionsInitialized = true;
|
||||
}
|
||||
});
|
||||
|
||||
ngOnInit(): void {
|
||||
window.addEventListener('online', this.onOnline);
|
||||
window.addEventListener('offline', this.onOffline);
|
||||
}
|
||||
|
||||
private onOnline = () => {
|
||||
this.offline = false;
|
||||
};
|
||||
|
||||
private onOffline = () => {
|
||||
this.checkServerReachable().then(reachable => {
|
||||
this.offline = !reachable;
|
||||
});
|
||||
};
|
||||
|
||||
private checkServerReachable(): Promise<boolean> {
|
||||
return fetch('/api/public/settings', {method: 'HEAD', cache: 'no-store'})
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
}
|
||||
|
||||
reload(): void {
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
private setupWebSocketSubscriptions(): void {
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-add').pipe(
|
||||
scan((acc, msg) => {
|
||||
const loadingState = this.libraryService.largeLibraryLoading();
|
||||
const book = JSON.parse(msg.body);
|
||||
if (loadingState.isLoading) {
|
||||
const newCount = acc.count + 1;
|
||||
this.libraryLoadingService.showBookLoadingProgress(book.metadata?.title || 'Unknown Book', newCount, loadingState.expectedCount);
|
||||
this.bookService.handleNewlyCreatedBook(book);
|
||||
if (newCount >= loadingState.expectedCount) {
|
||||
this.libraryService.setLargeLibraryLoading(false, 0);
|
||||
return {count: 0};
|
||||
}
|
||||
return {count: newCount};
|
||||
} else {
|
||||
this.bookService.handleNewlyCreatedBook(book);
|
||||
return {count: 0};
|
||||
}
|
||||
}, {count: 0})
|
||||
).subscribe()
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-update').subscribe(msg =>
|
||||
this.bookService.handleBookUpdate(JSON.parse(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/books-cover-update').subscribe(msg =>
|
||||
this.bookService.handleMultipleBookCoverPatches(JSON.parse(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/books-remove').subscribe(msg =>
|
||||
this.bookService.handleRemovedBookIds(JSON.parse(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-metadata-update').subscribe(msg =>
|
||||
this.bookService.handleBookUpdate(JSON.parse(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-metadata-batch-update').subscribe(msg =>
|
||||
this.bookService.handleMultipleBookUpdates(JSON.parse(msg.body))
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-metadata-batch-progress').subscribe(msg =>
|
||||
this.metadataProgressService.handleIncomingProgress(JSON.parse(msg.body) as MetadataBatchProgressNotification)
|
||||
)
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/log').subscribe(msg => {
|
||||
const logNotification = parseLogNotification(msg.body);
|
||||
this.notificationEventService.handleNewNotification(logNotification);
|
||||
})
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/bookdrop-file').subscribe(msg => {
|
||||
const notification = JSON.parse(msg.body) as BookdropFileNotification;
|
||||
this.bookdropFileService.handleIncomingFile(notification);
|
||||
})
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/task-progress').subscribe(msg => {
|
||||
const progress = JSON.parse(msg.body) as TaskProgressPayload;
|
||||
this.taskService.handleTaskProgress(progress);
|
||||
})
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/session-revoked').subscribe(() => {
|
||||
this.authService.forceLogout('session_revoked');
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
window.removeEventListener('online', this.onOnline);
|
||||
window.removeEventListener('offline', this.onOffline);
|
||||
this.subscriptions.forEach(sub => sub.unsubscribe());
|
||||
this.libraryLoadingService.hide();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import {Routes} from '@angular/router';
|
||||
import {BookBrowserComponent} from './features/book/components/book-browser/book-browser.component';
|
||||
import {AppLayoutComponent} from './shared/layout/component/layout-main/app.layout.component';
|
||||
import {LoginComponent} from './shared/components/login/login.component';
|
||||
import {AuthGuard} from './core/security/auth.guard';
|
||||
import {ChangePasswordComponent} from './shared/components/change-password/change-password.component';
|
||||
import {SetupComponent} from './shared/components/setup/setup.component';
|
||||
import {SetupGuard} from './shared/components/setup/setup.guard';
|
||||
import {SetupRedirectGuard} from './shared/components/setup/setup-redirect.guard';
|
||||
import {EmptyComponent} from './shared/components/empty/empty.component';
|
||||
import {OidcCallbackComponent} from './core/security/oidc-callback/oidc-callback.component';
|
||||
import {MainDashboardComponent} from './features/dashboard/components/main-dashboard/main-dashboard.component';
|
||||
import {LoginGuard} from './shared/components/setup/login.guard';
|
||||
import {BookdropGuard} from './core/security/guards/bookdrop.guard';
|
||||
import {LibraryStatsGuard} from './core/security/guards/library-stats.guard';
|
||||
import {UserStatsGuard} from './core/security/guards/user-stats.guard';
|
||||
import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
path: '',
|
||||
canActivate: [SetupRedirectGuard],
|
||||
pathMatch: 'full',
|
||||
component: EmptyComponent
|
||||
},
|
||||
{
|
||||
path: 'setup',
|
||||
component: SetupComponent,
|
||||
canActivate: [SetupGuard]
|
||||
},
|
||||
{path: 'oauth2-callback', component: OidcCallbackComponent},
|
||||
{
|
||||
path: '',
|
||||
component: AppLayoutComponent,
|
||||
children: [
|
||||
{path: 'dashboard', component: MainDashboardComponent, canActivate: [AuthGuard]},
|
||||
{path: 'all-books', component: BookBrowserComponent, canActivate: [AuthGuard]},
|
||||
{path: 'settings', loadComponent: () => import('./features/settings/settings.component').then(m => m.SettingsComponent), canActivate: [AuthGuard]},
|
||||
{path: 'library/:libraryId/books', component: BookBrowserComponent, canActivate: [AuthGuard]},
|
||||
{path: 'shelf/:shelfId/books', component: BookBrowserComponent, canActivate: [AuthGuard]},
|
||||
{path: 'unshelved-books', component: BookBrowserComponent, canActivate: [AuthGuard]},
|
||||
{path: 'series', loadComponent: () => import('./features/series-browser/components/series-browser/series-browser.component').then(m => m.SeriesBrowserComponent), canActivate: [AuthGuard]},
|
||||
{path: 'series/:seriesName', loadComponent: () => import('./features/book/components/series-page/series-page.component').then(m => m.SeriesPageComponent), canActivate: [AuthGuard]},
|
||||
{path: 'authors', loadComponent: () => import('./features/author-browser/components/author-browser/author-browser.component').then(m => m.AuthorBrowserComponent), canActivate: [AuthGuard]},
|
||||
{path: 'author/:authorId', loadComponent: () => import('./features/author-browser/components/author-detail/author-detail.component').then(m => m.AuthorDetailComponent), canActivate: [AuthGuard]},
|
||||
{path: 'magic-shelf/:magicShelfId/books', component: BookBrowserComponent, canActivate: [AuthGuard]},
|
||||
{path: 'book/:bookId', loadComponent: () => import('./features/metadata/component/book-metadata-center/book-metadata-center.component').then(m => m.BookMetadataCenterComponent), canActivate: [AuthGuard]},
|
||||
{path: 'bookdrop', loadComponent: () => import('./features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component').then(m => m.BookdropFileReviewComponent), canActivate: [BookdropGuard]},
|
||||
{path: 'metadata-manager', loadComponent: () => import('./features/metadata/component/metadata-manager/metadata-manager.component').then(m => m.MetadataManagerComponent), canActivate: [EditMetadataGuard]},
|
||||
{path: 'library-stats', loadComponent: () => import('./features/stats/component/library-stats/library-stats.component').then(m => m.LibraryStatsComponent), canActivate: [LibraryStatsGuard]},
|
||||
{path: 'reading-stats', loadComponent: () => import('./features/stats/component/user-stats/user-stats.component').then(m => m.UserStatsComponent), canActivate: [UserStatsGuard]},
|
||||
{path: 'notebook', loadComponent: () => import('./features/notebook/components/notebook/notebook.component').then(m => m.NotebookComponent), canActivate: [AuthGuard]},
|
||||
]
|
||||
},
|
||||
{
|
||||
path: 'pdf-reader/book/:bookId',
|
||||
loadComponent: () => import('./features/readers/pdf-reader/pdf-reader.component').then(m => m.PdfReaderComponent),
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'ebook-reader/book/:bookId',
|
||||
loadComponent: () => import('./features/readers/ebook-reader/ebook-reader.component').then(m => m.EbookReaderComponent),
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'cbx-reader/book/:bookId',
|
||||
loadComponent: () => import('./features/readers/cbx-reader/cbx-reader.component').then(m => m.CbxReaderComponent),
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'audiobook-player/book/:bookId',
|
||||
loadComponent: () => import('./features/readers/audiobook-player/audiobook-player.component').then(m => m.AudiobookPlayerComponent),
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'login',
|
||||
component: LoginComponent,
|
||||
canActivate: [LoginGuard]
|
||||
},
|
||||
{
|
||||
path: 'change-password',
|
||||
component: ChangePasswordComponent
|
||||
},
|
||||
{
|
||||
path: '**',
|
||||
redirectTo: 'login',
|
||||
pathMatch: 'full'
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,7 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
describe('App', () => {
|
||||
it('should pass', () => {
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import {environment} from '../../../environments/environment';
|
||||
|
||||
export const API_CONFIG = environment.API_CONFIG;
|
||||
@@ -0,0 +1,38 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
import {AVAILABLE_LANGS} from './transloco-loader';
|
||||
|
||||
// TODO(grimmory-cleanup): Remove after the Booklore-to-Grimmory localStorage migration window closes.
|
||||
export const LEGACY_LANG_STORAGE_KEY = 'booklore-lang';
|
||||
export const LANG_STORAGE_KEY = 'grimmory-lang';
|
||||
|
||||
function detectLanguage(available: string[]): string {
|
||||
const saved = localStorage.getItem(LANG_STORAGE_KEY) ?? localStorage.getItem(LEGACY_LANG_STORAGE_KEY);
|
||||
if (saved && available.includes(saved)) {
|
||||
localStorage.setItem(LANG_STORAGE_KEY, saved);
|
||||
return saved;
|
||||
}
|
||||
|
||||
const browserLocale = navigator.language;
|
||||
if (browserLocale && available.includes(browserLocale)) {
|
||||
return browserLocale;
|
||||
}
|
||||
|
||||
const baseLang = browserLocale?.split('-')[0];
|
||||
if (baseLang && available.includes(baseLang)) {
|
||||
return baseLang;
|
||||
}
|
||||
|
||||
return 'en';
|
||||
}
|
||||
|
||||
export function initializeLanguage() {
|
||||
return () => {
|
||||
const translocoService = inject(TranslocoService);
|
||||
const lang = detectLanguage(AVAILABLE_LANGS);
|
||||
translocoService.setActiveLang(lang);
|
||||
localStorage.setItem(LANG_STORAGE_KEY, lang);
|
||||
return firstValueFrom(translocoService.load(lang));
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Translation, TranslocoLoader} from '@jsverse/transloco';
|
||||
import {from, of, Observable} from 'rxjs';
|
||||
import en from '../../../i18n/en';
|
||||
|
||||
export const EN_TRANSLATIONS: Translation = en;
|
||||
|
||||
// To add a new language: create src/i18n/<lang>/ with domain JSONs + index.ts, then add an entry here.
|
||||
const LAZY_LANG_LOADERS: Record<string, () => Promise<{default: Translation}>> = {
|
||||
es: () => import('../../../i18n/es'),
|
||||
it: () => import('../../../i18n/it'),
|
||||
de: () => import('../../../i18n/de'),
|
||||
fr: () => import('../../../i18n/fr'),
|
||||
nl: () => import('../../../i18n/nl'),
|
||||
pl: () => import('../../../i18n/pl'),
|
||||
pt: () => import('../../../i18n/pt'),
|
||||
ru: () => import('../../../i18n/ru'),
|
||||
hr: () => import('../../../i18n/hr'),
|
||||
sv: () => import('../../../i18n/sv'),
|
||||
zh: () => import('../../../i18n/zh'),
|
||||
ja: () => import('../../../i18n/ja'),
|
||||
hu: () => import('../../../i18n/hu'),
|
||||
sl: () => import('../../../i18n/sl'),
|
||||
sk: () => import('../../../i18n/sk'),
|
||||
uk: () => import('../../../i18n/uk'),
|
||||
id: () => import('../../../i18n/id'),
|
||||
da: () => import('../../../i18n/da'),
|
||||
};
|
||||
|
||||
export const AVAILABLE_LANGS = ['en', ...Object.keys(LAZY_LANG_LOADERS)];
|
||||
|
||||
export const LANG_LABELS: Record<string, string> = {
|
||||
en: 'English',
|
||||
es: 'Español',
|
||||
it: 'Italiano',
|
||||
de: 'Deutsch',
|
||||
fr: 'Français',
|
||||
nl: 'Nederlands',
|
||||
pl: 'Polski',
|
||||
pt: 'Português',
|
||||
ru: 'Русский',
|
||||
hr: 'Hrvatski',
|
||||
sv: 'Svenska',
|
||||
zh: '中文',
|
||||
ja: '日本語',
|
||||
hu: 'Magyar',
|
||||
sl: 'Slovenščina',
|
||||
sk: 'Slovenčina',
|
||||
uk: 'Українська',
|
||||
id: 'Bahasa Indonesia',
|
||||
da: 'Dansk',
|
||||
};
|
||||
|
||||
function deepMerge(base: Record<string, Translation>, override: Record<string, Translation>): Record<string, Translation> {
|
||||
const result = {...base};
|
||||
for (const key of Object.keys(override)) {
|
||||
if (override[key] && typeof override[key] === 'object' && !Array.isArray(override[key])
|
||||
&& base[key] && typeof base[key] === 'object' && !Array.isArray(base[key])) {
|
||||
result[key] = deepMerge(base[key], override[key]);
|
||||
} else if (override[key]) {
|
||||
result[key] = override[key];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class TranslocoInlineLoader implements TranslocoLoader {
|
||||
getTranslation(lang: string): Observable<Translation> {
|
||||
if (lang === 'en') {
|
||||
return of(EN_TRANSLATIONS);
|
||||
}
|
||||
const loader = LAZY_LANG_LOADERS[lang];
|
||||
if (loader) {
|
||||
return from(loader().then(m => deepMerge(EN_TRANSLATIONS, m.default)));
|
||||
}
|
||||
return of(EN_TRANSLATIONS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy} from '@angular/router';
|
||||
import {BookBrowserScrollService} from '../features/book/components/book-browser/book-browser-scroll.service';
|
||||
import {BookSelectionService} from '../features/book/components/book-browser/book-selection.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class CustomReuseStrategy implements RouteReuseStrategy {
|
||||
private storedRoutes = new Map<string, DetachedRouteHandle>();
|
||||
private scrollService = inject(BookBrowserScrollService);
|
||||
private bookSelectionService = inject(BookSelectionService);
|
||||
|
||||
private readonly BOOK_BROWSER_PATHS = [
|
||||
'all-books',
|
||||
'unshelved-books',
|
||||
'library/:libraryId/books',
|
||||
'shelf/:shelfId/books',
|
||||
'magic-shelf/:magicShelfId/books',
|
||||
'authors',
|
||||
'series'
|
||||
];
|
||||
|
||||
private readonly BOOK_DETAILS_PATH = 'book/:bookId';
|
||||
|
||||
private getRouteKey(route: ActivatedRouteSnapshot): string {
|
||||
const path = route.routeConfig?.path || '';
|
||||
return this.scrollService.createKey(path, route.params);
|
||||
}
|
||||
|
||||
private isBookBrowserRoute(route: ActivatedRouteSnapshot): boolean {
|
||||
const path = route.routeConfig?.path;
|
||||
return this.BOOK_BROWSER_PATHS.includes(path || '');
|
||||
}
|
||||
|
||||
shouldDetach(route: ActivatedRouteSnapshot): boolean {
|
||||
return this.isBookBrowserRoute(route);
|
||||
}
|
||||
|
||||
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
|
||||
if (handle && this.isBookBrowserRoute(route)) {
|
||||
const key = this.getRouteKey(route);
|
||||
this.storedRoutes.set(key, handle);
|
||||
this.bookSelectionService.deselectAll();
|
||||
}
|
||||
}
|
||||
|
||||
shouldAttach(route: ActivatedRouteSnapshot): boolean {
|
||||
if (!this.isBookBrowserRoute(route)) {
|
||||
return false;
|
||||
}
|
||||
const key = this.getRouteKey(route);
|
||||
return this.storedRoutes.has(key);
|
||||
}
|
||||
|
||||
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
|
||||
const key = this.getRouteKey(route);
|
||||
const handle = this.storedRoutes.get(key) || null;
|
||||
|
||||
if (handle) {
|
||||
const savedPosition = this.scrollService.getPosition(key);
|
||||
if (savedPosition !== undefined) {
|
||||
setTimeout(() => {
|
||||
const scrollElement = document.querySelector('.virtual-scroller');
|
||||
if (scrollElement) {
|
||||
(scrollElement as HTMLElement).scrollTop = savedPosition;
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
|
||||
return future.routeConfig === curr.routeConfig &&
|
||||
JSON.stringify(future.params) === JSON.stringify(curr.params);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import {Injectable, signal} from '@angular/core';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class AuthInitializationService {
|
||||
private readonly _initialized = signal(false);
|
||||
readonly initialized = this._initialized.asReadonly();
|
||||
|
||||
markAsInitialized(): void {
|
||||
this._initialized.set(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {signal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {initializeAuthFactory} from './auth-initializer';
|
||||
import {AuthInitializationService} from './auth-initialization-service';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {AppSettingsService, PublicAppSettings} from '../../shared/service/app-settings.service';
|
||||
import {QueryClient, queryOptions} from '@tanstack/angular-query-experimental';
|
||||
|
||||
describe('initializeAuthFactory', () => {
|
||||
let authInitService: AuthInitializationService;
|
||||
let mockQueryClient: { fetchQuery: ReturnType<typeof vi.fn> };
|
||||
|
||||
const defaultPublicSettings: PublicAppSettings = {
|
||||
oidcEnabled: false,
|
||||
remoteAuthEnabled: false,
|
||||
oidcProviderDetails: null!,
|
||||
oidcForceOnlyMode: false,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockQueryClient = {
|
||||
fetchQuery: vi.fn().mockResolvedValue(defaultPublicSettings),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: AuthService, useValue: {token: signal(null), getInternalAccessToken: vi.fn()}},
|
||||
{
|
||||
provide: AppSettingsService,
|
||||
useValue: {
|
||||
publicAppSettings: signal(null),
|
||||
getPublicSettingsQueryOptions: () => queryOptions({queryKey: ['public-settings'], queryFn: async () => defaultPublicSettings}),
|
||||
},
|
||||
},
|
||||
{provide: QueryClient, useValue: mockQueryClient},
|
||||
AuthInitializationService,
|
||||
]
|
||||
});
|
||||
|
||||
authInitService = TestBed.inject(AuthInitializationService);
|
||||
});
|
||||
|
||||
it('should proceed with auth initialization when navigator.onLine is false', async () => {
|
||||
const markSpy = vi.spyOn(authInitService, 'markAsInitialized');
|
||||
|
||||
Object.defineProperty(navigator, 'onLine', {value: false, configurable: true});
|
||||
|
||||
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
||||
const initPromise = TestBed.runInInjectionContext(() => factory());
|
||||
|
||||
await initPromise;
|
||||
|
||||
expect(markSpy).toHaveBeenCalled();
|
||||
|
||||
Object.defineProperty(navigator, 'onLine', {value: true, configurable: true});
|
||||
});
|
||||
|
||||
it('should initialize normally when navigator.onLine is true', async () => {
|
||||
const markSpy = vi.spyOn(authInitService, 'markAsInitialized');
|
||||
|
||||
Object.defineProperty(navigator, 'onLine', {value: true, configurable: true});
|
||||
|
||||
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
||||
const initPromise = TestBed.runInInjectionContext(() => factory());
|
||||
|
||||
await initPromise;
|
||||
|
||||
expect(markSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {AuthService, websocketInitializer} from '../../shared/service/auth.service';
|
||||
import {AppSettingsService} from '../../shared/service/app-settings.service';
|
||||
import {AuthInitializationService} from './auth-initialization-service';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
const SETTINGS_TIMEOUT_MS = 10000;
|
||||
|
||||
export function initializeAuthFactory() {
|
||||
return () => {
|
||||
const appSettingsService = inject(AppSettingsService);
|
||||
const authService = inject(AuthService);
|
||||
const authInitService = inject(AuthInitializationService);
|
||||
const queryClient = inject(QueryClient);
|
||||
|
||||
const settingsPromise = queryClient.fetchQuery(appSettingsService.getPublicSettingsQueryOptions());
|
||||
const timeoutPromise = new Promise<null>(resolve =>
|
||||
setTimeout(() => resolve(null), SETTINGS_TIMEOUT_MS)
|
||||
);
|
||||
|
||||
return Promise.race([settingsPromise, timeoutPromise]).then(publicSettings => {
|
||||
if (!publicSettings) {
|
||||
console.warn('[Auth] Public settings fetch timed out, falling back to local auth');
|
||||
authInitService.markAsInitialized();
|
||||
return;
|
||||
}
|
||||
|
||||
if (publicSettings.remoteAuthEnabled) {
|
||||
return new Promise<void>(resolve => {
|
||||
authService.remoteLogin().subscribe({
|
||||
next: () => {
|
||||
authInitService.markAsInitialized();
|
||||
resolve();
|
||||
},
|
||||
error: err => {
|
||||
console.error('[Remote Login] failed:', err);
|
||||
authInitService.markAsInitialized();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
} else {
|
||||
if (authService.getInternalAccessToken()) {
|
||||
websocketInitializer(authService)();
|
||||
}
|
||||
authInitService.markAsInitialized();
|
||||
return;
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import {HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest} from '@angular/common/http';
|
||||
import {inject} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
import {catchError, filter, switchMap, take} from 'rxjs/operators';
|
||||
import {BehaviorSubject, Observable, throwError} from 'rxjs';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
|
||||
export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => {
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
|
||||
const token = authService.getInternalAccessToken();
|
||||
const isApiRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/`);
|
||||
|
||||
const authReq = (token && isApiRequest) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
|
||||
|
||||
return next(authReq).pipe(
|
||||
catchError((error: HttpErrorResponse) => {
|
||||
if (error.status === 401) {
|
||||
return handle401Error(authService, authReq, next, router);
|
||||
}
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
let isRefreshing = false;
|
||||
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
|
||||
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<unknown>, next: HttpHandlerFn, router: Router): Observable<HttpEvent<unknown>> {
|
||||
if (!isRefreshing) {
|
||||
isRefreshing = true;
|
||||
refreshTokenSubject.next(null);
|
||||
|
||||
return authService.internalRefreshToken().pipe(
|
||||
switchMap(response => {
|
||||
isRefreshing = false;
|
||||
const { accessToken, refreshToken } = response;
|
||||
if (accessToken && refreshToken) {
|
||||
authService.saveInternalTokens(accessToken, refreshToken);
|
||||
refreshTokenSubject.next(accessToken);
|
||||
}
|
||||
return next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${accessToken}` }
|
||||
}));
|
||||
}),
|
||||
catchError(err => {
|
||||
isRefreshing = false;
|
||||
forceLogout(authService, router);
|
||||
return throwError(() => err);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return refreshTokenSubject.pipe(
|
||||
filter(token => token !== null),
|
||||
take(1),
|
||||
switchMap(token =>
|
||||
next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${token}` }
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function forceLogout(authService: AuthService, router: Router): void {
|
||||
authService.logout();
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
|
||||
export const AuthGuard: CanActivateFn = (route, state) => {
|
||||
const router = inject(Router);
|
||||
const authService = inject(AuthService);
|
||||
|
||||
const internalAccessToken = authService.getInternalAccessToken();
|
||||
|
||||
if (internalAccessToken) {
|
||||
try {
|
||||
const payload = JSON.parse(atob(internalAccessToken.split('.')[1]));
|
||||
if (payload.exp && payload.exp * 1000 < Date.now()) {
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
return router.createUrlTree(['/login']);
|
||||
}
|
||||
if (payload.isDefaultPassword) {
|
||||
router.navigate(['/change-password']);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const BookdropGuard: CanActivateFn = () => {
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
if (user && (user.permissions.admin || user.permissions.canAccessBookdrop)) {
|
||||
return true;
|
||||
}
|
||||
router.navigate(['/dashboard']);
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const EditMetadataGuard: CanActivateFn = () => {
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
if (user && (user.permissions.admin || user.permissions.canEditMetadata)) {
|
||||
return true;
|
||||
}
|
||||
router.navigate(['/dashboard']);
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const LibraryStatsGuard: CanActivateFn = () => {
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
if (user && (user.permissions.admin || user.permissions.canAccessLibraryStats)) {
|
||||
return true;
|
||||
}
|
||||
router.navigate(['/dashboard']);
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const ManageLibraryGuard: CanActivateFn = () => {
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
if (user && (user.permissions.admin || user.permissions.canManageLibrary)) {
|
||||
return true;
|
||||
}
|
||||
router.navigate(['/dashboard']);
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {UserService} from '../../../features/settings/user-management/user.service';
|
||||
|
||||
export const UserStatsGuard: CanActivateFn = () => {
|
||||
const userService = inject(UserService);
|
||||
const router = inject(Router);
|
||||
const user = userService.currentUser();
|
||||
|
||||
if (user && (user.permissions.admin || user.permissions.canAccessUserStats)) {
|
||||
return true;
|
||||
}
|
||||
router.navigate(['/dashboard']);
|
||||
return false;
|
||||
};
|
||||
+623
@@ -0,0 +1,623 @@
|
||||
<ng-container *transloco="let t; prefix: 'settingsAuth'">
|
||||
<div class="main-container">
|
||||
<div class="settings-header">
|
||||
<h2 class="settings-title">
|
||||
<i class="pi pi-key"></i>
|
||||
{{ t('title') }}
|
||||
</h2>
|
||||
<p class="settings-description">
|
||||
{{ t('description') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-shield"></i>
|
||||
{{ t('methods.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('methods.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="auth-methods-list">
|
||||
<div class="auth-method-item is-active is-locked">
|
||||
<div class="auth-method-content">
|
||||
<div class="auth-method-header">
|
||||
<div class="auth-method-icon">
|
||||
<i class="pi pi-user"></i>
|
||||
</div>
|
||||
<div class="auth-method-info">
|
||||
<span class="auth-method-label">{{ t('internal.label') }}</span>
|
||||
<span class="auth-method-status active">{{ t('internal.status') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="auth-method-description">
|
||||
{{ t('internal.description') }}
|
||||
</p>
|
||||
</div>
|
||||
<p-checkbox
|
||||
[(ngModel)]="internalAuthEnabled"
|
||||
[binary]="true"
|
||||
[disabled]="true">
|
||||
</p-checkbox>
|
||||
</div>
|
||||
|
||||
<div class="auth-method-item" [class.is-active]="oidcEnabled">
|
||||
<div class="auth-method-content">
|
||||
<div class="auth-method-header">
|
||||
<div class="auth-method-icon oidc">
|
||||
<i class="pi pi-key"></i>
|
||||
</div>
|
||||
<div class="auth-method-info">
|
||||
<span class="auth-method-label">
|
||||
{{ t('oidc.label') }}
|
||||
</span>
|
||||
<span class="auth-method-status" [class.active]="oidcEnabled">
|
||||
{{ oidcEnabled ? t('oidc.enabled') : t('oidc.disabled') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="auth-method-description">
|
||||
{{ t('oidc.description') }}
|
||||
<app-external-doc-link docType="authentication"></app-external-doc-link>
|
||||
@if (!isOidcFormComplete() && !oidcEnabled) {
|
||||
<span class="config-hint">{{ t('oidc.configHint') }}</span>
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="oidcEnabled"
|
||||
[disabled]="!isOidcFormComplete()"
|
||||
(onChange)="toggleOidcEnabled()">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-cog"></i>
|
||||
{{ t('providerConfig.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('providerConfig.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="config-grid">
|
||||
<div class="config-item">
|
||||
<label for="providerName">{{ t('providerConfig.providerName') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="providerName"
|
||||
[(ngModel)]="oidcProvider.providerName"
|
||||
[placeholder]="t('providerConfig.providerPlaceholder')"/>
|
||||
</div>
|
||||
|
||||
<div class="config-item">
|
||||
<label for="clientId">{{ t('providerConfig.clientId') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="clientId"
|
||||
[(ngModel)]="oidcProvider.clientId"
|
||||
[placeholder]="t('providerConfig.clientIdPlaceholder')"/>
|
||||
</div>
|
||||
|
||||
<div class="config-item">
|
||||
<label for="clientSecret">{{ t('providerConfig.clientSecret') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="clientSecret"
|
||||
type="password"
|
||||
[(ngModel)]="oidcProvider.clientSecret"
|
||||
[placeholder]="t('providerConfig.clientSecretPlaceholder')"/>
|
||||
<span class="field-hint">{{ t('providerConfig.clientSecretHint') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="config-item span-2">
|
||||
<label for="issuerUri">{{ t('providerConfig.issuerUri') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="issuerUri"
|
||||
[(ngModel)]="oidcProvider.issuerUri"
|
||||
[placeholder]="t('providerConfig.issuerPlaceholder')"/>
|
||||
</div>
|
||||
|
||||
<div class="config-item">
|
||||
<label for="scopes">{{ t('providerConfig.scope') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="scopes"
|
||||
[(ngModel)]="oidcProvider.scopes"
|
||||
[placeholder]="'openid profile email groups offline_access'"/>
|
||||
<span class="field-hint">{{ t('providerConfig.scopeHint') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (oidcEnabled) {
|
||||
<div class="config-grid" style="margin-top: 0.75rem;">
|
||||
<div class="config-item">
|
||||
<label for="sessionDuration">{{ t('providerConfig.sessionDuration') }}</label>
|
||||
<p-inputNumber
|
||||
size="small"
|
||||
inputId="sessionDuration"
|
||||
[(ngModel)]="sessionDurationHours"
|
||||
[min]="1"
|
||||
[max]="8760"
|
||||
[showButtons]="true"
|
||||
[placeholder]="t('providerConfig.sessionDurationPlaceholder')"
|
||||
mode="decimal"
|
||||
[useGrouping]="false">
|
||||
</p-inputNumber>
|
||||
<span class="field-hint">{{ t('providerConfig.sessionDurationHint') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="claims-section">
|
||||
<h4 class="subsection-title">{{ t('providerConfig.claimMappings') }}</h4>
|
||||
<p class="subsection-description">
|
||||
{{ t('providerConfig.claimDesc') }}
|
||||
</p>
|
||||
<div class="claims-grid">
|
||||
<div class="config-item">
|
||||
<label for="claimUsername">{{ t('providerConfig.usernameClaim') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="claimUsername"
|
||||
[(ngModel)]="oidcProvider.claimMapping.username"
|
||||
[placeholder]="t('providerConfig.usernamePlaceholder')"/>
|
||||
</div>
|
||||
<div class="config-item">
|
||||
<label for="claimEmail">{{ t('providerConfig.emailClaim') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="claimEmail"
|
||||
[(ngModel)]="oidcProvider.claimMapping.email"
|
||||
[placeholder]="t('providerConfig.emailPlaceholder')"/>
|
||||
</div>
|
||||
<div class="config-item">
|
||||
<label for="claimName">{{ t('providerConfig.nameClaim') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="claimName"
|
||||
[(ngModel)]="oidcProvider.claimMapping.name"
|
||||
[placeholder]="t('providerConfig.namePlaceholder')"/>
|
||||
</div>
|
||||
<div class="config-item">
|
||||
<label for="claimGroups">{{ t('providerConfig.groupsClaim') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="claimGroups"
|
||||
[(ngModel)]="oidcProvider.claimMapping.groups"
|
||||
[placeholder]="t('providerConfig.groupsPlaceholder')"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="provider-actions-row">
|
||||
<div class="test-results-inline">
|
||||
@if (testConnectionResult) {
|
||||
<div class="test-results-toggle"
|
||||
[style.border-radius]="showTestDetails ? '6px 6px 0 0' : '6px'"
|
||||
(click)="showTestDetails = !showTestDetails">
|
||||
@if (testConnectionResult.success) {
|
||||
<i class="pi pi-check-circle" style="color: var(--p-green-500);"></i>
|
||||
<span>{{ t('testConnection.passed') }}</span>
|
||||
} @else {
|
||||
<i class="pi pi-times-circle" style="color: var(--p-red-500);"></i>
|
||||
<span>{{ t('testConnection.failed') }}</span>
|
||||
}
|
||||
<span style="color: var(--p-text-muted-color); font-size: 0.75rem;">
|
||||
({{ testConnectionResult.checks.length }} {{ t('testConnection.checks') }})
|
||||
</span>
|
||||
<i class="pi pi-chevron-right toggle-chevron" [class.expanded]="showTestDetails"></i>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="provider-action-buttons">
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
[label]="t('testConnection.button')"
|
||||
[icon]="isTestingConnection ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
|
||||
severity="info"
|
||||
size="small"
|
||||
(click)="testConnection()"
|
||||
[disabled]="!oidcProvider.issuerUri || isTestingConnection">
|
||||
</p-button>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
[label]="'common.save' | transloco"
|
||||
icon="pi pi-save"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveOidcProvider()"
|
||||
[disabled]="!isOidcFormComplete()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
@if (testConnectionResult && showTestDetails) {
|
||||
<div class="test-results-details">
|
||||
@for (check of testConnectionResult.checks; track check.name) {
|
||||
<div class="test-check-row">
|
||||
@switch (check.status) {
|
||||
@case ('PASS') {
|
||||
<i class="pi pi-check-circle" style="color: var(--p-green-500);"></i>
|
||||
}
|
||||
@case ('FAIL') {
|
||||
<i class="pi pi-times-circle" style="color: var(--p-red-500);"></i>
|
||||
}
|
||||
@case ('WARN') {
|
||||
<i class="pi pi-exclamation-triangle" style="color: var(--p-yellow-500);"></i>
|
||||
}
|
||||
@case ('SKIP') {
|
||||
<i class="pi pi-minus-circle" style="color: var(--p-surface-400);"></i>
|
||||
}
|
||||
}
|
||||
<span class="check-name">{{ check.name }}</span>
|
||||
<span class="check-message">{{ check.message }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
{{ t('infoPanel.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('infoPanel.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="section-body">
|
||||
<div class="info-panel-grid">
|
||||
@for (item of infoItems; track item.labelKey) {
|
||||
<div class="info-panel-item">
|
||||
<span class="info-panel-label">{{ t(item.labelKey) }}</span>
|
||||
<div class="info-panel-value-row">
|
||||
<code class="info-panel-value">{{ item.value }}</code>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
icon="pi pi-copy"
|
||||
severity="secondary"
|
||||
size="small"
|
||||
[style]="{'min-width': '2rem'}"
|
||||
(click)="copyToClipboard(item.value)">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (oidcEnabled) {
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-ban"></i>
|
||||
{{ t('oidcOnly.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('oidcOnly.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="provisioning-toggle">
|
||||
<div class="toggle-content">
|
||||
<div class="toggle-info">
|
||||
<span class="toggle-label">{{ t('oidcOnly.label') }}</span>
|
||||
<span class="toggle-status" [class.active]="oidcForceOnlyMode">
|
||||
{{ oidcForceOnlyMode ? t('oidcOnly.enabled') : t('oidcOnly.disabled') }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="toggle-description">
|
||||
{{ t('oidcOnly.description') }}
|
||||
</p>
|
||||
@if (oidcForceOnlyMode) {
|
||||
<p class="toggle-description" style="color: var(--p-yellow-500); margin-top: 0.5rem;">
|
||||
<i class="pi pi-exclamation-triangle" style="margin-right: 0.25rem;"></i>
|
||||
{{ t('oidcOnly.backdoorHint') }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="oidcForceOnlyMode"
|
||||
(onChange)="toggleOidcForceOnlyMode()">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<div class="section-header-row">
|
||||
<div class="section-header-text">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-users"></i>
|
||||
{{ t('provisioning.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('provisioning.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="provisioning-toggle">
|
||||
<div class="toggle-content">
|
||||
<div class="toggle-info">
|
||||
<span class="toggle-label">{{ t('provisioning.autoLabel') }}</span>
|
||||
<span class="toggle-status" [class.active]="autoUserProvisioningEnabled">
|
||||
{{ autoUserProvisioningEnabled ? t('provisioning.autoEnabled') : t('provisioning.autoDisabled') }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="toggle-description">
|
||||
{{ t('provisioning.autoDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="autoUserProvisioningEnabled"
|
||||
inputId="autoProvision"
|
||||
(onChange)="saveOidcAutoProvisionSettings()">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
|
||||
<div class="provisioning-toggle">
|
||||
<div class="toggle-content">
|
||||
<div class="toggle-info">
|
||||
<span class="toggle-label">{{ t('provisioning.linkLocalLabel') }}</span>
|
||||
<span class="toggle-status" [class.active]="allowLocalAccountLinking">
|
||||
{{ allowLocalAccountLinking ? t('provisioning.autoEnabled') : t('provisioning.autoDisabled') }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="toggle-description">
|
||||
{{ t('provisioning.linkLocalDesc') }}
|
||||
</p>
|
||||
@if (allowLocalAccountLinking) {
|
||||
<p class="toggle-description" style="color: var(--p-yellow-500); margin-top: 0.5rem;">
|
||||
<i class="pi pi-exclamation-triangle" style="margin-right: 0.25rem;"></i>
|
||||
{{ t('provisioning.linkLocalWarning') }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="allowLocalAccountLinking"
|
||||
inputId="linkLocal"
|
||||
(onChange)="saveOidcAutoProvisionSettings()">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
|
||||
@if (autoUserProvisioningEnabled) {
|
||||
<div class="default-settings">
|
||||
<div class="permissions-group">
|
||||
<h4 class="group-title">{{ t('provisioning.defaultPerms') }}</h4>
|
||||
<div class="permissions-grid">
|
||||
<div class="permission-item">
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
[disabled]="true"
|
||||
[ngModel]="true"
|
||||
inputId="permissionRead">
|
||||
</p-checkbox>
|
||||
<label for="permissionRead">{{ t('provisioning.readBooks') }}</label>
|
||||
</div>
|
||||
@for (perm of availablePermissions; track perm) {
|
||||
<div class="permission-item">
|
||||
<p-checkbox
|
||||
[(ngModel)]="perm.selected"
|
||||
[binary]="true"
|
||||
[inputId]="perm.value">
|
||||
</p-checkbox>
|
||||
<label [for]="perm.value">{{ t(perm.translationKey) }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="libraries-group">
|
||||
<h4 class="group-title">{{ t('provisioning.defaultLibraryAccess') }}</h4>
|
||||
<div style="display: flex; align-items: center; gap: 0.5rem; justify-content: space-between;">
|
||||
<p-multiSelect
|
||||
[options]="allLibraries"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[(ngModel)]="editingLibraryIds"
|
||||
[placeholder]="t('provisioning.selectLibraries')"
|
||||
appendTo="body"
|
||||
class="libraries-select"
|
||||
style="flex: 1;">
|
||||
</p-multiSelect>
|
||||
<p-button
|
||||
icon="pi pi-save"
|
||||
[label]="'common.save' | transloco"
|
||||
[outlined]="true"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveOidcAutoProvisionSettings()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<div class="section-header-row">
|
||||
<div class="section-header-text">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-sitemap"></i>
|
||||
{{ t('groupMapping.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('groupMapping.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-plus"
|
||||
[label]="t('groupMapping.addMapping')"
|
||||
[outlined]="true"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="openNewGroupMapping()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="config-grid-2col" style="margin-bottom: 1rem;">
|
||||
<div class="config-item">
|
||||
<label for="groupSyncMode">{{ t('groupMapping.syncModeLabel') }}</label>
|
||||
<p-select
|
||||
inputId="groupSyncMode"
|
||||
[(ngModel)]="groupSyncMode"
|
||||
[options]="groupSyncModeOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
appendTo="body">
|
||||
</p-select>
|
||||
<span class="field-hint">{{ t('groupMapping.syncModeHint') }}</span>
|
||||
</div>
|
||||
<div class="config-item" style="display: flex; align-items: flex-end;">
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
[label]="'common.save' | transloco"
|
||||
icon="pi pi-save"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveGroupSyncMode()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (groupMappings.length > 0) {
|
||||
<p-table [value]="groupMappings" [tableStyle]="{'min-width': '100%'}" styleClass="p-datatable-sm">
|
||||
<ng-template #header>
|
||||
<tr>
|
||||
<th>{{ t('groupMapping.colGroupClaim') }}</th>
|
||||
<th>{{ t('groupMapping.colAdmin') }}</th>
|
||||
<th>{{ t('groupMapping.colPermissions') }}</th>
|
||||
<th>{{ t('groupMapping.colLibraries') }}</th>
|
||||
<th>{{ t('groupMapping.colDescription') }}</th>
|
||||
<th style="width: 8rem;"></th>
|
||||
</tr>
|
||||
</ng-template>
|
||||
<ng-template #body let-mapping>
|
||||
<tr>
|
||||
<td>{{ mapping.oidcGroupClaim }}</td>
|
||||
<td>
|
||||
@if (mapping.isAdmin) {
|
||||
<app-tag [rounded]="true" color="warning" size="2xs">Admin</app-tag>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@for (perm of mapping.permissions; track perm) {
|
||||
<app-tag [rounded]="true" color="info" size="2xs" style="margin-right: 0.25rem; margin-bottom: 0.25rem;">{{ perm }}</app-tag>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@for (libId of mapping.libraryIds; track libId) {
|
||||
<app-tag [rounded]="true" color="secondary" size="2xs" style="margin-right: 0.25rem; margin-bottom: 0.25rem;">{{ getLibraryName(libId) }}</app-tag>
|
||||
}
|
||||
</td>
|
||||
<td>{{ mapping.description }}</td>
|
||||
<td>
|
||||
<div style="display: flex; gap: 0.5rem;">
|
||||
<p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" size="small" (click)="openEditGroupMapping(mapping)"></p-button>
|
||||
<p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (click)="deleteGroupMapping(mapping)"></p-button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-dialog
|
||||
[header]="editingGroupMapping.id ? t('groupMapping.editTitle') : t('groupMapping.addTitle')"
|
||||
[(visible)]="showGroupMappingDialog"
|
||||
[modal]="true"
|
||||
[style]="{width: '550px', maxWidth: '95vw'}"
|
||||
[dismissableMask]="true">
|
||||
<div class="config-grid" style="gap: 1rem;">
|
||||
<div class="config-item full-width">
|
||||
<label for="gmGroupClaim">{{ t('groupMapping.groupClaimLabel') }}</label>
|
||||
<input pInputText id="gmGroupClaim" [(ngModel)]="editingGroupMapping.oidcGroupClaim" [placeholder]="t('groupMapping.groupClaimPlaceholder')"/>
|
||||
</div>
|
||||
<div class="config-item full-width">
|
||||
<label for="gmDescription">{{ t('groupMapping.descriptionLabel') }}</label>
|
||||
<input pInputText id="gmDescription" [(ngModel)]="editingGroupMapping.description" [placeholder]="t('groupMapping.descriptionPlaceholder')"/>
|
||||
</div>
|
||||
<div class="config-item full-width">
|
||||
<div class="provisioning-toggle" style="padding: 0;">
|
||||
<div class="toggle-content">
|
||||
<span class="toggle-label">{{ t('groupMapping.adminLabel') }}</span>
|
||||
</div>
|
||||
<p-toggleswitch [(ngModel)]="editingGroupMapping.isAdmin"></p-toggleswitch>
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-item full-width">
|
||||
<h4 class="group-title">{{ t('groupMapping.permissionsLabel') }}</h4>
|
||||
<div class="permissions-grid">
|
||||
<div class="permission-item">
|
||||
<p-checkbox [binary]="true" [disabled]="true" [ngModel]="true" inputId="gmPermRead"></p-checkbox>
|
||||
<label for="gmPermRead">{{ t('provisioning.readBooks') }}</label>
|
||||
</div>
|
||||
@for (perm of editingGroupMappingPerms; track perm) {
|
||||
<div class="permission-item">
|
||||
<p-checkbox [(ngModel)]="perm.selected" [binary]="true" [inputId]="'gm_' + perm.value"></p-checkbox>
|
||||
<label [for]="'gm_' + perm.value">{{ t(perm.translationKey) }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-item full-width">
|
||||
<h4 class="group-title">{{ t('groupMapping.librariesLabel') }}</h4>
|
||||
<p-multiSelect
|
||||
[options]="allLibraries"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[(ngModel)]="editingGroupMappingLibraryIds"
|
||||
[placeholder]="t('provisioning.selectLibraries')"
|
||||
appendTo="body"
|
||||
class="libraries-select">
|
||||
</p-multiSelect>
|
||||
</div>
|
||||
</div>
|
||||
<ng-template #footer>
|
||||
<p-button
|
||||
[label]="'common.save' | transloco"
|
||||
icon="pi pi-check"
|
||||
(click)="saveGroupMapping()"
|
||||
[disabled]="!editingGroupMapping.oidcGroupClaim">
|
||||
</p-button>
|
||||
</ng-template>
|
||||
</p-dialog>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
@use '../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.main-container {
|
||||
@include settings.settings-page-container;
|
||||
}
|
||||
|
||||
@include settings.settings-page-header;
|
||||
|
||||
.settings-title {
|
||||
@include settings.settings-page-title;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.settings-description {
|
||||
@include settings.settings-page-description;
|
||||
}
|
||||
|
||||
.settings-card {
|
||||
@include settings.settings-card;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
@include settings.settings-section-header;
|
||||
}
|
||||
|
||||
.section-header-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
p-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.section-header-text {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
@include settings.settings-section-title;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
@include settings.settings-section-description;
|
||||
}
|
||||
|
||||
.section-body {
|
||||
@include settings.settings-section-body;
|
||||
}
|
||||
|
||||
// Authentication Methods List
|
||||
.auth-methods-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.auth-method-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-left: 3px solid var(--p-content-border-color);
|
||||
border-radius: 6px;
|
||||
padding: 1rem;
|
||||
transition: border-color 0.2s ease, background 0.2s ease;
|
||||
|
||||
&:hover:not(.is-locked) {
|
||||
background: color-mix(in srgb, var(--ground-background) 40%, var(--p-surface-800) 60%);
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
border-left-color: var(--p-green-500);
|
||||
}
|
||||
|
||||
&.is-locked {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.auth-method-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.auth-method-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.auth-method-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
background: color-mix(in srgb, var(--p-primary-color) 15%, transparent);
|
||||
color: var(--p-primary-color);
|
||||
border-radius: 8px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.pi {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
&.oidc {
|
||||
background: color-mix(in srgb, var(--p-orange-500) 15%, transparent);
|
||||
color: var(--p-orange-500);
|
||||
}
|
||||
}
|
||||
|
||||
.auth-method-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.125rem;
|
||||
}
|
||||
|
||||
.auth-method-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-weight: 600;
|
||||
font-size: 0.9375rem;
|
||||
color: var(--p-text-color);
|
||||
}
|
||||
|
||||
|
||||
.auth-method-status {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-muted-color);
|
||||
|
||||
&.active {
|
||||
color: var(--p-green-400);
|
||||
}
|
||||
}
|
||||
|
||||
.auth-method-description {
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
padding-left: calc(36px + 0.75rem);
|
||||
|
||||
@media (max-width: 600px) {
|
||||
padding-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.config-hint {
|
||||
display: block;
|
||||
color: var(--p-orange-400);
|
||||
font-weight: 500;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
// Configuration Grid
|
||||
.config-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 0.75rem;
|
||||
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.config-grid-2col {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.75rem;
|
||||
|
||||
@media (max-width: 600px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.config-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.375rem;
|
||||
|
||||
&.full-width {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
&.span-2 {
|
||||
grid-column: span 2;
|
||||
|
||||
@media (max-width: 600px) {
|
||||
grid-column: span 1;
|
||||
}
|
||||
}
|
||||
|
||||
label {
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
// Claims Section
|
||||
.claims-section {
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px dashed var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.subsection-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.25rem 0;
|
||||
}
|
||||
|
||||
.subsection-description {
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.4;
|
||||
margin: 0 0 0.75rem 0;
|
||||
}
|
||||
|
||||
.claims-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 0.75rem;
|
||||
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
// Provider Actions Row
|
||||
.provider-actions-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px dashed var(--p-content-border-color);
|
||||
|
||||
@media (max-width: 600px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
|
||||
.test-results-inline {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.provider-action-buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// Test Connection Results
|
||||
.test-results-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.625rem 0.875rem;
|
||||
border-radius: 6px;
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--p-text-color);
|
||||
transition: background 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--ground-background) 40%, var(--p-surface-800) 60%);
|
||||
}
|
||||
|
||||
.toggle-chevron {
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
transition: transform 0.2s ease;
|
||||
margin-left: auto;
|
||||
|
||||
&.expanded {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.test-results-details {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
padding: 0.5rem 0.875rem 0.625rem;
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-top: none;
|
||||
border-radius: 0 0 6px 6px;
|
||||
background: color-mix(in srgb, var(--ground-background) 60%, var(--p-surface-800) 40%);
|
||||
}
|
||||
|
||||
.test-check-row {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.5rem;
|
||||
padding: 0.1875rem 0;
|
||||
font-size: 0.8125rem;
|
||||
|
||||
.check-name {
|
||||
font-weight: 500;
|
||||
color: var(--p-text-color);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.check-message {
|
||||
color: var(--p-text-muted-color);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pi {
|
||||
font-size: 0.8125rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Provisioning Toggle
|
||||
.provisioning-toggle {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-left: 3px solid var(--p-primary-color);
|
||||
border-radius: 6px;
|
||||
padding: 1rem;
|
||||
|
||||
@media (max-width: 600px) {
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.toggle-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toggle-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.125rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.toggle-label {
|
||||
font-weight: 600;
|
||||
font-size: 0.9375rem;
|
||||
color: var(--p-text-color);
|
||||
}
|
||||
|
||||
.toggle-status {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-muted-color);
|
||||
|
||||
&.active {
|
||||
color: var(--p-green-400);
|
||||
}
|
||||
}
|
||||
|
||||
.toggle-description {
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
// Default Settings (Permissions & Libraries)
|
||||
.default-settings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px dashed var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.permissions-group,
|
||||
.libraries-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.group-title {
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.permissions-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 0.625rem;
|
||||
padding-left: 0.5rem;
|
||||
}
|
||||
|
||||
.permission-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
label {
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-text-color);
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.libraries-select {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
// Info Panel
|
||||
.info-panel-grid {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.info-panel-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.info-panel-label {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-muted-color);
|
||||
}
|
||||
|
||||
.info-panel-value-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.info-panel-value {
|
||||
flex: 1;
|
||||
font-size: 0.8125rem;
|
||||
padding: 0.375rem 0.625rem;
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 4px;
|
||||
color: var(--p-text-color);
|
||||
word-break: break-all;
|
||||
}
|
||||
+426
@@ -0,0 +1,426 @@
|
||||
import {Component, effect, inject} from '@angular/core';
|
||||
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {ToggleSwitch} from 'primeng/toggleswitch';
|
||||
import {InputNumber} from 'primeng/inputnumber';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {AppSettingsService} from '../../../shared/service/app-settings.service';
|
||||
import {AppSettingKey, AppSettings, OidcProviderDetails, OidcTestResult} from '../../../shared/model/app-settings.model';
|
||||
import {MultiSelect} from 'primeng/multiselect';
|
||||
import {LibraryService} from '../../../features/book/service/library.service';
|
||||
import {ExternalDocLinkComponent} from '../../../shared/components/external-doc-link/external-doc-link.component';
|
||||
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {OidcGroupMapping} from '../../../shared/model/oidc-group-mapping.model';
|
||||
import {OidcGroupMappingService} from '../../../shared/service/oidc-group-mapping.service';
|
||||
import {Select} from 'primeng/select';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {Dialog} from 'primeng/dialog';
|
||||
import {TagComponent} from '../../../shared/components/tag/tag.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-authentication-settings',
|
||||
templateUrl: './authentication-settings.component.html',
|
||||
standalone: true,
|
||||
imports: [
|
||||
FormsModule,
|
||||
InputText,
|
||||
Checkbox,
|
||||
ToggleSwitch,
|
||||
Button,
|
||||
MultiSelect,
|
||||
InputNumber,
|
||||
ReactiveFormsModule,
|
||||
ExternalDocLinkComponent,
|
||||
TranslocoDirective,
|
||||
TranslocoPipe,
|
||||
Select,
|
||||
TableModule,
|
||||
Dialog,
|
||||
TagComponent
|
||||
],
|
||||
styleUrls: ['./authentication-settings.component.scss']
|
||||
})
|
||||
export class AuthenticationSettingsComponent {
|
||||
availablePermissions = [
|
||||
{label: 'Upload Books', value: 'permissionUpload', selected: false, translationKey: 'perms.uploadBooks'},
|
||||
{label: 'Download Books', value: 'permissionDownload', selected: false, translationKey: 'perms.downloadBooks'},
|
||||
{label: 'Edit Book Metadata', value: 'permissionEditMetadata', selected: false, translationKey: 'perms.editMetadata'},
|
||||
{label: 'Manage Library', value: 'permissionManipulateLibrary', selected: false, translationKey: 'perms.manageLibrary'},
|
||||
{label: 'Email Book', value: 'permissionEmailBook', selected: false, translationKey: 'perms.emailBook'},
|
||||
{label: 'Delete Book', value: 'permissionDeleteBook', selected: false, translationKey: 'perms.deleteBook'},
|
||||
{label: 'KOReader Sync', value: 'permissionSyncKoreader', selected: false, translationKey: 'perms.koreaderSync'},
|
||||
{label: 'Kobo Sync', value: 'permissionSyncKobo', selected: false, translationKey: 'perms.koboSync'},
|
||||
{label: 'Access OPDS', value: 'permissionAccessOpds', selected: false, translationKey: 'perms.accessOpds'}
|
||||
];
|
||||
|
||||
internalAuthEnabled = true;
|
||||
autoUserProvisioningEnabled = false;
|
||||
allowLocalAccountLinking = true;
|
||||
selectedPermissions: string[] = [];
|
||||
oidcEnabled = false;
|
||||
|
||||
editingLibraryIds: number[] = [];
|
||||
sessionDurationHours: number | null = null;
|
||||
backchannelLogoutUri = `${window.location.origin}/api/v1/auth/oidc/backchannel-logout`;
|
||||
oidcForceOnlyMode = false;
|
||||
|
||||
infoItems = [
|
||||
{labelKey: 'infoPanel.redirectUri', value: `${window.location.origin}/oauth2-callback`},
|
||||
{labelKey: 'infoPanel.postLogoutRedirectUri', value: `${window.location.origin}/login`},
|
||||
{labelKey: 'infoPanel.backChannelLogoutUri', value: `${window.location.origin}/api/v1/auth/oidc/backchannel-logout`},
|
||||
{labelKey: 'infoPanel.requiredScopes', value: 'openid profile email groups offline_access'},
|
||||
{labelKey: 'infoPanel.pkceMethod', value: 'S256'},
|
||||
{labelKey: 'infoPanel.grantType', value: 'Authorization Code'},
|
||||
];
|
||||
|
||||
// Test connection
|
||||
isTestingConnection = false;
|
||||
testConnectionResult: OidcTestResult | null = null;
|
||||
showTestDetails = false;
|
||||
|
||||
// Group mapping
|
||||
groupSyncMode: string = 'DISABLED';
|
||||
groupSyncModeOptions = [
|
||||
{label: 'Disabled', value: 'DISABLED'},
|
||||
{label: 'On Login (Replace)', value: 'ON_LOGIN'},
|
||||
{label: 'On Login (Additive)', value: 'ON_LOGIN_ADDITIVE'}
|
||||
];
|
||||
groupMappings: OidcGroupMapping[] = [];
|
||||
showGroupMappingDialog = false;
|
||||
editingGroupMapping: OidcGroupMapping = this.emptyGroupMapping();
|
||||
editingGroupMappingPerms: {label: string; value: string; selected: boolean; translationKey: string}[] = [];
|
||||
editingGroupMappingLibraryIds: number[] = [];
|
||||
|
||||
oidcProvider: OidcProviderDetails = {
|
||||
providerName: '',
|
||||
clientId: '',
|
||||
clientSecret: '',
|
||||
issuerUri: '',
|
||||
scopes: '',
|
||||
claimMapping: {
|
||||
username: '',
|
||||
email: '',
|
||||
name: '',
|
||||
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(); }
|
||||
|
||||
private readonly loadSettingsEffect = effect(() => {
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
if (settings) {
|
||||
this.loadSettings(settings);
|
||||
}
|
||||
});
|
||||
|
||||
loadSettings(settings: AppSettings): void {
|
||||
this.oidcEnabled = settings.oidcEnabled;
|
||||
|
||||
const details = settings.oidcAutoProvisionDetails;
|
||||
|
||||
this.autoUserProvisioningEnabled = details?.enableAutoProvisioning ?? false;
|
||||
this.allowLocalAccountLinking = details?.allowLocalAccountLinking ?? true;
|
||||
this.selectedPermissions = details?.defaultPermissions ?? [];
|
||||
this.editingLibraryIds = details?.defaultLibraryIds ?? [];
|
||||
|
||||
const defaultClaimMapping = {
|
||||
username: 'preferred_username',
|
||||
email: 'email',
|
||||
name: 'given_name',
|
||||
groups: ''
|
||||
};
|
||||
|
||||
this.sessionDurationHours = settings.oidcSessionDurationHours ?? null;
|
||||
this.groupSyncMode = settings.oidcGroupSyncMode ?? 'DISABLED';
|
||||
this.oidcForceOnlyMode = settings.oidcForceOnlyMode ?? false;
|
||||
|
||||
this.oidcProvider = {
|
||||
providerName: settings.oidcProviderDetails?.providerName || '',
|
||||
clientId: settings.oidcProviderDetails?.clientId || '',
|
||||
issuerUri: settings.oidcProviderDetails?.issuerUri || '',
|
||||
scopes: settings.oidcProviderDetails?.scopes || '',
|
||||
claimMapping: settings.oidcProviderDetails?.claimMapping || defaultClaimMapping
|
||||
};
|
||||
|
||||
this.availablePermissions.forEach(perm => {
|
||||
perm.selected = this.selectedPermissions.includes(perm.value);
|
||||
});
|
||||
|
||||
if (this.oidcEnabled) {
|
||||
this.loadGroupMappings();
|
||||
}
|
||||
}
|
||||
|
||||
isOidcFormComplete(): boolean {
|
||||
const p = this.oidcProvider;
|
||||
return !!(p.providerName && p.clientId && p.issuerUri && p.claimMapping.name && p.claimMapping.email && p.claimMapping.username);
|
||||
}
|
||||
|
||||
toggleOidcEnabled(): void {
|
||||
if (!this.isOidcFormComplete()) return;
|
||||
this.appSettingsService.toggleOidcEnabled(this.oidcEnabled).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.oidcUpdated')
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.oidcError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
saveOidcProvider(): void {
|
||||
const payload: {key: AppSettingKey; newValue: unknown}[] = [
|
||||
{
|
||||
key: AppSettingKey.OIDC_PROVIDER_DETAILS,
|
||||
newValue: this.oidcProvider
|
||||
}
|
||||
];
|
||||
if (this.oidcEnabled) {
|
||||
payload.push({
|
||||
key: AppSettingKey.OIDC_SESSION_DURATION_HOURS,
|
||||
newValue: this.sessionDurationHours
|
||||
});
|
||||
}
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.providerSaved')
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.providerError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
copyBackchannelUri(): void {
|
||||
this.copyToClipboard(this.backchannelLogoutUri);
|
||||
}
|
||||
|
||||
copyToClipboard(value: string): void {
|
||||
navigator.clipboard.writeText(value).then(() => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.copiedToClipboard')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
saveSessionDuration(): void {
|
||||
const payload = [
|
||||
{
|
||||
key: AppSettingKey.OIDC_SESSION_DURATION_HOURS,
|
||||
newValue: this.sessionDurationHours
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.sessionDurationSaved')
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.sessionDurationError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
saveOidcAutoProvisionSettings(): void {
|
||||
const provisionDetails = {
|
||||
enableAutoProvisioning: this.autoUserProvisioningEnabled,
|
||||
allowLocalAccountLinking: this.allowLocalAccountLinking,
|
||||
defaultPermissions: [
|
||||
'permissionRead',
|
||||
...this.availablePermissions.filter(p => p.selected).map(p => p.value)
|
||||
],
|
||||
defaultLibraryIds: this.editingLibraryIds
|
||||
};
|
||||
|
||||
const payload = [
|
||||
{
|
||||
key: AppSettingKey.OIDC_AUTO_PROVISION_DETAILS,
|
||||
newValue: provisionDetails
|
||||
}
|
||||
];
|
||||
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.provisionSaved')
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.provisionError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// Group mapping methods
|
||||
loadGroupMappings(): void {
|
||||
this.groupMappingService.getAll().subscribe(mappings => this.groupMappings = mappings);
|
||||
}
|
||||
|
||||
saveGroupSyncMode(): void {
|
||||
const payload = [
|
||||
{
|
||||
key: AppSettingKey.OIDC_GROUP_SYNC_MODE,
|
||||
newValue: this.groupSyncMode
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.syncModeSaved')
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.syncModeError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
openNewGroupMapping(): void {
|
||||
this.editingGroupMapping = this.emptyGroupMapping();
|
||||
this.initGroupMappingPerms([]);
|
||||
this.editingGroupMappingLibraryIds = [];
|
||||
this.showGroupMappingDialog = true;
|
||||
}
|
||||
|
||||
openEditGroupMapping(mapping: OidcGroupMapping): void {
|
||||
this.editingGroupMapping = {...mapping};
|
||||
this.initGroupMappingPerms(mapping.permissions);
|
||||
this.editingGroupMappingLibraryIds = [...mapping.libraryIds];
|
||||
this.showGroupMappingDialog = true;
|
||||
}
|
||||
|
||||
private initGroupMappingPerms(selectedPerms: string[]): void {
|
||||
this.editingGroupMappingPerms = this.availablePermissions.map(p => ({
|
||||
...p,
|
||||
selected: selectedPerms.includes(p.value)
|
||||
}));
|
||||
}
|
||||
|
||||
saveGroupMapping(): void {
|
||||
const mapping: OidcGroupMapping = {
|
||||
...this.editingGroupMapping,
|
||||
permissions: [
|
||||
'permissionRead',
|
||||
...this.editingGroupMappingPerms.filter(p => p.selected).map(p => p.value)
|
||||
],
|
||||
libraryIds: this.editingGroupMappingLibraryIds
|
||||
};
|
||||
|
||||
const obs = mapping.id
|
||||
? this.groupMappingService.update(mapping.id, mapping)
|
||||
: this.groupMappingService.create(mapping);
|
||||
|
||||
obs.subscribe({
|
||||
next: () => {
|
||||
this.showGroupMappingDialog = false;
|
||||
this.loadGroupMappings();
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.groupMappingSaved')
|
||||
});
|
||||
},
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.groupMappingError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
deleteGroupMapping(mapping: OidcGroupMapping): void {
|
||||
if (!mapping.id) return;
|
||||
this.groupMappingService.delete(mapping.id).subscribe({
|
||||
next: () => {
|
||||
this.loadGroupMappings();
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.groupMappingDeleted')
|
||||
});
|
||||
},
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.groupMappingError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
getLibraryName(id: number): string {
|
||||
return this.allLibraries.find(l => l.id === id)?.name ?? `#${id}`;
|
||||
}
|
||||
|
||||
testConnection(): void {
|
||||
this.isTestingConnection = true;
|
||||
this.testConnectionResult = null;
|
||||
this.appSettingsService.testOidcConnection(this.oidcProvider).subscribe({
|
||||
next: (result) => {
|
||||
this.testConnectionResult = result;
|
||||
this.showTestDetails = true;
|
||||
this.isTestingConnection = false;
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.testConnection.error')
|
||||
});
|
||||
this.isTestingConnection = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
toggleOidcForceOnlyMode(): void {
|
||||
const payload = [
|
||||
{
|
||||
key: AppSettingKey.OIDC_FORCE_ONLY_MODE,
|
||||
newValue: this.oidcForceOnlyMode
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.oidcOnly.saved')
|
||||
}),
|
||||
error: (err) => {
|
||||
this.oidcForceOnlyMode = !this.oidcForceOnlyMode;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: err?.error?.message || this.t.translate('settingsAuth.oidcOnly.error')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private emptyGroupMapping(): OidcGroupMapping {
|
||||
return {oidcGroupClaim: '', isAdmin: false, permissions: [], libraryIds: [], description: ''};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<div class="oidc-callback-loading">
|
||||
<i class="pi pi-spin pi-spinner"></i>
|
||||
<span>{{ 'auth.oidc.signingIn' | transloco }}</span>
|
||||
</div>
|
||||
@@ -0,0 +1,18 @@
|
||||
.oidc-callback-loading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
gap: 1rem;
|
||||
color: var(--text-color);
|
||||
background: var(--ground-background);
|
||||
|
||||
i {
|
||||
font-size: 2.5rem;
|
||||
}
|
||||
|
||||
span {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
import {TranslocoPipe} from '@jsverse/transloco';
|
||||
import {OidcService} from '../oidc.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-oidc-callback',
|
||||
templateUrl: './oidc-callback.component.html',
|
||||
styleUrls: ['./oidc-callback.component.scss'],
|
||||
imports: [TranslocoPipe]
|
||||
})
|
||||
export class OidcCallbackComponent implements OnInit {
|
||||
private router = inject(Router);
|
||||
private oidcService = inject(OidcService);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
ngOnInit(): void {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
|
||||
const error = params.get('error');
|
||||
if (error) {
|
||||
const description = params.get('error_description') || error;
|
||||
console.error('[OIDC Callback] Provider returned error:', error, description);
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: description}});
|
||||
return;
|
||||
}
|
||||
|
||||
const code = params.get('code');
|
||||
const returnedState = params.get('state');
|
||||
|
||||
if (!code || !returnedState) {
|
||||
console.error('[OIDC Callback] Missing code or state');
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: 'missing_code'}});
|
||||
return;
|
||||
}
|
||||
|
||||
const pkceState = this.oidcService.retrievePkceState(returnedState);
|
||||
if (!pkceState) {
|
||||
console.error('[OIDC Callback] No PKCE state found for state parameter');
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: 'missing_pkce_state'}});
|
||||
return;
|
||||
}
|
||||
|
||||
if (returnedState !== pkceState.state) {
|
||||
console.error('[OIDC Callback] State mismatch');
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: 'state_mismatch'}});
|
||||
return;
|
||||
}
|
||||
|
||||
this.oidcService.exchangeCode(code, pkceState.codeVerifier, pkceState.nonce, pkceState.state).subscribe({
|
||||
next: (response) => {
|
||||
sessionStorage.removeItem('oidc_redirect_count');
|
||||
this.authService.saveInternalTokens(response.accessToken, response.refreshToken);
|
||||
this.authService.initializeWebSocketConnection();
|
||||
if (response.isDefaultPassword === 'true') {
|
||||
this.router.navigate(['/change-password']);
|
||||
} else {
|
||||
this.router.navigate(['/dashboard']);
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
console.error('[OIDC Callback] Token exchange failed', err);
|
||||
const errorMsg = err.error?.message || 'exchange_failed';
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: errorMsg}});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {firstValueFrom, Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
import {AppSettingsService, PublicAppSettings} from '../../shared/service/app-settings.service';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
|
||||
interface OidcPkceState {
|
||||
codeVerifier: string;
|
||||
state: string;
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
interface OidcTokenResponse {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
isDefaultPassword: string;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class OidcService {
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
|
||||
async generatePkce(): Promise<{codeVerifier: string; codeChallenge: string}> {
|
||||
const array = new Uint8Array(32);
|
||||
crypto.getRandomValues(array);
|
||||
const codeVerifier = this.base64UrlEncode(array);
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const hash = await crypto.subtle.digest('SHA-256', encoder.encode(codeVerifier));
|
||||
const codeChallenge = this.base64UrlEncode(new Uint8Array(hash));
|
||||
|
||||
return {codeVerifier, codeChallenge};
|
||||
}
|
||||
|
||||
generateRandomString(): string {
|
||||
const array = new Uint8Array(32);
|
||||
crypto.getRandomValues(array);
|
||||
return this.base64UrlEncode(array);
|
||||
}
|
||||
|
||||
buildAuthUrl(
|
||||
issuerUri: string,
|
||||
clientId: string,
|
||||
codeChallenge: string,
|
||||
state: string,
|
||||
nonce: string,
|
||||
authorizationEndpoint?: string,
|
||||
scopes?: string
|
||||
): Promise<string> {
|
||||
const redirectUri = `${window.location.origin}/oauth2-callback`;
|
||||
const scope = scopes?.trim() || 'openid profile email groups offline_access';
|
||||
|
||||
if (authorizationEndpoint) {
|
||||
return Promise.resolve(this.buildUrl(authorizationEndpoint, clientId, redirectUri, scope, codeChallenge, state, nonce));
|
||||
}
|
||||
|
||||
// Fetch from discovery if authorization_endpoint not provided
|
||||
return fetch(`${issuerUri.replace(/\/+$/, '')}/.well-known/openid-configuration`)
|
||||
.then(res => res.json())
|
||||
.then(doc => {
|
||||
const endpoint = doc.authorization_endpoint;
|
||||
if (!endpoint) {
|
||||
throw new Error('authorization_endpoint not found in discovery document');
|
||||
}
|
||||
return this.buildUrl(endpoint, clientId, redirectUri, scope, codeChallenge, state, nonce);
|
||||
});
|
||||
}
|
||||
|
||||
async fetchState(): Promise<string> {
|
||||
const response = await firstValueFrom(
|
||||
this.http.get<{state: string}>(`${API_CONFIG.BASE_URL}/api/v1/auth/oidc/state`)
|
||||
);
|
||||
return response.state;
|
||||
}
|
||||
|
||||
exchangeCode(code: string, codeVerifier: string, nonce: string, state: string): Observable<OidcTokenResponse> {
|
||||
const redirectUri = `${window.location.origin}/oauth2-callback`;
|
||||
return this.http.post<OidcTokenResponse>(`${API_CONFIG.BASE_URL}/api/v1/auth/oidc/callback`, {
|
||||
code,
|
||||
codeVerifier,
|
||||
redirectUri,
|
||||
nonce,
|
||||
state
|
||||
});
|
||||
}
|
||||
|
||||
storePkceState(pkceState: OidcPkceState): void {
|
||||
sessionStorage.setItem(`oidc_pkce_${pkceState.state}`, JSON.stringify(pkceState));
|
||||
}
|
||||
|
||||
retrievePkceState(state: string): OidcPkceState | null {
|
||||
const key = `oidc_pkce_${state}`;
|
||||
const stored = sessionStorage.getItem(key);
|
||||
sessionStorage.removeItem(key);
|
||||
if (!stored) return null;
|
||||
try {
|
||||
return JSON.parse(stored);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private buildUrl(
|
||||
endpoint: string,
|
||||
clientId: string,
|
||||
redirectUri: string,
|
||||
scope: string,
|
||||
codeChallenge: string,
|
||||
state: string,
|
||||
nonce: string
|
||||
): string {
|
||||
const params = new URLSearchParams({
|
||||
response_type: 'code',
|
||||
client_id: clientId,
|
||||
redirect_uri: redirectUri,
|
||||
scope,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
state,
|
||||
nonce,
|
||||
});
|
||||
return `${endpoint}?${params.toString()}`;
|
||||
}
|
||||
|
||||
private base64UrlEncode(bytes: Uint8Array): string {
|
||||
let binary = '';
|
||||
for (const byte of bytes) {
|
||||
binary += String.fromCharCode(byte);
|
||||
}
|
||||
return btoa(binary)
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Pipe, PipeTransform } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
@Pipe({
|
||||
name: 'secure',
|
||||
pure: true
|
||||
})
|
||||
export class SecurePipe implements PipeTransform {
|
||||
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {}
|
||||
|
||||
transform(url: string): Observable<SafeUrl> {
|
||||
return this.http.get(url, { responseType: 'blob' }).pipe(
|
||||
map(blob => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(blob)))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Directive, ElementRef, Input, OnChanges, OnDestroy, inject, SimpleChanges } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Subscription } from 'rxjs';
|
||||
|
||||
@Directive({
|
||||
selector: '[appSecureSrc]',
|
||||
standalone: true
|
||||
})
|
||||
export class SecureSrcDirective implements OnChanges, OnDestroy {
|
||||
@Input('appSecureSrc') src!: string;
|
||||
|
||||
private currentUrl: string | null = null;
|
||||
private subscription: Subscription | null = null;
|
||||
|
||||
private el = inject(ElementRef);
|
||||
private http = inject(HttpClient);
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['src']) {
|
||||
this.loadImage();
|
||||
}
|
||||
}
|
||||
|
||||
private loadImage(): void {
|
||||
this.cleanup();
|
||||
|
||||
if (!this.src) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.subscription = this.http.get(this.src, { responseType: 'blob' }).subscribe({
|
||||
next: (blob) => {
|
||||
this.currentUrl = URL.createObjectURL(blob);
|
||||
this.el.nativeElement.src = this.currentUrl;
|
||||
},
|
||||
error: (err) => {
|
||||
// Only log non-CORS errors to avoid console spam
|
||||
// CORS errors are expected in development and will be resolved by backend CORS config
|
||||
if (err.status !== 0 && err.status !== 403) {
|
||||
console.error('Error loading secure image:', err);
|
||||
}
|
||||
// Set a fallback placeholder image if available
|
||||
const fallbackSrc = this.el.nativeElement.getAttribute('data-fallback-src') || 'assets/images/missing-cover.jpg';
|
||||
this.el.nativeElement.src = fallbackSrc;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
if (this.subscription) {
|
||||
this.subscription.unsubscribe();
|
||||
this.subscription = null;
|
||||
}
|
||||
if (this.currentUrl) {
|
||||
URL.revokeObjectURL(this.currentUrl);
|
||||
this.currentUrl = null;
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.cleanup();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class LoadingService {
|
||||
private activeLoaders: HTMLElement[] = [];
|
||||
|
||||
show(message: string = 'Loading...'): HTMLElement {
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'fullscreen-loader';
|
||||
loader.innerHTML = `
|
||||
<div class="loader-content">
|
||||
<i class="pi pi-spin pi-spinner" style="font-size: 3rem; color: var(--primary-color);"></i>
|
||||
<p style="margin-top: 1rem; color: var(--text-color);">${message}</p>
|
||||
</div>
|
||||
`;
|
||||
loader.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 9999;
|
||||
backdrop-filter: blur(4px);
|
||||
`;
|
||||
|
||||
const content = loader.querySelector('.loader-content') as HTMLElement;
|
||||
if (content) {
|
||||
content.style.cssText = `
|
||||
text-align: center;
|
||||
background: var(--surface-card);
|
||||
padding: 2rem;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
|
||||
`;
|
||||
}
|
||||
|
||||
document.body.appendChild(loader);
|
||||
document.body.style.cursor = 'wait';
|
||||
this.activeLoaders.push(loader);
|
||||
|
||||
return loader;
|
||||
}
|
||||
|
||||
hide(loader: HTMLElement): void {
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
|
||||
const index = this.activeLoaders.indexOf(loader);
|
||||
if (index > -1) {
|
||||
this.activeLoaders.splice(index, 1);
|
||||
}
|
||||
|
||||
if (this.activeLoaders.length === 0) {
|
||||
document.body.style.cursor = 'default';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hideAll(): void {
|
||||
this.activeLoaders.forEach(loader => {
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
});
|
||||
this.activeLoaders = [];
|
||||
document.body.style.cursor = 'default';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Observable, of} from 'rxjs';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class PostLoginInitializerService {
|
||||
|
||||
initialize(): Observable<void> {
|
||||
return of(undefined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import {TranslocoTestingModule, TranslocoTestingOptions} from '@jsverse/transloco';
|
||||
import {EN_TRANSLATIONS} from '../config/transloco-loader';
|
||||
|
||||
export function getTranslocoModule(options: TranslocoTestingOptions = {}) {
|
||||
return TranslocoTestingModule.forRoot({
|
||||
langs: {en: EN_TRANSLATIONS, ...options.langs},
|
||||
translocoConfig: {
|
||||
availableLangs: ['en'],
|
||||
defaultLang: 'en',
|
||||
...options.translocoConfig,
|
||||
},
|
||||
...options,
|
||||
});
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
<ng-container *transloco="let t; prefix: 'authorBrowser'">
|
||||
@if (loading()) {
|
||||
<div class="loading-state">
|
||||
<p-progressSpinner
|
||||
[style]="{'width': '60px', 'height': '60px'}"
|
||||
strokeWidth="3"
|
||||
fill="transparent"
|
||||
animationDuration="1.5s">
|
||||
</p-progressSpinner>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!loading()) {
|
||||
<div class="browse-header">
|
||||
<h2 class="browse-title">{{ t('browseAllAuthors') }}</h2>
|
||||
|
||||
<div class="browse-controls">
|
||||
<div class="search-wrapper">
|
||||
<i class="pi pi-search search-icon"></i>
|
||||
<input
|
||||
pInputText
|
||||
type="text"
|
||||
[placeholder]="t('searchPlaceholder')"
|
||||
[ngModel]="searchTerm()"
|
||||
(ngModelChange)="onSearchChange($event)"
|
||||
class="search-input"/>
|
||||
</div>
|
||||
|
||||
<div class="filter-sort-wrapper">
|
||||
<p-select
|
||||
[options]="sortOptions"
|
||||
[ngModel]="sortBy()"
|
||||
(ngModelChange)="onSortChange($event)"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="sort-dropdown">
|
||||
</p-select>
|
||||
|
||||
<button class="sort-direction-btn" (click)="toggleSortDirection()">
|
||||
<i class="pi" [class.pi-arrow-up]="sortDirection() === 'asc'" [class.pi-arrow-down]="sortDirection() === 'desc'"></i>
|
||||
</button>
|
||||
|
||||
<button class="filter-btn" (click)="filterPopover.toggle($event)">
|
||||
<i class="pi pi-filter"></i>
|
||||
@if (activeFilterCount() > 0) {
|
||||
<span class="filter-badge"></span>
|
||||
}
|
||||
</button>
|
||||
|
||||
@if (!isMobile) {
|
||||
<button class="display-settings-btn" (click)="displaySettingsPopover.toggle($event)">
|
||||
<i class="pi pi-sliders-h"></i>
|
||||
</button>
|
||||
<p-popover #displaySettingsPopover>
|
||||
<div class="display-settings-content">
|
||||
<label class="display-settings-label">{{ t('cardSize') }}</label>
|
||||
<p-slider
|
||||
[ngModel]="authorScaleService.scaleFactor()"
|
||||
(ngModelChange)="authorScaleService.setScale($event)"
|
||||
[min]="0.7"
|
||||
[max]="1.3"
|
||||
[step]="0.01"
|
||||
[style]="{ width: '100%' }">
|
||||
</p-slider>
|
||||
<div class="scale-value-display">
|
||||
{{ authorScaleService.scaleFactor().toFixed(2) }}x
|
||||
</div>
|
||||
</div>
|
||||
</p-popover>
|
||||
}
|
||||
|
||||
<p-popover #filterPopover>
|
||||
<div class="filter-popover-content">
|
||||
<div class="filter-group">
|
||||
<label class="filter-label">{{ t('filters.matchStatus') }}</label>
|
||||
<p-select
|
||||
[options]="[
|
||||
{label: t('filters.all'), value: 'all'},
|
||||
{label: t('filters.matched'), value: 'matched'},
|
||||
{label: t('filters.unmatched'), value: 'unmatched'}
|
||||
]"
|
||||
[ngModel]="filters().matchStatus"
|
||||
(ngModelChange)="onFilterChange('matchStatus', $event)"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="filter-dropdown">
|
||||
</p-select>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<label class="filter-label">{{ t('filters.photoStatus') }}</label>
|
||||
<p-select
|
||||
[options]="[
|
||||
{label: t('filters.all'), value: 'all'},
|
||||
{label: t('filters.hasPhoto'), value: 'has-photo'},
|
||||
{label: t('filters.noPhoto'), value: 'no-photo'}
|
||||
]"
|
||||
[ngModel]="filters().photoStatus"
|
||||
(ngModelChange)="onFilterChange('photoStatus', $event)"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="filter-dropdown">
|
||||
</p-select>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<label class="filter-label">{{ t('filters.readStatus') }}</label>
|
||||
<p-select
|
||||
[options]="[
|
||||
{label: t('filters.all'), value: 'all'},
|
||||
{label: t('filters.allRead'), value: 'all-read'},
|
||||
{label: t('filters.someRead'), value: 'some-read'},
|
||||
{label: t('filters.inProgress'), value: 'in-progress'},
|
||||
{label: t('filters.unread'), value: 'unread'}
|
||||
]"
|
||||
[ngModel]="filters().readStatus"
|
||||
(ngModelChange)="onFilterChange('readStatus', $event)"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="filter-dropdown">
|
||||
</p-select>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<label class="filter-label">{{ t('filters.bookCount') }}</label>
|
||||
<p-select
|
||||
[options]="[
|
||||
{label: t('filters.all'), value: 'all'},
|
||||
{label: '0', value: '0'},
|
||||
{label: '1', value: '1'},
|
||||
{label: '2', value: '2'},
|
||||
{label: '3', value: '3'},
|
||||
{label: '4', value: '4'},
|
||||
{label: '5', value: '5'},
|
||||
{label: '6-10', value: '6-10'},
|
||||
{label: '11-20', value: '11-20'},
|
||||
{label: '21-35', value: '21-35'},
|
||||
{label: '36+', value: '36+'}
|
||||
]"
|
||||
[ngModel]="filters().bookCount"
|
||||
(ngModelChange)="onFilterChange('bookCount', $event)"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="filter-dropdown">
|
||||
</p-select>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<label class="filter-label">{{ t('filters.library') }}</label>
|
||||
<p-select
|
||||
[options]="libraryOptions()"
|
||||
[ngModel]="filters().library"
|
||||
(ngModelChange)="onFilterChange('library', $event)"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="filter-dropdown">
|
||||
</p-select>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<label class="filter-label">{{ t('filters.genre') }}</label>
|
||||
<p-select
|
||||
[options]="genreOptions()"
|
||||
[ngModel]="filters().genre"
|
||||
(ngModelChange)="onFilterChange('genre', $event)"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="filter-dropdown">
|
||||
</p-select>
|
||||
</div>
|
||||
|
||||
@if (activeFilterCount() > 0) {
|
||||
<p-button
|
||||
[label]="t('filters.reset')"
|
||||
icon="pi pi-filter-slash"
|
||||
severity="secondary"
|
||||
[outlined]="true"
|
||||
size="small"
|
||||
(onClick)="resetFilters()"
|
||||
class="filter-reset-btn">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (filteredAuthors(); as authorList) {
|
||||
@if (authorList.length === 0) {
|
||||
<div class="empty-state">
|
||||
<i class="pi pi-users empty-icon"></i>
|
||||
<p>{{ t('noAuthorsFound') }}</p>
|
||||
</div>
|
||||
} @else {
|
||||
<virtual-scroller
|
||||
#scroll
|
||||
[items]="authorList"
|
||||
class="virtual-scroller">
|
||||
<div class="author-grid"
|
||||
#container
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
||||
@for (author of scroll.viewPortItems; track author.id; let i = $index) {
|
||||
<div class="virtual-scroller-item"
|
||||
[ngStyle]="{width: cardWidth + 'px', height: cardHeight + 'px'}"
|
||||
[style.--card-scale]="authorScaleService.scaleFactor()">
|
||||
<app-author-card
|
||||
[author]="author"
|
||||
[index]="authorList.indexOf(author)"
|
||||
[cacheBuster]="thumbnailCacheBusters.get(author.id) || 0"
|
||||
[canQuickMatch]="canEditMetadata"
|
||||
[canDelete]="canDeleteBook"
|
||||
[isCheckboxEnabled]="canEditMetadata || canDeleteBook"
|
||||
[isSelected]="isAuthorSelected(author.id)"
|
||||
(cardClick)="navigateToAuthor($event)"
|
||||
(viewAuthor)="navigateToAuthor($event)"
|
||||
(editAuthor)="navigateToAuthorEdit($event)"
|
||||
(deleteAuthor)="deleteAuthor($event)"
|
||||
(quickMatched)="onAuthorQuickMatched($event)"
|
||||
(checkboxClick)="onCheckboxClicked($event)">
|
||||
</app-author-card>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</virtual-scroller>
|
||||
}
|
||||
}
|
||||
|
||||
@if (currentUser(); as user) {
|
||||
<div class="author-browser-footer" [class.footer-hidden]="selectedCount() === 0">
|
||||
<div class="footer-content">
|
||||
<div class="selected-count-badge">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
<span class="selected-count">{{ selectedCount() }}</span>
|
||||
<span class="selected-label">{{ t('footer.selected') }}</span>
|
||||
</div>
|
||||
@if (canEditMetadata || canDeleteBook) {
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<div class="action-buttons-group">
|
||||
@if (canEditMetadata) {
|
||||
<p-button
|
||||
icon="pi pi-bolt"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
(onClick)="autoMatchSelected()"
|
||||
[pTooltip]="t('footer.autoMatch')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (canDeleteBook) {
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
outlined="true"
|
||||
severity="danger"
|
||||
(onClick)="deleteSelected()"
|
||||
[pTooltip]="t('footer.deleteSelected')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<div class="action-buttons-group">
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-check-square"
|
||||
severity="success"
|
||||
(click)="selectAllAuthors()"
|
||||
[pTooltip]="t('footer.selectAll')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-times"
|
||||
severity="warn"
|
||||
(click)="deselectAllAuthors()"
|
||||
[pTooltip]="t('footer.deselectAll')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</ng-container>
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
.loading-state {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: calc(100dvh - 6.7rem);
|
||||
}
|
||||
|
||||
.browse-header {
|
||||
padding: 0.75rem 1rem 0;
|
||||
}
|
||||
|
||||
.browse-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 800;
|
||||
margin-bottom: 0.75rem;
|
||||
background: linear-gradient(135deg, #ffffff, #e2e8f0, #3b82f6);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.browse-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.search-wrapper {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
max-width: 400px;
|
||||
|
||||
.search-icon {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
color: #94a3b8;
|
||||
font-size: 0.9rem;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 100%;
|
||||
padding-left: 2.25rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-sort-wrapper {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.sort-dropdown,
|
||||
.filter-dropdown {
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
.display-settings-btn,
|
||||
.filter-btn,
|
||||
.sort-direction-btn {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid color-mix(in srgb, var(--p-surface-500), transparent 50%);
|
||||
background: color-mix(in srgb, var(--p-surface-700), transparent 30%);
|
||||
color: #94a3b8;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: #e2e8f0;
|
||||
border-color: var(--p-primary-400);
|
||||
}
|
||||
}
|
||||
|
||||
.filter-badge {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--p-primary-400);
|
||||
}
|
||||
|
||||
.display-settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
.display-settings-label {
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
.scale-value-display {
|
||||
text-align: center;
|
||||
font-size: 0.8rem;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.filter-popover-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.filter-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.filter-label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.filter-reset-btn {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.virtual-scroller {
|
||||
width: 100%;
|
||||
height: calc(100dvh - 12.5rem);
|
||||
padding: 1rem;
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--primary-color) rgba(20, 20, 30, 0.5);
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 12px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: rgba(20, 20, 30, 0.5);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
height: calc(100dvh - 13rem);
|
||||
padding: 0.5rem;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.author-grid {
|
||||
display: grid;
|
||||
gap: 1.25rem;
|
||||
align-items: start;
|
||||
justify-items: center;
|
||||
width: 100%;
|
||||
padding-top: 1rem;
|
||||
padding-right: 1rem;
|
||||
padding-left: 1rem;
|
||||
}
|
||||
|
||||
.virtual-scroller-item {
|
||||
position: relative;
|
||||
overflow: visible;
|
||||
transition: width 0.2s ease, height 0.2s ease;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 4rem 2rem;
|
||||
text-align: center;
|
||||
|
||||
.empty-icon {
|
||||
font-size: 3rem;
|
||||
color: #64748b;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
p {
|
||||
color: #94a3b8;
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.author-browser-footer {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 1rem 0.5rem 0.5rem;
|
||||
z-index: 1;
|
||||
border-radius: 10px 10px 0 0;
|
||||
border: 1px solid rgba(255, 255, 255, 0.5);
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
background: rgba(0, 0, 0, 0.65);
|
||||
transition: transform 0.1s ease, opacity 0.1s ease;
|
||||
|
||||
&.footer-hidden {
|
||||
transform: translateX(-50%) translateY(100%);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
> .footer-content {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
max-width: 100%;
|
||||
left: 0;
|
||||
right: 0;
|
||||
transform: none;
|
||||
|
||||
&.footer-hidden {
|
||||
transform: translateY(100%);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.footer-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 0.75rem;
|
||||
}
|
||||
|
||||
.selected-count-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.9rem;
|
||||
color: #e4e4e7;
|
||||
|
||||
i {
|
||||
font-size: 1rem;
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.selected-count {
|
||||
font-weight: 700;
|
||||
font-size: 1rem;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.selected-label {
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
|
||||
.action-buttons-group {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
gap: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.browse-header {
|
||||
padding: 0.5rem 0.5rem 0;
|
||||
}
|
||||
|
||||
.browse-controls {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.search-wrapper {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.filter-sort-wrapper {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sort-dropdown {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
+582
@@ -0,0 +1,582 @@
|
||||
import {Component, computed, DestroyRef, effect, HostListener, inject, OnInit, signal, ViewChild} from '@angular/core';
|
||||
import {NgStyle} from '@angular/common';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||
import {filter} from 'rxjs/operators';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Select} from 'primeng/select';
|
||||
import {Slider} from 'primeng/slider';
|
||||
import {Popover} from 'primeng/popover';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {VirtualScrollerComponent, VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
|
||||
import {BookBrowserScrollService} from '../../../book/components/book-browser/book-browser-scroll.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorSummary, EnrichedAuthor, AuthorFilters, DEFAULT_AUTHOR_FILTERS} from '../../model/author.model';
|
||||
import {AuthorCardComponent} from '../author-card/author-card.component';
|
||||
import {AuthorScalePreferenceService} from '../../service/author-scale-preference.service';
|
||||
import {AuthorSelectionService, AuthorCheckboxClickEvent} from '../../service/author-selection.service';
|
||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book, ReadStatus} from '../../../book/model/book.model';
|
||||
|
||||
type SortDirection = 'asc' | 'desc';
|
||||
|
||||
interface SortOption {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface FilterOption {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SORT_DIRECTIONS: Record<string, SortDirection> = {
|
||||
'name': 'asc',
|
||||
'book-count': 'desc',
|
||||
'matched': 'desc',
|
||||
'recently-added': 'desc',
|
||||
'recently-read': 'desc',
|
||||
'reading-progress': 'desc',
|
||||
'avg-rating': 'desc',
|
||||
'photo': 'desc',
|
||||
'series-count': 'desc'
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-author-browser',
|
||||
standalone: true,
|
||||
templateUrl: './author-browser.component.html',
|
||||
styleUrls: ['./author-browser.component.scss'],
|
||||
imports: [
|
||||
NgStyle,
|
||||
FormsModule,
|
||||
ProgressSpinner,
|
||||
InputText,
|
||||
Select,
|
||||
Slider,
|
||||
Popover,
|
||||
Button,
|
||||
Divider,
|
||||
Tooltip,
|
||||
TranslocoDirective,
|
||||
AuthorCardComponent,
|
||||
VirtualScrollerModule
|
||||
]
|
||||
})
|
||||
export class AuthorBrowserComponent implements OnInit {
|
||||
|
||||
private static readonly BASE_WIDTH = 165;
|
||||
private static readonly BASE_HEIGHT = 290;
|
||||
private static readonly MOBILE_BASE_WIDTH = 140;
|
||||
private static readonly MOBILE_BASE_HEIGHT = 250;
|
||||
|
||||
private authorService = inject(AuthorService);
|
||||
private bookService = inject(BookService);
|
||||
private messageService = inject(MessageService);
|
||||
private pageTitle = inject(PageTitleService);
|
||||
private scrollService = inject(BookBrowserScrollService);
|
||||
private t = inject(TranslocoService);
|
||||
private router = inject(Router);
|
||||
private activatedRoute = inject(ActivatedRoute);
|
||||
private destroyRef = inject(DestroyRef);
|
||||
protected userService = inject(UserService);
|
||||
protected authorScaleService = inject(AuthorScalePreferenceService);
|
||||
protected selectionService = inject(AuthorSelectionService);
|
||||
|
||||
@ViewChild('scroll')
|
||||
virtualScroller: VirtualScrollerComponent | undefined;
|
||||
|
||||
screenWidth = window.innerWidth;
|
||||
thumbnailCacheBusters = new Map<number, number>();
|
||||
private selectedAuthors = this.selectionService.selectedAuthors;
|
||||
private allAuthorsState = signal<AuthorSummary[] | null>(null);
|
||||
|
||||
loading = computed(() => this.allAuthorsState() === null || this.bookService.isBooksLoading());
|
||||
protected currentUser = this.userService.currentUser;
|
||||
selectedCount = computed(() => this.selectedAuthors().size);
|
||||
searchTerm = signal('');
|
||||
sortBy = signal('name');
|
||||
sortDirection = signal<SortDirection>('asc');
|
||||
filters = signal<AuthorFilters>({...DEFAULT_AUTHOR_FILTERS});
|
||||
private enrichedAuthors = computed(() => {
|
||||
const authors = this.allAuthorsState();
|
||||
if (!authors) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.enrichAuthors(authors, this.bookService.books());
|
||||
});
|
||||
libraryOptions = computed<FilterOption[]>(() => {
|
||||
const allLabel = this.t.translate('authorBrowser.filters.all');
|
||||
const librarySet = new Set<string>();
|
||||
|
||||
for (const author of this.enrichedAuthors()) {
|
||||
for (const library of author.libraryNames) {
|
||||
librarySet.add(library);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{label: allLabel, value: 'all'},
|
||||
...[...librarySet].sort().map(library => ({label: library, value: library}))
|
||||
];
|
||||
});
|
||||
genreOptions = computed<FilterOption[]>(() => {
|
||||
const allLabel = this.t.translate('authorBrowser.filters.all');
|
||||
const genreSet = new Set<string>();
|
||||
|
||||
for (const author of this.enrichedAuthors()) {
|
||||
for (const category of author.categories) {
|
||||
genreSet.add(category);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{label: allLabel, value: 'all'},
|
||||
...[...genreSet].sort().map(category => ({label: category, value: category}))
|
||||
];
|
||||
});
|
||||
activeFilterCount = computed(() => {
|
||||
const filters = this.filters();
|
||||
let count = 0;
|
||||
if (filters.matchStatus !== 'all') count++;
|
||||
if (filters.photoStatus !== 'all') count++;
|
||||
if (filters.readStatus !== 'all') count++;
|
||||
if (filters.bookCount !== 'all') count++;
|
||||
if (filters.library !== 'all') count++;
|
||||
if (filters.genre !== 'all') count++;
|
||||
return count;
|
||||
});
|
||||
filteredAuthors = computed<EnrichedAuthor[]>(() => {
|
||||
let result = this.enrichedAuthors();
|
||||
const search = this.searchTerm().trim().toLowerCase();
|
||||
|
||||
if (search) {
|
||||
result = result.filter(author => author.name.toLowerCase().includes(search));
|
||||
}
|
||||
|
||||
result = this.applyFilters(result, this.filters());
|
||||
return this.applySort(result, this.sortBy(), this.sortDirection());
|
||||
});
|
||||
private readonly syncAuthorsEffect = effect(() => {
|
||||
const authors = this.authorService.allAuthors();
|
||||
if (authors !== null) {
|
||||
this.allAuthorsState.set(authors);
|
||||
}
|
||||
});
|
||||
private readonly syncSelectionEffect = effect(() => {
|
||||
this.selectionService.setCurrentAuthors(this.filteredAuthors());
|
||||
});
|
||||
|
||||
@HostListener('window:resize')
|
||||
onResize(): void {
|
||||
this.screenWidth = window.innerWidth;
|
||||
}
|
||||
|
||||
get isMobile(): boolean {
|
||||
return this.screenWidth <= 767;
|
||||
}
|
||||
|
||||
get cardWidth(): number {
|
||||
const base = this.isMobile
|
||||
? AuthorBrowserComponent.MOBILE_BASE_WIDTH
|
||||
: AuthorBrowserComponent.BASE_WIDTH;
|
||||
return Math.round(base * this.authorScaleService.scaleFactor());
|
||||
}
|
||||
|
||||
get cardHeight(): number {
|
||||
const base = this.isMobile
|
||||
? AuthorBrowserComponent.MOBILE_BASE_HEIGHT
|
||||
: AuthorBrowserComponent.BASE_HEIGHT;
|
||||
return Math.round(base * this.authorScaleService.scaleFactor());
|
||||
}
|
||||
|
||||
get gridColumnMinWidth(): string {
|
||||
return `${this.cardWidth}px`;
|
||||
}
|
||||
|
||||
sortOptions: SortOption[] = [];
|
||||
|
||||
private readonly validSortValues = [
|
||||
'name', 'book-count', 'matched', 'recently-added', 'recently-read',
|
||||
'reading-progress', 'avg-rating', 'photo', 'series-count'
|
||||
];
|
||||
|
||||
ngOnInit(): void {
|
||||
this.pageTitle.setPageTitle(this.t.translate('authorBrowser.pageTitle'));
|
||||
|
||||
this.sortOptions = [
|
||||
{label: this.t.translate('authorBrowser.sort.name'), value: 'name'},
|
||||
{label: this.t.translate('authorBrowser.sort.bookCount'), value: 'book-count'},
|
||||
{label: this.t.translate('authorBrowser.sort.matched'), value: 'matched'},
|
||||
{label: this.t.translate('authorBrowser.sort.recentlyAdded'), value: 'recently-added'},
|
||||
{label: this.t.translate('authorBrowser.sort.recentlyRead'), value: 'recently-read'},
|
||||
{label: this.t.translate('authorBrowser.sort.readingProgress'), value: 'reading-progress'},
|
||||
{label: this.t.translate('authorBrowser.sort.avgRating'), value: 'avg-rating'},
|
||||
{label: this.t.translate('authorBrowser.sort.photo'), value: 'photo'},
|
||||
{label: this.t.translate('authorBrowser.sort.seriesCount'), value: 'series-count'}
|
||||
];
|
||||
|
||||
const sortParam = this.activatedRoute.snapshot.queryParamMap.get('sort');
|
||||
const dirParam = this.activatedRoute.snapshot.queryParamMap.get('dir') as SortDirection | null;
|
||||
if (sortParam && this.validSortValues.includes(sortParam)) {
|
||||
this.sortBy.set(sortParam);
|
||||
this.sortDirection.set(dirParam === 'asc' || dirParam === 'desc' ? dirParam : DEFAULT_SORT_DIRECTIONS[sortParam]);
|
||||
}
|
||||
|
||||
this.setupScrollPositionTracking();
|
||||
this.destroyRef.onDestroy(() => this.selectionService.deselectAll());
|
||||
}
|
||||
|
||||
onSearchChange(value: string): void {
|
||||
this.searchTerm.set(value);
|
||||
}
|
||||
|
||||
onSortChange(value: string): void {
|
||||
this.sortBy.set(value);
|
||||
const nextDirection = DEFAULT_SORT_DIRECTIONS[value] || 'asc';
|
||||
this.sortDirection.set(nextDirection);
|
||||
this.updateSortQueryParams(value, nextDirection);
|
||||
}
|
||||
|
||||
toggleSortDirection(): void {
|
||||
const next: SortDirection = this.sortDirection() === 'asc' ? 'desc' : 'asc';
|
||||
this.sortDirection.set(next);
|
||||
this.updateSortQueryParams(this.sortBy(), next);
|
||||
}
|
||||
|
||||
onFilterChange(key: keyof AuthorFilters, value: string): void {
|
||||
this.filters.update(current => ({...current, [key]: value}));
|
||||
}
|
||||
|
||||
resetFilters(): void {
|
||||
this.filters.set({...DEFAULT_AUTHOR_FILTERS});
|
||||
}
|
||||
|
||||
get canEditMetadata(): boolean {
|
||||
const user = this.userService.currentUser();
|
||||
return !!user?.permissions?.admin || !!user?.permissions?.canEditMetadata;
|
||||
}
|
||||
|
||||
get canDeleteBook(): boolean {
|
||||
const user = this.userService.currentUser();
|
||||
return !!user?.permissions?.admin || !!user?.permissions?.canDeleteBook;
|
||||
}
|
||||
|
||||
isAuthorSelected(authorId: number): boolean {
|
||||
return this.selectedAuthors().has(authorId);
|
||||
}
|
||||
|
||||
onCheckboxClicked(event: AuthorCheckboxClickEvent): void {
|
||||
this.selectionService.handleCheckboxClick(event);
|
||||
}
|
||||
|
||||
selectAllAuthors(): void {
|
||||
this.selectionService.selectAll();
|
||||
}
|
||||
|
||||
deselectAllAuthors(): void {
|
||||
this.selectionService.deselectAll();
|
||||
}
|
||||
|
||||
navigateToAuthor(author: AuthorSummary): void {
|
||||
this.router.navigate(['/author', author.id]);
|
||||
}
|
||||
|
||||
navigateToAuthorEdit(author: AuthorSummary): void {
|
||||
this.router.navigate(['/author', author.id], {queryParams: {tab: 'edit'}});
|
||||
}
|
||||
|
||||
deleteAuthor(author: AuthorSummary): void {
|
||||
this.authorService.deleteAuthors([author.id]).subscribe({
|
||||
next: () => {
|
||||
this.removeAuthorsFromList([author.id]);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('authorBrowser.toast.deleteSuccessSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.deleteSuccessDetail')
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.toast.deleteFailedSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.deleteFailedDetail')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onAuthorQuickMatched(updated: AuthorSummary): void {
|
||||
this.thumbnailCacheBusters.set(updated.id, Date.now());
|
||||
this.allAuthorsState.update(current =>
|
||||
(current ?? []).map(author => author.id === updated.id ? updated : author)
|
||||
);
|
||||
}
|
||||
|
||||
autoMatchSelected(): void {
|
||||
const ids = this.selectionService.getSelectedIds();
|
||||
this.selectionService.deselectAll();
|
||||
this.authorService.autoMatchAuthors(ids).subscribe({
|
||||
next: (matched) => {
|
||||
this.thumbnailCacheBusters.set(matched.id, Date.now());
|
||||
this.allAuthorsState.update(current => (current ?? []).map(author => author.id === matched.id
|
||||
? {...author, asin: matched.asin, hasPhoto: matched.hasPhoto}
|
||||
: author
|
||||
));
|
||||
},
|
||||
complete: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('authorBrowser.toast.autoMatchSuccessSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.autoMatchSuccessDetail')
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.toast.autoMatchFailedSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.autoMatchFailedDetail')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
deleteSelected(): void {
|
||||
const ids = this.selectionService.getSelectedIds();
|
||||
this.authorService.deleteAuthors(ids).subscribe({
|
||||
next: () => {
|
||||
this.selectionService.deselectAll();
|
||||
this.removeAuthorsFromList(ids);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('authorBrowser.toast.deleteSelectedSuccessSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.deleteSelectedSuccessDetail')
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.toast.deleteFailedSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.deleteFailedDetail')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private updateSortQueryParams(sort: string, dir: SortDirection): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: {sort, dir},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
private enrichAuthors(authors: AuthorSummary[], books: Book[]): EnrichedAuthor[] {
|
||||
const booksByAuthor = new Map<string, Book[]>();
|
||||
for (const book of books) {
|
||||
if (book.metadata?.authors) {
|
||||
for (const authorName of book.metadata.authors) {
|
||||
const key = authorName.toLowerCase();
|
||||
let list = booksByAuthor.get(key);
|
||||
if (!list) {
|
||||
list = [];
|
||||
booksByAuthor.set(key, list);
|
||||
}
|
||||
list.push(book);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return authors.map(author => {
|
||||
const authorBooks = booksByAuthor.get(author.name.toLowerCase()) || [];
|
||||
|
||||
const libraryIds = new Set<number>();
|
||||
const libraryNameSet = new Set<string>();
|
||||
const categorySet = new Set<string>();
|
||||
const seriesSet = new Set<string>();
|
||||
let latestAddedOn: string | null = null;
|
||||
let lastReadTime: string | null = null;
|
||||
let readCount = 0;
|
||||
let inProgressCount = 0;
|
||||
let ratingSum = 0;
|
||||
let ratingCount = 0;
|
||||
|
||||
for (const book of authorBooks) {
|
||||
libraryIds.add(book.libraryId);
|
||||
if (book.libraryName) libraryNameSet.add(book.libraryName);
|
||||
|
||||
if (book.metadata?.categories) {
|
||||
for (const cat of book.metadata.categories) categorySet.add(cat);
|
||||
}
|
||||
if (book.metadata?.seriesName) {
|
||||
seriesSet.add(book.metadata.seriesName.toLowerCase());
|
||||
}
|
||||
if (book.addedOn && (!latestAddedOn || book.addedOn > latestAddedOn)) {
|
||||
latestAddedOn = book.addedOn;
|
||||
}
|
||||
if (book.lastReadTime && (!lastReadTime || book.lastReadTime > lastReadTime)) {
|
||||
lastReadTime = book.lastReadTime;
|
||||
}
|
||||
if (book.readStatus === ReadStatus.READ) readCount++;
|
||||
if (book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING) inProgressCount++;
|
||||
if (book.personalRating != null) {
|
||||
ratingSum += book.personalRating;
|
||||
ratingCount++;
|
||||
}
|
||||
}
|
||||
|
||||
const totalBooks = authorBooks.length;
|
||||
let readStatus: EnrichedAuthor['readStatus'] = 'unread';
|
||||
if (totalBooks > 0) {
|
||||
if (readCount === totalBooks) {
|
||||
readStatus = 'all-read';
|
||||
} else if (inProgressCount > 0) {
|
||||
readStatus = 'in-progress';
|
||||
} else if (readCount > 0) {
|
||||
readStatus = 'some-read';
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...author,
|
||||
libraryIds,
|
||||
libraryNames: [...libraryNameSet].sort(),
|
||||
categories: [...categorySet].sort(),
|
||||
readStatus,
|
||||
hasSeries: seriesSet.size > 0,
|
||||
seriesCount: seriesSet.size,
|
||||
latestAddedOn,
|
||||
lastReadTime,
|
||||
readingProgress: totalBooks > 0 ? Math.round((readCount / totalBooks) * 100) : 0,
|
||||
avgPersonalRating: ratingCount > 0 ? ratingSum / ratingCount : null
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private applyFilters(authors: EnrichedAuthor[], filters: AuthorFilters): EnrichedAuthor[] {
|
||||
return authors.filter(a => {
|
||||
if (filters.matchStatus === 'matched' && !a.asin) return false;
|
||||
if (filters.matchStatus === 'unmatched' && a.asin) return false;
|
||||
|
||||
if (filters.photoStatus === 'has-photo' && !a.hasPhoto) return false;
|
||||
if (filters.photoStatus === 'no-photo' && a.hasPhoto) return false;
|
||||
|
||||
if (filters.readStatus !== 'all' && a.readStatus !== filters.readStatus) return false;
|
||||
|
||||
if (filters.bookCount !== 'all') {
|
||||
const c = a.bookCount;
|
||||
switch (filters.bookCount) {
|
||||
case '0': if (c !== 0) return false; break;
|
||||
case '1': if (c !== 1) return false; break;
|
||||
case '2': if (c !== 2) return false; break;
|
||||
case '3': if (c !== 3) return false; break;
|
||||
case '4': if (c !== 4) return false; break;
|
||||
case '5': if (c !== 5) return false; break;
|
||||
case '6-10': if (c < 6 || c > 10) return false; break;
|
||||
case '11-20': if (c < 11 || c > 20) return false; break;
|
||||
case '21-35': if (c < 21 || c > 35) return false; break;
|
||||
case '36+': if (c < 36) return false; break;
|
||||
}
|
||||
}
|
||||
|
||||
if (filters.library !== 'all' && !a.libraryNames.includes(filters.library)) return false;
|
||||
if (filters.genre !== 'all' && !a.categories.includes(filters.genre)) return false;
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private getScrollPositionKey(): string {
|
||||
const path = this.activatedRoute.snapshot.routeConfig?.path ?? '';
|
||||
return this.scrollService.createKey(path, this.activatedRoute.snapshot.params);
|
||||
}
|
||||
|
||||
private setupScrollPositionTracking(): void {
|
||||
this.router.events.pipe(
|
||||
filter(event => event instanceof NavigationStart),
|
||||
takeUntilDestroyed(this.destroyRef)
|
||||
).subscribe(() => {
|
||||
this.dismissBodyMenus();
|
||||
this.saveScrollPosition();
|
||||
});
|
||||
}
|
||||
|
||||
private dismissBodyMenus(): void {
|
||||
document.querySelectorAll('.p-tieredmenu-overlay').forEach(el => el.remove());
|
||||
}
|
||||
|
||||
private saveScrollPosition(): void {
|
||||
if (this.virtualScroller?.viewPortInfo) {
|
||||
const key = this.getScrollPositionKey();
|
||||
const position = this.virtualScroller.viewPortInfo.scrollStartPosition ?? 0;
|
||||
this.scrollService.savePosition(key, position);
|
||||
}
|
||||
}
|
||||
|
||||
private removeAuthorsFromList(ids: number[]): void {
|
||||
const idSet = new Set(ids);
|
||||
this.allAuthorsState.update(current => (current ?? []).filter(author => !idSet.has(author.id)));
|
||||
}
|
||||
|
||||
private applySort(authors: EnrichedAuthor[], sortBy: string, direction: SortDirection): EnrichedAuthor[] {
|
||||
const sorted = [...authors];
|
||||
const dir = direction === 'asc' ? 1 : -1;
|
||||
|
||||
switch (sortBy) {
|
||||
case 'name':
|
||||
return sorted.sort((a, b) => dir * a.name.localeCompare(b.name));
|
||||
case 'book-count':
|
||||
return sorted.sort((a, b) => dir * (a.bookCount - b.bookCount));
|
||||
case 'matched':
|
||||
return sorted.sort((a, b) => {
|
||||
const aVal = a.asin ? 1 : 0;
|
||||
const bVal = b.asin ? 1 : 0;
|
||||
if (aVal !== bVal) return dir * (aVal - bVal);
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
case 'recently-added':
|
||||
return sorted.sort((a, b) => {
|
||||
if (!a.latestAddedOn && !b.latestAddedOn) return a.name.localeCompare(b.name);
|
||||
if (!a.latestAddedOn) return 1;
|
||||
if (!b.latestAddedOn) return -1;
|
||||
return dir * a.latestAddedOn.localeCompare(b.latestAddedOn);
|
||||
});
|
||||
case 'recently-read':
|
||||
return sorted.sort((a, b) => {
|
||||
if (!a.lastReadTime && !b.lastReadTime) return a.name.localeCompare(b.name);
|
||||
if (!a.lastReadTime) return 1;
|
||||
if (!b.lastReadTime) return -1;
|
||||
return dir * a.lastReadTime.localeCompare(b.lastReadTime);
|
||||
});
|
||||
case 'reading-progress':
|
||||
return sorted.sort((a, b) => dir * (a.readingProgress - b.readingProgress));
|
||||
case 'avg-rating':
|
||||
return sorted.sort((a, b) => {
|
||||
if (a.avgPersonalRating == null && b.avgPersonalRating == null) return a.name.localeCompare(b.name);
|
||||
if (a.avgPersonalRating == null) return 1;
|
||||
if (b.avgPersonalRating == null) return -1;
|
||||
return dir * (a.avgPersonalRating - b.avgPersonalRating);
|
||||
});
|
||||
case 'photo':
|
||||
return sorted.sort((a, b) => {
|
||||
const aVal = a.hasPhoto ? 1 : 0;
|
||||
const bVal = b.hasPhoto ? 1 : 0;
|
||||
if (aVal !== bVal) return dir * (aVal - bVal);
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
case 'series-count':
|
||||
return sorted.sort((a, b) => dir * (a.seriesCount - b.seriesCount));
|
||||
default:
|
||||
return sorted;
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
<div class="author-card" [class.selected]="isSelected" (click)="onCardClick($event)">
|
||||
<div class="cover-container" [ngClass]="{'loaded': isImageLoaded}">
|
||||
@if (hasPhoto) {
|
||||
<img
|
||||
[src]="thumbnailUrl"
|
||||
class="author-photo"
|
||||
[class.loaded]="isImageLoaded"
|
||||
[alt]="author.name"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
(load)="onImageLoad()"
|
||||
(error)="onPhotoError()"/>
|
||||
} @else {
|
||||
<div class="author-photo-placeholder">
|
||||
<i class="pi pi-user"></i>
|
||||
</div>
|
||||
}
|
||||
|
||||
<span class="book-count-badge">{{ author.bookCount }}</span>
|
||||
|
||||
@if (isCheckboxEnabled) {
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
class="select-checkbox"
|
||||
(click)="captureMouseEvent($event)"
|
||||
[ngModel]="isSelected"
|
||||
(onChange)="toggleSelection($event)">
|
||||
</p-checkbox>
|
||||
}
|
||||
|
||||
<div class="card-overlay">
|
||||
@if (isMatched) {
|
||||
<i class="pi pi-check-circle matched-icon" [pTooltip]="'authorBrowser.card.matched' | transloco" tooltipPosition="top"></i>
|
||||
}
|
||||
<h4 class="author-name" [pTooltip]="author.name" tooltipPosition="bottom">{{ author.name }}</h4>
|
||||
<div class="menu-button-container">
|
||||
<p-tieredmenu #menu [model]="items" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()"></p-tieredmenu>
|
||||
<p-button
|
||||
class="card-menu-btn"
|
||||
size="small"
|
||||
[text]="true"
|
||||
(click)="onMenuToggle($event, menu)"
|
||||
icon="pi pi-ellipsis-v">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
.author-card {
|
||||
background-color: var(--card-background);
|
||||
border-radius: 8px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
transition: box-shadow 0.25s ease, transform 0.25s ease;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
&.selected {
|
||||
border: 2px solid var(--primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% {
|
||||
background-position: -200% 0;
|
||||
}
|
||||
100% {
|
||||
background-position: 200% 0;
|
||||
}
|
||||
}
|
||||
|
||||
.cover-container {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: var(--card-background);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.cover-container:not(.loaded) {
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--surface-ground) 25%,
|
||||
var(--surface-hover, rgba(255, 255, 255, 0.08)) 50%,
|
||||
var(--surface-ground) 75%
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.author-photo {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 8px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s ease-in, transform 0.35s ease;
|
||||
}
|
||||
|
||||
.author-photo.loaded {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.author-card:hover .author-photo.loaded {
|
||||
transform: scale(1.04);
|
||||
}
|
||||
|
||||
.author-photo-placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
color: #64748b;
|
||||
background: color-mix(in srgb, var(--p-surface-800), transparent 20%);
|
||||
|
||||
i {
|
||||
font-size: 3rem;
|
||||
}
|
||||
}
|
||||
|
||||
.book-count-badge {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
padding: 3px 9px;
|
||||
border-radius: 10px;
|
||||
line-height: 1.3;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.card-overlay {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
padding: 8px 2px 4px 8px;
|
||||
background: linear-gradient(to top, rgba(0, 0, 0, 0.9) 0%, rgba(0, 0, 0, 0.5) 70%, transparent 100%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.matched-icon {
|
||||
color: #22c55e;
|
||||
font-size: 0.85rem;
|
||||
flex-shrink: 0;
|
||||
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5));
|
||||
}
|
||||
|
||||
.author-name {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: #fff;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
line-height: 1.3;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
.menu-button-container {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
::ng-deep .card-menu-btn .p-button {
|
||||
padding: 0.15rem 0.25rem !important;
|
||||
color: #fff !important;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.15) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.select-checkbox {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.15s ease, visibility 0.15s ease;
|
||||
z-index: 3;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.cover-container:hover .select-checkbox,
|
||||
.author-card.selected .select-checkbox {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
import {ChangeDetectorRef, Component, EventEmitter, inject, Input, OnChanges, Output, SimpleChanges} from '@angular/core';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {CheckboxChangeEvent, CheckboxModule} from 'primeng/checkbox';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {TieredMenu} from 'primeng/tieredmenu';
|
||||
import {Button} from 'primeng/button';
|
||||
import {MenuItem, MessageService} from 'primeng/api';
|
||||
import {AuthorSummary} from '../../model/author.model';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-author-card',
|
||||
standalone: true,
|
||||
templateUrl: './author-card.component.html',
|
||||
styleUrls: ['./author-card.component.scss'],
|
||||
imports: [NgClass, TranslocoPipe, Tooltip, CheckboxModule, FormsModule, TieredMenu, Button]
|
||||
})
|
||||
export class AuthorCardComponent implements OnChanges {
|
||||
|
||||
@Input({required: true}) author!: AuthorSummary;
|
||||
@Input() canQuickMatch = false;
|
||||
@Input() canDelete = false;
|
||||
@Input() isCheckboxEnabled = false;
|
||||
@Input() isSelected = false;
|
||||
@Output() cardClick = new EventEmitter<AuthorSummary>();
|
||||
@Output() quickMatched = new EventEmitter<AuthorSummary>();
|
||||
@Output() checkboxClick = new EventEmitter<{ index: number; author: AuthorSummary; selected: boolean; shiftKey: boolean }>();
|
||||
@Output() viewAuthor = new EventEmitter<AuthorSummary>();
|
||||
@Output() editAuthor = new EventEmitter<AuthorSummary>();
|
||||
@Output() deleteAuthor = new EventEmitter<AuthorSummary>();
|
||||
@Output() menuToggled = new EventEmitter<boolean>();
|
||||
@Input() index = 0;
|
||||
@Input() cacheBuster = 0;
|
||||
|
||||
private authorService = inject(AuthorService);
|
||||
private messageService = inject(MessageService);
|
||||
private t = inject(TranslocoService);
|
||||
private cdr = inject(ChangeDetectorRef);
|
||||
private lastShiftKey = false;
|
||||
|
||||
hasPhoto = false;
|
||||
isImageLoaded = false;
|
||||
quickMatching = false;
|
||||
|
||||
items: MenuItem[] = [];
|
||||
private menuInitialized = false;
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['author']) {
|
||||
const prev = changes['author'].previousValue as AuthorSummary | undefined;
|
||||
const curr = changes['author'].currentValue as AuthorSummary;
|
||||
if (!prev || prev.id !== curr.id || prev.hasPhoto !== curr.hasPhoto || prev.asin !== curr.asin) {
|
||||
this.hasPhoto = curr.hasPhoto;
|
||||
this.isImageLoaded = false;
|
||||
}
|
||||
}
|
||||
if (changes['cacheBuster'] && !changes['cacheBuster'].firstChange) {
|
||||
this.hasPhoto = true;
|
||||
this.isImageLoaded = false;
|
||||
}
|
||||
}
|
||||
|
||||
get thumbnailUrl(): string {
|
||||
return this.authorService.getAuthorThumbnailUrl(this.author.id, this.cacheBuster || undefined);
|
||||
}
|
||||
|
||||
get isMatched(): boolean {
|
||||
return !!this.author.asin;
|
||||
}
|
||||
|
||||
onCardClick(event: MouseEvent): void {
|
||||
const target = event.target as HTMLElement;
|
||||
if (target.closest('.menu-button-container')) {
|
||||
return;
|
||||
}
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.toggleCardSelection(!this.isSelected);
|
||||
return;
|
||||
}
|
||||
event.stopPropagation();
|
||||
this.cardClick.emit(this.author);
|
||||
}
|
||||
|
||||
onImageLoad(): void {
|
||||
this.isImageLoaded = true;
|
||||
}
|
||||
|
||||
onPhotoError(): void {
|
||||
this.hasPhoto = false;
|
||||
}
|
||||
|
||||
captureMouseEvent(event: MouseEvent): void {
|
||||
event.stopPropagation();
|
||||
this.lastShiftKey = event.shiftKey;
|
||||
}
|
||||
|
||||
toggleSelection(event: CheckboxChangeEvent): void {
|
||||
this.checkboxClick.emit({index: this.index, author: this.author, selected: event.checked, shiftKey: this.lastShiftKey});
|
||||
}
|
||||
|
||||
toggleCardSelection(selected: boolean): void {
|
||||
this.checkboxClick.emit({index: this.index, author: this.author, selected, shiftKey: false});
|
||||
}
|
||||
|
||||
onMenuToggle(event: Event, menu: TieredMenu): void {
|
||||
if (!this.menuInitialized) {
|
||||
this.menuInitialized = true;
|
||||
this.initMenu();
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
menu.toggle(event);
|
||||
}
|
||||
|
||||
onMenuShow(): void {
|
||||
this.menuToggled.emit(true);
|
||||
}
|
||||
|
||||
onMenuHide(): void {
|
||||
this.menuToggled.emit(false);
|
||||
}
|
||||
|
||||
private initMenu(): void {
|
||||
this.items = [
|
||||
{
|
||||
label: this.t.translate('authorBrowser.card.menu.viewAuthor'),
|
||||
icon: 'pi pi-user',
|
||||
command: () => this.viewAuthor.emit(this.author)
|
||||
},
|
||||
...(this.canQuickMatch ? [
|
||||
{
|
||||
label: this.t.translate('authorBrowser.card.menu.editAuthor'),
|
||||
icon: 'pi pi-pencil',
|
||||
command: () => this.editAuthor.emit(this.author)
|
||||
},
|
||||
{
|
||||
label: this.t.translate('authorBrowser.card.menu.quickMatch'),
|
||||
icon: this.quickMatching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt',
|
||||
disabled: this.quickMatching,
|
||||
command: () => this.onQuickMatch()
|
||||
}
|
||||
] : []),
|
||||
...(this.canDelete ? [
|
||||
{
|
||||
label: this.t.translate('authorBrowser.card.menu.deleteAuthor'),
|
||||
icon: 'pi pi-trash',
|
||||
command: () => this.deleteAuthor.emit(this.author)
|
||||
}
|
||||
] : [])
|
||||
];
|
||||
}
|
||||
|
||||
private onQuickMatch(): void {
|
||||
if (this.quickMatching) return;
|
||||
|
||||
this.quickMatching = true;
|
||||
this.authorService.quickMatchAuthor(this.author.id).subscribe({
|
||||
next: (updated) => {
|
||||
this.quickMatching = false;
|
||||
this.author = {...this.author, asin: updated.asin, hasPhoto: true};
|
||||
this.hasPhoto = true;
|
||||
this.isImageLoaded = false;
|
||||
this.menuInitialized = false;
|
||||
this.quickMatched.emit(this.author);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('authorBrowser.toast.quickMatchSuccessSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.quickMatchSuccessDetail')
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.quickMatching = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.toast.quickMatchFailedSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.quickMatchFailedDetail')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
<ng-container *transloco="let t; prefix: 'authorBrowser.detail'">
|
||||
@if (loading) {
|
||||
<div class="loading-state">
|
||||
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s">
|
||||
</p-progressSpinner>
|
||||
<p style="color: var(--primary-color);">{{ t('loading') }}</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!loading && author(); as author) {
|
||||
<div class="author-wrapper">
|
||||
<p-tabs [value]="tab" lazy="true" scrollable>
|
||||
<p-tablist>
|
||||
<p-tab value="books">
|
||||
<i class="pi pi-user"></i>
|
||||
{{ t('booksTab') }}
|
||||
</p-tab>
|
||||
@if (canEditMetadata) {
|
||||
<p-tab value="edit">
|
||||
<i class="pi pi-pencil"></i>
|
||||
{{ t('editTab') }}
|
||||
</p-tab>
|
||||
<p-tab value="match">
|
||||
<i class="pi pi-search"></i>
|
||||
{{ t('matchTab') }}
|
||||
</p-tab>
|
||||
}
|
||||
</p-tablist>
|
||||
<p-tabpanels class="tabpanels-responsive">
|
||||
<p-tabpanel value="books">
|
||||
<div class="author-header">
|
||||
<div class="author-photo-section">
|
||||
@if (hasPhoto) {
|
||||
<img
|
||||
[src]="photoUrl"
|
||||
class="author-photo-large"
|
||||
[alt]="author.name"
|
||||
(error)="onPhotoError()"/>
|
||||
} @else {
|
||||
<div class="author-photo-placeholder-large">
|
||||
<i class="pi pi-user"></i>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="author-info">
|
||||
<div class="author-title-row">
|
||||
<h2 class="author-title">{{ author.name }}</h2>
|
||||
@if (author.asin) {
|
||||
<a [href]="'https://www.amazon.com/stores/author/' + author.asin + '/about'"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="asin-link">
|
||||
<p-tag [value]="'ASIN: ' + author.asin" severity="info"></p-tag>
|
||||
</a>
|
||||
<a [href]="'https://www.audible.com/author/' + author.asin"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="asin-link">
|
||||
<p-tag value="Audible" severity="warn"></p-tag>
|
||||
</a>
|
||||
}
|
||||
@if (canEditMetadata) {
|
||||
<p-button
|
||||
[icon]="quickMatching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
|
||||
[outlined]="true"
|
||||
severity="warn"
|
||||
size="small"
|
||||
[disabled]="quickMatching"
|
||||
(onClick)="quickMatch()"
|
||||
[pTooltip]="t('quickMatchTooltip')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (author.description) {
|
||||
<div class="description-box">
|
||||
<div #descriptionContent
|
||||
[ngClass]="{'line-clamp-5': !isExpanded, 'line-clamp-none': isExpanded}"
|
||||
class="description-container">
|
||||
<div class="readonly-editor">{{ author.description }}</div>
|
||||
</div>
|
||||
@if (isExpanded || isOverflowing) {
|
||||
<p-button
|
||||
[label]="isExpanded ? t('showLess') : t('showMore')"
|
||||
[icon]="isExpanded ? 'pi pi-chevron-up' : 'pi pi-chevron-down'"
|
||||
iconPos="right"
|
||||
size="small"
|
||||
text
|
||||
(click)="toggleExpand()">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (authorBooks(); as books) {
|
||||
<div class="books-section">
|
||||
<h3 class="section-title">{{ t('booksBy', {name: author.name}) }} ({{ books.length }})</h3>
|
||||
@if (books.length === 0) {
|
||||
<div class="empty-books">
|
||||
<i class="pi pi-book"></i>
|
||||
<p>{{ t('noBooksFound') }}</p>
|
||||
</div>
|
||||
} @else {
|
||||
<virtual-scroller #scroll [items]="books" class="books-virtual-scroller">
|
||||
<div class="books-grid" #container
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
||||
@for (book of scroll.viewPortItems; track book.id; let i = $index) {
|
||||
<div class="virtual-scroller-item"
|
||||
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
||||
<app-book-card
|
||||
[index]="books.indexOf(book)"
|
||||
[book]="book"
|
||||
[isSeriesCollapsed]="false"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</virtual-scroller>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</p-tabpanel>
|
||||
|
||||
@if (canEditMetadata) {
|
||||
<p-tabpanel value="edit">
|
||||
<app-author-editor
|
||||
[authorId]="author.id"
|
||||
[author]="author"
|
||||
(authorUpdated)="onAuthorUpdated($event)">
|
||||
</app-author-editor>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel value="match">
|
||||
<app-author-match
|
||||
[authorId]="author.id"
|
||||
[authorName]="author.name"
|
||||
(authorMatched)="onAuthorUpdated($event)">
|
||||
</app-author-match>
|
||||
</p-tabpanel>
|
||||
}
|
||||
</p-tabpanels>
|
||||
</p-tabs>
|
||||
</div>
|
||||
}
|
||||
</ng-container>
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
.tabpanels-responsive {
|
||||
height: calc(100dvh - 9.7rem);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.tabpanels-responsive {
|
||||
height: calc(100dvh - 8.5rem);
|
||||
}
|
||||
}
|
||||
|
||||
.author-wrapper {
|
||||
position: relative;
|
||||
border-radius: 0.75rem;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.loading-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.author-header {
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
padding: 0.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.author-photo-section {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.author-photo-large {
|
||||
width: 180px;
|
||||
height: 220px;
|
||||
object-fit: cover;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
|
||||
|
||||
@media (max-width: 767px) {
|
||||
width: 140px;
|
||||
height: 175px;
|
||||
}
|
||||
}
|
||||
|
||||
.author-photo-placeholder-large {
|
||||
width: 180px;
|
||||
height: 220px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 12px;
|
||||
background: color-mix(in srgb, var(--p-surface-800), transparent 20%);
|
||||
color: #64748b;
|
||||
|
||||
i {
|
||||
font-size: 4rem;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
width: 140px;
|
||||
height: 175px;
|
||||
}
|
||||
}
|
||||
|
||||
.author-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.author-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.asin-link {
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
|
||||
.author-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 800;
|
||||
line-height: 1.25;
|
||||
margin: 0;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
font-size: 1.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.description-box {
|
||||
padding: 1rem 0.5rem 0.5rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
|
||||
.description-container {
|
||||
transition: all 0.3s;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.line-clamp-5 {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 5;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.line-clamp-none {
|
||||
-webkit-line-clamp: unset;
|
||||
}
|
||||
|
||||
.readonly-editor {
|
||||
font-size: 0.9rem;
|
||||
color: #d1d5db;
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.books-section {
|
||||
padding: 0 0.5rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 1rem;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
.books-virtual-scroller {
|
||||
width: 100%;
|
||||
height: calc(100dvh - 22rem);
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--primary-color) rgba(20, 20, 30, 0.5);
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 12px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: rgba(20, 20, 30, 0.5);
|
||||
border-radius: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
.books-grid {
|
||||
display: grid;
|
||||
gap: 1.3rem;
|
||||
align-items: start;
|
||||
justify-items: center;
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.virtual-scroller-item {
|
||||
position: relative;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.empty-books {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
|
||||
i {
|
||||
font-size: 2.5rem;
|
||||
color: #64748b;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
p {
|
||||
color: #94a3b8;
|
||||
font-size: 1rem;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
import {AfterViewChecked, Component, computed, ElementRef, inject, OnInit, signal, ViewChild} from '@angular/core';
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {NgClass, NgStyle} from '@angular/common';
|
||||
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Tag} from 'primeng/tag';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorDetails} from '../../model/author.model';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component';
|
||||
import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service';
|
||||
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {AuthorMatchComponent} from '../author-match/author-match.component';
|
||||
import {AuthorEditorComponent} from '../author-editor/author-editor.component';
|
||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-author-detail',
|
||||
standalone: true,
|
||||
templateUrl: './author-detail.component.html',
|
||||
styleUrls: ['./author-detail.component.scss'],
|
||||
imports: [
|
||||
NgClass,
|
||||
NgStyle,
|
||||
Tabs,
|
||||
TabList,
|
||||
Tab,
|
||||
TabPanels,
|
||||
TabPanel,
|
||||
ProgressSpinner,
|
||||
Button,
|
||||
Tag,
|
||||
TranslocoDirective,
|
||||
Tooltip,
|
||||
VirtualScrollerModule,
|
||||
BookCardComponent,
|
||||
AuthorMatchComponent,
|
||||
AuthorEditorComponent
|
||||
]
|
||||
})
|
||||
export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
||||
|
||||
private route = inject(ActivatedRoute);
|
||||
private router = inject(Router);
|
||||
private authorService = inject(AuthorService);
|
||||
private bookService = inject(BookService);
|
||||
private messageService = inject(MessageService);
|
||||
protected coverScalePreferenceService = inject(CoverScalePreferenceService);
|
||||
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
|
||||
protected userService = inject(UserService);
|
||||
private pageTitle = inject(PageTitleService);
|
||||
private t = inject(TranslocoService);
|
||||
|
||||
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
|
||||
|
||||
loading = true;
|
||||
tab = 'books';
|
||||
isExpanded = false;
|
||||
isOverflowing = false;
|
||||
hasPhoto = true;
|
||||
photoTimestamp = Date.now();
|
||||
quickMatching = false;
|
||||
private authorState = signal<AuthorDetails | null>(null);
|
||||
author = this.authorState.asReadonly();
|
||||
authorBooks = computed(() => {
|
||||
const authorName = this.author()?.name?.toLowerCase();
|
||||
if (!authorName) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.bookService.books().filter(book =>
|
||||
book.metadata?.authors?.some(author => author.toLowerCase() === authorName)
|
||||
);
|
||||
});
|
||||
|
||||
get currentCardSize() {
|
||||
return this.coverScalePreferenceService.currentCardSize();
|
||||
}
|
||||
|
||||
get gridColumnMinWidth(): string {
|
||||
return this.coverScalePreferenceService.gridColumnMinWidth();
|
||||
}
|
||||
|
||||
get photoUrl(): string {
|
||||
const author = this.author();
|
||||
if (!author) return '';
|
||||
return this.authorService.getAuthorPhotoUrl(author.id) + '&t=' + this.photoTimestamp;
|
||||
}
|
||||
|
||||
get canEditMetadata(): boolean {
|
||||
const user = this.userService.getCurrentUser();
|
||||
return !!user?.permissions?.admin || !!user?.permissions?.canEditMetadata;
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
const authorId = Number(this.route.snapshot.paramMap.get('authorId'));
|
||||
const tabParam = this.route.snapshot.queryParamMap.get('tab');
|
||||
if (tabParam) {
|
||||
this.tab = tabParam;
|
||||
}
|
||||
this.loadAuthor(authorId);
|
||||
}
|
||||
|
||||
ngAfterViewChecked(): void {
|
||||
if (!this.isExpanded && this.descriptionContentRef) {
|
||||
const el = this.descriptionContentRef.nativeElement;
|
||||
this.isOverflowing = el.scrollHeight > el.clientHeight;
|
||||
}
|
||||
}
|
||||
|
||||
toggleExpand(): void {
|
||||
this.isExpanded = !this.isExpanded;
|
||||
}
|
||||
|
||||
onPhotoError(): void {
|
||||
this.hasPhoto = false;
|
||||
}
|
||||
|
||||
onAuthorUpdated(updatedAuthor: AuthorDetails): void {
|
||||
this.authorState.set(updatedAuthor);
|
||||
this.hasPhoto = true;
|
||||
this.photoTimestamp = Date.now();
|
||||
this.authorService.patchAuthorInCache(updatedAuthor.id, {
|
||||
name: updatedAuthor.name,
|
||||
asin: updatedAuthor.asin,
|
||||
hasPhoto: true,
|
||||
});
|
||||
}
|
||||
|
||||
quickMatch(): void {
|
||||
const author = this.author();
|
||||
if (!author || this.quickMatching) return;
|
||||
this.quickMatching = true;
|
||||
this.authorService.quickMatchAuthor(author.id).subscribe({
|
||||
next: (matched) => {
|
||||
this.onAuthorUpdated(matched);
|
||||
this.quickMatching = false;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('authorBrowser.toast.quickMatchSuccessSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.quickMatchSuccessDetail')
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.quickMatching = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.toast.quickMatchFailedSummary'),
|
||||
detail: this.t.translate('authorBrowser.toast.quickMatchFailedDetail')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private loadAuthor(authorId: number): void {
|
||||
this.authorService.getAuthorDetails(authorId).subscribe({
|
||||
next: (author) => {
|
||||
this.authorState.set(author);
|
||||
this.loading = false;
|
||||
this.pageTitle.setPageTitle(author.name);
|
||||
},
|
||||
error: () => {
|
||||
this.loading = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
<ng-container *transloco="let t; prefix: 'authorBrowser.editor'">
|
||||
<div class="editor-container">
|
||||
<div class="cover-section">
|
||||
@if (hasPhoto) {
|
||||
<p-image
|
||||
[src]="photoUrl"
|
||||
alt="Author Photo"
|
||||
width="200"
|
||||
appendTo="body"
|
||||
[preview]="true"
|
||||
(onImageError)="onPhotoError()">
|
||||
</p-image>
|
||||
} @else {
|
||||
<div class="photo-placeholder">
|
||||
<i class="pi pi-user"></i>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (isUploading) {
|
||||
<p-progressSpinner class="upload-spinner" strokeWidth="4" fill="transparent" animationDuration=".8s"></p-progressSpinner>
|
||||
}
|
||||
|
||||
<div class="cover-actions">
|
||||
<p-fileupload
|
||||
[chooseStyleClass]="'p-button-sm p-button-outlined p-button-danger'"
|
||||
[pTooltip]="t('uploadPhotoTooltip')"
|
||||
tooltipPosition="top"
|
||||
[disabled]="form.get('photoLocked')?.value"
|
||||
name="file"
|
||||
[url]="uploadUrl"
|
||||
mode="basic"
|
||||
chooseIcon="pi pi-upload"
|
||||
accept="image/jpeg,image/png"
|
||||
maxFileSize="5000000"
|
||||
(onUpload)="onUpload()"
|
||||
(onError)="onUploadError()"
|
||||
[auto]="true"
|
||||
(onBeforeUpload)="onBeforeUpload()">
|
||||
</p-fileupload>
|
||||
|
||||
<p-button
|
||||
[pTooltip]="t('searchPhotoTooltip')"
|
||||
tooltipPosition="top"
|
||||
size="small"
|
||||
icon="pi pi-search"
|
||||
[outlined]="true"
|
||||
[disabled]="form.get('photoLocked')?.value"
|
||||
(onClick)="openPhotoSearch()"
|
||||
severity="info">
|
||||
</p-button>
|
||||
|
||||
@if (!form.get('photoLocked')?.value) {
|
||||
<p-button
|
||||
[pTooltip]="t('lockField')"
|
||||
tooltipPosition="top"
|
||||
size="small"
|
||||
icon="pi pi-lock-open"
|
||||
[outlined]="true"
|
||||
(onClick)="togglePhotoLock()"
|
||||
severity="success">
|
||||
</p-button>
|
||||
}
|
||||
@if (form.get('photoLocked')?.value) {
|
||||
<p-button
|
||||
[pTooltip]="t('unlockField')"
|
||||
tooltipPosition="top"
|
||||
size="small"
|
||||
icon="pi pi-lock"
|
||||
[outlined]="true"
|
||||
(onClick)="togglePhotoLock()"
|
||||
severity="warn">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form class="fields-section" [formGroup]="form" (ngSubmit)="onSave()">
|
||||
<div class="field-group">
|
||||
<label for="authorName">{{ t('nameLabel') }}</label>
|
||||
<div class="field-with-lock">
|
||||
<input pInputText id="authorName" formControlName="name"/>
|
||||
@if (!form.get('nameLocked')?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('name')" severity="success"></p-button>
|
||||
}
|
||||
@if (form.get('nameLocked')?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('name')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field-group">
|
||||
<label for="authorAsin">{{ t('asinLabel') }}</label>
|
||||
<div class="field-with-lock">
|
||||
<input pInputText id="authorAsin" formControlName="asin"/>
|
||||
@if (!form.get('asinLocked')?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('asin')" severity="success"></p-button>
|
||||
}
|
||||
@if (form.get('asinLocked')?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('asin')" severity="warn"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field-group description-group">
|
||||
<label for="authorDescription">{{ t('descriptionLabel') }}</label>
|
||||
<div class="field-with-lock description-with-lock">
|
||||
<textarea pTextarea id="authorDescription" formControlName="description"
|
||||
[rows]="8" [autoResize]="true"></textarea>
|
||||
@if (!form.get('descriptionLocked')?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('description')" severity="success" size="small"></p-button>
|
||||
}
|
||||
@if (form.get('descriptionLocked')?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('description')" severity="warn" size="small"></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-footer">
|
||||
<p-divider></p-divider>
|
||||
<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('lockAllBtn')" icon="pi pi-lock" [outlined]="true" severity="warn" (onClick)="lockAll()"></p-button>
|
||||
<p-divider layout="vertical"/>
|
||||
<p-button
|
||||
type="submit"
|
||||
[label]="isSaving ? t('saving') : t('saveBtn')"
|
||||
[icon]="isSaving ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
|
||||
[disabled]="isSaving">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</ng-container>
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
:host {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: calc(100dvh - 11rem);
|
||||
}
|
||||
|
||||
.editor-container {
|
||||
padding: 1rem 0.5rem;
|
||||
display: flex;
|
||||
gap: 2rem;
|
||||
flex: 1;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.cover-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.photo-placeholder {
|
||||
width: 200px;
|
||||
height: 280px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 12px;
|
||||
background: color-mix(in srgb, var(--p-surface-800), transparent 20%);
|
||||
color: #64748b;
|
||||
|
||||
i {
|
||||
font-size: 4rem;
|
||||
}
|
||||
}
|
||||
|
||||
.upload-spinner {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.cover-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding-top: 0.75rem;
|
||||
}
|
||||
|
||||
.fields-section {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.field-group {
|
||||
margin-bottom: 1.25rem;
|
||||
|
||||
label {
|
||||
display: block;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color-secondary);
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
}
|
||||
|
||||
.field-with-lock {
|
||||
display: flex;
|
||||
|
||||
input,
|
||||
textarea {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .field-with-lock input {
|
||||
border-radius: 6px 0 0 6px;
|
||||
}
|
||||
|
||||
.field-with-lock textarea {
|
||||
border-radius: 6px 0 6px 6px;
|
||||
}
|
||||
|
||||
::ng-deep .field-with-lock button {
|
||||
border-color: var(--p-inputtext-border-color) !important;
|
||||
border-radius: 0 6px 6px 0 !important;
|
||||
border-left: 0px !important;
|
||||
}
|
||||
|
||||
.description-with-lock {
|
||||
display: flex;
|
||||
flex-grow: 1;
|
||||
width: 100%;
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.form-footer {
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.footer-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
justify-content: flex-end;
|
||||
padding: 0.5rem 0;
|
||||
|
||||
@media (max-width: 639px) {
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
import {Component, EventEmitter, inject, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
|
||||
import {FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {Button} from 'primeng/button';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Textarea} from 'primeng/textarea';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {Image} from 'primeng/image';
|
||||
import {FileUpload} from 'primeng/fileupload';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorDetails} from '../../model/author.model';
|
||||
import {AuthorPhotoSearchComponent} from '../author-photo-search/author-photo-search.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-author-editor',
|
||||
standalone: true,
|
||||
templateUrl: './author-editor.component.html',
|
||||
styleUrls: ['./author-editor.component.scss'],
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
TranslocoDirective,
|
||||
Button,
|
||||
InputText,
|
||||
Textarea,
|
||||
Tooltip,
|
||||
Image,
|
||||
FileUpload,
|
||||
ProgressSpinner,
|
||||
Divider
|
||||
],
|
||||
providers: [DialogService]
|
||||
})
|
||||
export class AuthorEditorComponent implements OnInit, OnChanges {
|
||||
|
||||
@Input({required: true}) authorId!: number;
|
||||
@Input({required: true}) author!: AuthorDetails;
|
||||
@Output() authorUpdated = new EventEmitter<AuthorDetails>();
|
||||
|
||||
private authorService = inject(AuthorService);
|
||||
private messageService = inject(MessageService);
|
||||
private dialogService = inject(DialogService);
|
||||
private t = inject(TranslocoService);
|
||||
|
||||
form!: FormGroup;
|
||||
isSaving = false;
|
||||
isUploading = false;
|
||||
hasPhoto = true;
|
||||
photoTimestamp = Date.now();
|
||||
|
||||
get photoUrl(): string {
|
||||
return this.authorService.getAuthorPhotoUrl(this.authorId) + '&t=' + this.photoTimestamp;
|
||||
}
|
||||
|
||||
get uploadUrl(): string {
|
||||
return this.authorService.getUploadAuthorPhotoUrl(this.authorId);
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['author'] && !changes['author'].firstChange) {
|
||||
this.hasPhoto = true;
|
||||
this.photoTimestamp = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.form = new FormGroup({
|
||||
name: new FormControl(this.author.name || ''),
|
||||
nameLocked: new FormControl(this.author.nameLocked || false),
|
||||
description: new FormControl(this.author.description || ''),
|
||||
descriptionLocked: new FormControl(this.author.descriptionLocked || false),
|
||||
asin: new FormControl(this.author.asin || ''),
|
||||
asinLocked: new FormControl(this.author.asinLocked || false),
|
||||
photoLocked: new FormControl(this.author.photoLocked || false)
|
||||
});
|
||||
|
||||
this.applyLockStates();
|
||||
}
|
||||
|
||||
toggleLock(field: string): void {
|
||||
const lockedControl = this.form.get(field + 'Locked');
|
||||
if (!lockedControl) return;
|
||||
const isLocked = !lockedControl.value;
|
||||
lockedControl.setValue(isLocked);
|
||||
|
||||
const fieldControl = this.form.get(field);
|
||||
if (fieldControl) {
|
||||
isLocked ? fieldControl.disable() : fieldControl.enable();
|
||||
}
|
||||
|
||||
this.saveMetadata();
|
||||
}
|
||||
|
||||
togglePhotoLock(): void {
|
||||
const lockedControl = this.form.get('photoLocked');
|
||||
if (!lockedControl) return;
|
||||
lockedControl.setValue(!lockedControl.value);
|
||||
this.saveMetadata();
|
||||
}
|
||||
|
||||
onSave(): void {
|
||||
this.saveMetadata();
|
||||
}
|
||||
|
||||
lockAll(): void {
|
||||
for (const field of ['name', 'description', 'asin']) {
|
||||
this.form.get(field + 'Locked')?.setValue(true);
|
||||
this.form.get(field)?.disable();
|
||||
}
|
||||
this.form.get('photoLocked')?.setValue(true);
|
||||
this.saveMetadata();
|
||||
}
|
||||
|
||||
unlockAll(): void {
|
||||
for (const field of ['name', 'description', 'asin']) {
|
||||
this.form.get(field + 'Locked')?.setValue(false);
|
||||
this.form.get(field)?.enable();
|
||||
}
|
||||
this.form.get('photoLocked')?.setValue(false);
|
||||
this.saveMetadata();
|
||||
}
|
||||
|
||||
openPhotoSearch(): void {
|
||||
const ref = this.dialogService.open(AuthorPhotoSearchComponent, {
|
||||
data: {authorId: this.authorId, authorName: this.author.name},
|
||||
header: this.t.translate('authorBrowser.editor.searchPhotoTitle'),
|
||||
width: '70vw',
|
||||
height: '80vh',
|
||||
modal: true,
|
||||
closable: true,
|
||||
dismissableMask: true,
|
||||
contentStyle: {'overflow': 'hidden', 'padding': '0', 'display': 'flex', 'flex-direction': 'column'}
|
||||
});
|
||||
ref?.onClose.subscribe((result: boolean) => {
|
||||
if (result) {
|
||||
this.photoTimestamp = Date.now();
|
||||
this.hasPhoto = true;
|
||||
this.authorUpdated.emit(this.author);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onPhotoError(): void {
|
||||
this.hasPhoto = false;
|
||||
}
|
||||
|
||||
onBeforeUpload(): void {
|
||||
this.isUploading = true;
|
||||
}
|
||||
|
||||
onUpload(): void {
|
||||
this.isUploading = false;
|
||||
this.photoTimestamp = Date.now();
|
||||
this.hasPhoto = true;
|
||||
this.authorUpdated.emit(this.author);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('authorBrowser.editor.toast.photoUploadedSummary'),
|
||||
detail: this.t.translate('authorBrowser.editor.toast.photoUploadedDetail')
|
||||
});
|
||||
}
|
||||
|
||||
onUploadError(): void {
|
||||
this.isUploading = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.editor.toast.errorSummary'),
|
||||
detail: this.t.translate('authorBrowser.editor.toast.photoUploadErrorDetail')
|
||||
});
|
||||
}
|
||||
|
||||
private saveMetadata(): void {
|
||||
if (this.isSaving) return;
|
||||
this.isSaving = true;
|
||||
|
||||
const formValue = this.form.getRawValue();
|
||||
const request = {
|
||||
name: formValue.name?.trim() || undefined,
|
||||
description: formValue.description?.trim(),
|
||||
asin: formValue.asin?.trim(),
|
||||
nameLocked: formValue.nameLocked,
|
||||
descriptionLocked: formValue.descriptionLocked,
|
||||
asinLocked: formValue.asinLocked,
|
||||
photoLocked: formValue.photoLocked
|
||||
};
|
||||
|
||||
this.authorService.updateAuthor(this.authorId, request).subscribe({
|
||||
next: (updated) => {
|
||||
this.isSaving = false;
|
||||
this.authorUpdated.emit(updated);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('authorBrowser.editor.toast.successSummary'),
|
||||
detail: this.t.translate('authorBrowser.editor.toast.successDetail')
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.isSaving = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.editor.toast.errorSummary'),
|
||||
detail: this.t.translate('authorBrowser.editor.toast.errorDetail')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private applyLockStates(): void {
|
||||
for (const field of ['name', 'description', 'asin']) {
|
||||
const lockedControl = this.form.get(field + 'Locked');
|
||||
const fieldControl = this.form.get(field);
|
||||
if (lockedControl?.value && fieldControl) {
|
||||
fieldControl.disable();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<ng-container *transloco="let t; prefix: 'authorBrowser.match'">
|
||||
<div class="match-container">
|
||||
<div class="search-form">
|
||||
<div class="search-fields">
|
||||
<div class="field">
|
||||
<label>{{ t('authorNameLabel') }}</label>
|
||||
<input pInputText type="text" [(ngModel)]="searchQuery" [placeholder]="t('authorNamePlaceholder')" class="search-input"/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t('asinLabel') }}</label>
|
||||
<input pInputText type="text" [(ngModel)]="asinQuery" [placeholder]="t('asinPlaceholder')" class="search-input"/>
|
||||
</div>
|
||||
<div class="field region-field">
|
||||
<label>{{ t('regionLabel') }}</label>
|
||||
<p-select
|
||||
[options]="regionOptions"
|
||||
[(ngModel)]="selectedRegion"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="region-dropdown">
|
||||
</p-select>
|
||||
</div>
|
||||
<div class="field search-btn-field">
|
||||
<p-button
|
||||
[label]="t('searchBtn')"
|
||||
icon="pi pi-search"
|
||||
(onClick)="search()"
|
||||
[loading]="searching"
|
||||
[disabled]="!canSearch">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (searching) {
|
||||
<div class="search-loading">
|
||||
<p-progressSpinner
|
||||
[style]="{'width': '40px', 'height': '40px'}"
|
||||
strokeWidth="3"
|
||||
fill="transparent"
|
||||
animationDuration="1.5s">
|
||||
</p-progressSpinner>
|
||||
<span>{{ t('searching') }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!searching && hasSearched && results.length === 0) {
|
||||
<div class="empty-results">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<p>{{ t('noResults') }}</p>
|
||||
<p class="hint">{{ t('noResultsHint') }}</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!searching && !hasSearched) {
|
||||
<div class="ready-state">
|
||||
<i class="pi pi-search"></i>
|
||||
<p>{{ t('readyToSearch') }}</p>
|
||||
<p class="hint">{{ t('readyToSearchHint') }}</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!searching && results.length > 0) {
|
||||
<div class="results-header">
|
||||
<span>{{ t('resultsFound', {count: results.length}) }}</span>
|
||||
</div>
|
||||
<div class="results-list">
|
||||
@for (result of results; track result.asin) {
|
||||
<div class="result-card">
|
||||
<div class="result-image">
|
||||
@if (result.imageUrl) {
|
||||
<img [src]="result.imageUrl" [alt]="result.name" loading="lazy"/>
|
||||
} @else {
|
||||
<div class="result-placeholder">
|
||||
<i class="pi pi-user"></i>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="result-info">
|
||||
<h4 class="result-name">{{ result.name }}</h4>
|
||||
<span class="result-asin">ASIN: {{ result.asin }}</span>
|
||||
@if (result.description) {
|
||||
<p class="result-description">{{ result.description }}</p>
|
||||
}
|
||||
</div>
|
||||
<div class="result-action">
|
||||
<p-button
|
||||
[label]="t('matchBtn')"
|
||||
icon="pi pi-link"
|
||||
severity="success"
|
||||
[loading]="matching"
|
||||
(onClick)="matchAuthor(result)">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
.match-container {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.search-form {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.search-fields {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
align-items: flex-end;
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
|
||||
label {
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
&:first-child {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.region-field {
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.region-dropdown {
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.search-btn-field {
|
||||
padding-bottom: 1px;
|
||||
}
|
||||
}
|
||||
|
||||
.search-loading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 3rem;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.empty-results,
|
||||
.ready-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
|
||||
i {
|
||||
font-size: 2.5rem;
|
||||
color: #64748b;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
p {
|
||||
color: #94a3b8;
|
||||
font-size: 1rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 0.85rem;
|
||||
color: #64748b;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.results-header {
|
||||
font-size: 0.9rem;
|
||||
color: #94a3b8;
|
||||
margin-bottom: 1rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.results-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.result-card {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
border-radius: 10px;
|
||||
border: 1px solid color-mix(in srgb, var(--p-surface-500), transparent 60%);
|
||||
background: color-mix(in srgb, var(--p-surface-900), transparent 30%);
|
||||
transition: border-color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: color-mix(in srgb, var(--p-primary-400), transparent 50%);
|
||||
}
|
||||
}
|
||||
|
||||
.result-image {
|
||||
flex-shrink: 0;
|
||||
width: 80px;
|
||||
height: 100px;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: color-mix(in srgb, var(--p-surface-800), transparent 20%);
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
}
|
||||
|
||||
.result-placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
color: #64748b;
|
||||
|
||||
i {
|
||||
font-size: 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
.result-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.result-name {
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
color: #e2e8f0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.result-asin {
|
||||
font-size: 0.8rem;
|
||||
color: #64748b;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.result-description {
|
||||
font-size: 0.85rem;
|
||||
color: #94a3b8;
|
||||
margin: 0.25rem 0 0;
|
||||
line-height: 1.4;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.result-action {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.search-fields {
|
||||
flex-direction: column;
|
||||
|
||||
.search-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.region-field,
|
||||
.region-dropdown {
|
||||
min-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.result-card {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.result-image {
|
||||
width: 60px;
|
||||
height: 75px;
|
||||
}
|
||||
|
||||
.result-action {
|
||||
align-self: flex-end;
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import {Component, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Button} from 'primeng/button';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Select} from 'primeng/select';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorDetails, AuthorMatchRequest, AuthorSearchResult} from '../../model/author.model';
|
||||
|
||||
interface RegionOption {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-author-match',
|
||||
standalone: true,
|
||||
templateUrl: './author-match.component.html',
|
||||
styleUrls: ['./author-match.component.scss'],
|
||||
imports: [
|
||||
FormsModule,
|
||||
Button,
|
||||
InputText,
|
||||
Select,
|
||||
ProgressSpinner,
|
||||
TranslocoDirective
|
||||
]
|
||||
})
|
||||
export class AuthorMatchComponent implements OnInit {
|
||||
|
||||
@Input({required: true}) authorId!: number;
|
||||
@Input({required: true}) authorName!: string;
|
||||
@Output() authorMatched = new EventEmitter<AuthorDetails>();
|
||||
|
||||
private authorService = inject(AuthorService);
|
||||
private messageService = inject(MessageService);
|
||||
private t = inject(TranslocoService);
|
||||
|
||||
searchQuery = '';
|
||||
asinQuery = '';
|
||||
selectedRegion = 'us';
|
||||
searching = false;
|
||||
matching = false;
|
||||
results: AuthorSearchResult[] = [];
|
||||
hasSearched = false;
|
||||
|
||||
regionOptions: RegionOption[] = [
|
||||
{label: 'US', value: 'us'},
|
||||
{label: 'UK', value: 'uk'},
|
||||
{label: 'AU', value: 'au'},
|
||||
{label: 'CA', value: 'ca'},
|
||||
{label: 'IN', value: 'in'},
|
||||
{label: 'FR', value: 'fr'},
|
||||
{label: 'DE', value: 'de'},
|
||||
{label: 'IT', value: 'it'},
|
||||
{label: 'ES', value: 'es'},
|
||||
{label: 'JP', value: 'jp'}
|
||||
];
|
||||
|
||||
ngOnInit(): void {
|
||||
this.searchQuery = this.authorName;
|
||||
}
|
||||
|
||||
get canSearch(): boolean {
|
||||
return !!this.searchQuery.trim() || !!this.asinQuery.trim();
|
||||
}
|
||||
|
||||
search(): void {
|
||||
const asin = this.asinQuery.trim();
|
||||
const query = this.searchQuery.trim();
|
||||
if (!query && !asin) return;
|
||||
this.searching = true;
|
||||
this.results = [];
|
||||
this.hasSearched = true;
|
||||
|
||||
this.authorService.searchAuthorMetadata(this.authorId, query, this.selectedRegion, asin || undefined)
|
||||
.subscribe({
|
||||
next: (results) => {
|
||||
this.results = results;
|
||||
this.searching = false;
|
||||
},
|
||||
error: () => {
|
||||
this.searching = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.match.toast.searchFailedSummary'),
|
||||
detail: this.t.translate('authorBrowser.match.toast.searchFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
matchAuthor(result: AuthorSearchResult): void {
|
||||
this.matching = true;
|
||||
const request: AuthorMatchRequest = {
|
||||
source: result.source,
|
||||
asin: result.asin,
|
||||
region: this.selectedRegion
|
||||
};
|
||||
|
||||
this.authorService.matchAuthor(this.authorId, request).subscribe({
|
||||
next: (updatedAuthor) => {
|
||||
this.matching = false;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('authorBrowser.match.toast.matchSuccessSummary'),
|
||||
detail: this.t.translate('authorBrowser.match.toast.matchSuccessDetail'),
|
||||
life: 3000
|
||||
});
|
||||
this.authorMatched.emit(updatedAuthor);
|
||||
},
|
||||
error: () => {
|
||||
this.matching = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.match.toast.matchFailedSummary'),
|
||||
detail: this.t.translate('authorBrowser.match.toast.matchFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
<ng-container *transloco="let t; prefix: 'authorBrowser.photoSearch'">
|
||||
<div class="photo-search-container">
|
||||
<div class="search-section">
|
||||
<form [formGroup]="searchForm" (ngSubmit)="onSearch()">
|
||||
<div class="form-row">
|
||||
<div class="form-field">
|
||||
<label for="photoQuery">
|
||||
<i class="pi pi-user"></i>
|
||||
{{ t('queryLabel') }}
|
||||
</label>
|
||||
<input
|
||||
pInputText
|
||||
id="photoQuery"
|
||||
formControlName="query"
|
||||
[placeholder]="t('queryPlaceholder')"/>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<p-button
|
||||
type="submit"
|
||||
[label]="t('searchBtn')"
|
||||
icon="pi pi-search"
|
||||
[loading]="searching"
|
||||
[disabled]="searchForm.invalid">
|
||||
</p-button>
|
||||
<p-button
|
||||
type="button"
|
||||
icon="pi pi-refresh"
|
||||
[text]="true"
|
||||
[rounded]="true"
|
||||
severity="secondary"
|
||||
(click)="onClear()"
|
||||
[pTooltip]="t('resetTooltip')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="results-section">
|
||||
@if (!hasSearched) {
|
||||
<div class="empty-state">
|
||||
<div class="empty-state-icon">
|
||||
<i class="pi pi-images"></i>
|
||||
</div>
|
||||
<h3>{{ t('readyTitle') }}</h3>
|
||||
<p>{{ t('readyHint') }}</p>
|
||||
</div>
|
||||
} @else if (searching) {
|
||||
<div class="loading-state">
|
||||
<p-progressSpinner strokeWidth="3" animationDuration="1s"></p-progressSpinner>
|
||||
<p>{{ t('searching') }}</p>
|
||||
</div>
|
||||
} @else if (photos.length === 0) {
|
||||
<div class="empty-state no-results">
|
||||
<div class="empty-state-icon warning">
|
||||
<i class="pi pi-search"></i>
|
||||
</div>
|
||||
<h3>{{ t('noResults') }}</h3>
|
||||
<p>{{ t('noResultsHint') }}</p>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="results-header">
|
||||
<span class="results-count">
|
||||
<i class="pi pi-images"></i>
|
||||
{{ t('resultsFound', { count: photos.length }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="photos-grid">
|
||||
@for (photo of photos; track photo.url; let i = $index) {
|
||||
<div class="photo-card">
|
||||
<div class="photo-image-wrapper">
|
||||
<p-image
|
||||
[src]="photo.url"
|
||||
[alt]="t('photoAlt', { index: i + 1 })"
|
||||
appendTo="body"
|
||||
[preview]="true">
|
||||
</p-image>
|
||||
@if (photo.width && photo.height) {
|
||||
<div class="resolution-badge">
|
||||
{{ photo.width }} x {{ photo.height }}
|
||||
</div>
|
||||
}
|
||||
<div class="photo-overlay">
|
||||
<p-button
|
||||
(click)="selectAndUploadPhoto(photo)"
|
||||
[label]="t('selectBtn')"
|
||||
icon="pi pi-check"
|
||||
size="small">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
:host {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.photo-search-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 0 1.5rem 1.5rem 1.5rem;
|
||||
}
|
||||
|
||||
.search-section {
|
||||
flex-shrink: 0;
|
||||
background: var(--surface-ground);
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 12px;
|
||||
padding: 1.25rem 1.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.form-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
flex: 1;
|
||||
|
||||
label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-color-secondary);
|
||||
|
||||
i {
|
||||
font-size: 0.875rem;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding-bottom: 1px;
|
||||
}
|
||||
}
|
||||
|
||||
.results-section {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.empty-state,
|
||||
.loading-state {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem;
|
||||
text-align: center;
|
||||
background: var(--surface-ground);
|
||||
border: 1px dashed var(--surface-border);
|
||||
border-radius: 12px;
|
||||
|
||||
h3 {
|
||||
margin: 0 0 0.5rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-color-secondary);
|
||||
max-width: 300px;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state-icon {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(135deg, var(--primary-100), var(--primary-50));
|
||||
border-radius: 50%;
|
||||
margin-bottom: 1.5rem;
|
||||
|
||||
i {
|
||||
font-size: 2rem;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
&.warning {
|
||||
background: linear-gradient(135deg, var(--yellow-100), var(--yellow-50));
|
||||
|
||||
i {
|
||||
color: var(--yellow-600);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.loading-state {
|
||||
p {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.results-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
padding-bottom: 0.75rem;
|
||||
border-bottom: 1px solid var(--surface-border);
|
||||
|
||||
.results-count {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
|
||||
i {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.photos-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
gap: 1.25rem;
|
||||
padding: 0.25rem;
|
||||
}
|
||||
|
||||
.photo-card {
|
||||
.photo-image-wrapper {
|
||||
position: relative;
|
||||
width: 150px;
|
||||
height: 200px;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--surface-ground);
|
||||
border: 2px solid transparent;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary-color);
|
||||
|
||||
.photo-overlay {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep {
|
||||
.p-image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.p-image-preview {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.resolution-badge {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 6px;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
color: white;
|
||||
padding: 3px 6px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.photo-overlay {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.5rem;
|
||||
background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
|
||||
opacity: 0;
|
||||
z-index: 3;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.search-section .form-row {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
.form-actions {
|
||||
flex-direction: row;
|
||||
justify-content: flex-end;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.photos-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||
import {Button} from 'primeng/button';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {Image} from 'primeng/image';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {finalize} from 'rxjs/operators';
|
||||
import {AuthorService} from '../../service/author.service';
|
||||
import {AuthorPhotoResult} from '../../model/author.model';
|
||||
|
||||
@Component({
|
||||
selector: 'app-author-photo-search',
|
||||
templateUrl: './author-photo-search.component.html',
|
||||
styleUrls: ['./author-photo-search.component.scss'],
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
Button,
|
||||
InputText,
|
||||
ProgressSpinner,
|
||||
Image,
|
||||
Tooltip,
|
||||
TranslocoDirective
|
||||
]
|
||||
})
|
||||
export class AuthorPhotoSearchComponent implements OnInit {
|
||||
searchForm: FormGroup;
|
||||
photos: AuthorPhotoResult[] = [];
|
||||
searching = 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;
|
||||
|
||||
constructor() {
|
||||
this.searchForm = this.fb.group({
|
||||
query: ['', Validators.required]
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.authorId = this.dynamicDialogConfig.data.authorId;
|
||||
const authorName = this.dynamicDialogConfig.data.authorName;
|
||||
|
||||
if (authorName) {
|
||||
this.searchForm.patchValue({query: authorName});
|
||||
if (this.searchForm.valid) {
|
||||
this.onSearch();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onSearch(): void {
|
||||
if (!this.searchForm.valid) return;
|
||||
this.searching = true;
|
||||
|
||||
this.authorService.searchAuthorPhotos(this.authorId, this.searchForm.value.query)
|
||||
.pipe(finalize(() => this.searching = false))
|
||||
.subscribe({
|
||||
next: (photos) => {
|
||||
this.photos = photos.sort((a, b) => a.index - b.index);
|
||||
this.hasSearched = true;
|
||||
},
|
||||
error: () => {
|
||||
this.photos = [];
|
||||
this.hasSearched = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
selectAndUploadPhoto(photo: AuthorPhotoResult): void {
|
||||
this.authorService.uploadAuthorPhotoFromUrl(this.authorId, photo.url).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('authorBrowser.editor.toast.photoUploadedSummary'),
|
||||
detail: this.t.translate('authorBrowser.editor.toast.photoUploadedDetail')
|
||||
});
|
||||
this.dynamicDialogRef.close(true);
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('authorBrowser.editor.toast.errorSummary'),
|
||||
detail: this.t.translate('authorBrowser.editor.toast.photoUploadErrorDetail')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onClear(): void {
|
||||
this.searchForm.reset();
|
||||
this.photos = [];
|
||||
this.hasSearched = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
export interface AuthorSummary {
|
||||
id: number;
|
||||
name: string;
|
||||
asin?: string;
|
||||
bookCount: number;
|
||||
hasPhoto: boolean;
|
||||
}
|
||||
|
||||
export interface EnrichedAuthor extends AuthorSummary {
|
||||
libraryIds: Set<number>;
|
||||
libraryNames: string[];
|
||||
categories: string[];
|
||||
readStatus: 'all-read' | 'some-read' | 'in-progress' | 'unread';
|
||||
hasSeries: boolean;
|
||||
seriesCount: number;
|
||||
latestAddedOn: string | null;
|
||||
lastReadTime: string | null;
|
||||
readingProgress: number;
|
||||
avgPersonalRating: number | null;
|
||||
}
|
||||
|
||||
export interface AuthorFilters {
|
||||
matchStatus: 'all' | 'matched' | 'unmatched';
|
||||
photoStatus: 'all' | 'has-photo' | 'no-photo';
|
||||
readStatus: 'all' | 'all-read' | 'some-read' | 'in-progress' | 'unread';
|
||||
bookCount: 'all' | '0' | '1' | '2' | '3' | '4' | '5' | '6-10' | '11-20' | '21-35' | '36+';
|
||||
library: string;
|
||||
genre: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_AUTHOR_FILTERS: AuthorFilters = {
|
||||
matchStatus: 'all',
|
||||
photoStatus: 'all',
|
||||
readStatus: 'all',
|
||||
bookCount: 'all',
|
||||
library: 'all',
|
||||
genre: 'all'
|
||||
};
|
||||
|
||||
export interface AuthorDetails {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string;
|
||||
asin?: string;
|
||||
nameLocked: boolean;
|
||||
descriptionLocked: boolean;
|
||||
asinLocked: boolean;
|
||||
photoLocked: boolean;
|
||||
}
|
||||
|
||||
export interface AuthorSearchResult {
|
||||
source: string;
|
||||
asin: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
imageUrl?: string;
|
||||
}
|
||||
|
||||
export interface AuthorMatchRequest {
|
||||
source: string;
|
||||
asin: string;
|
||||
region: string;
|
||||
}
|
||||
|
||||
export interface AuthorPhotoResult {
|
||||
url: string;
|
||||
width: number;
|
||||
height: number;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export interface AuthorUpdateRequest {
|
||||
name?: string;
|
||||
description?: string;
|
||||
asin?: string;
|
||||
nameLocked?: boolean;
|
||||
descriptionLocked?: boolean;
|
||||
asinLocked?: boolean;
|
||||
photoLocked?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {AuthorSummary} from '../model/author.model';
|
||||
import {AUTHORS_QUERY_KEY} from './author-query-keys';
|
||||
|
||||
export function patchAuthorInCache(queryClient: QueryClient, authorId: number, fields: Partial<AuthorSummary>): void {
|
||||
queryClient.setQueryData<AuthorSummary[]>(AUTHORS_QUERY_KEY, current =>
|
||||
(current ?? []).map(author => author.id === authorId ? {...author, ...fields} : author)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export const AUTHORS_QUERY_KEY = ['authors'] as const;
|
||||
@@ -0,0 +1,56 @@
|
||||
import {inject, Injectable, signal} from '@angular/core';
|
||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthorScalePreferenceService {
|
||||
|
||||
private readonly DEBOUNCE_MS = 1000;
|
||||
private readonly STORAGE_KEY = 'authorScalePreference';
|
||||
|
||||
private readonly localStorageService = inject(LocalStorageService);
|
||||
|
||||
private readonly _scaleFactor = signal(1.0);
|
||||
readonly scaleFactor = this._scaleFactor.asReadonly();
|
||||
|
||||
private saveTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
private lastPersistedScale = 1.0;
|
||||
|
||||
constructor() {
|
||||
const initialScale = this.loadScaleFromStorage();
|
||||
this._scaleFactor.set(initialScale);
|
||||
this.lastPersistedScale = initialScale;
|
||||
}
|
||||
|
||||
setScale(scale: number): void {
|
||||
this._scaleFactor.set(scale);
|
||||
if (scale === this.lastPersistedScale) {
|
||||
return;
|
||||
}
|
||||
this.scheduleSave(scale);
|
||||
}
|
||||
|
||||
private scheduleSave(scale: number): void {
|
||||
if (this.saveTimeout) {
|
||||
clearTimeout(this.saveTimeout);
|
||||
}
|
||||
|
||||
this.saveTimeout = setTimeout(() => {
|
||||
this.saveScalePreference(scale);
|
||||
}, this.DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
private saveScalePreference(scale: number): void {
|
||||
this.localStorageService.set(this.STORAGE_KEY, scale);
|
||||
this.lastPersistedScale = scale;
|
||||
}
|
||||
|
||||
private loadScaleFromStorage(): number {
|
||||
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
|
||||
if (saved !== null && !isNaN(saved)) {
|
||||
return saved;
|
||||
}
|
||||
return 1.0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import {computed, Injectable, signal} from '@angular/core';
|
||||
import {AuthorSummary} from '../model/author.model';
|
||||
|
||||
export interface AuthorCheckboxClickEvent {
|
||||
index: number;
|
||||
author: AuthorSummary;
|
||||
selected: boolean;
|
||||
shiftKey: boolean;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class AuthorSelectionService {
|
||||
private readonly _selectedAuthors = signal<Set<number>>(new Set());
|
||||
readonly selectedAuthors = this._selectedAuthors.asReadonly();
|
||||
readonly selectedCount = computed(() => this._selectedAuthors().size);
|
||||
|
||||
private currentAuthors: AuthorSummary[] = [];
|
||||
private lastSelectedIndex: number | null = null;
|
||||
|
||||
setCurrentAuthors(authors: AuthorSummary[]): void {
|
||||
this.currentAuthors = authors;
|
||||
}
|
||||
|
||||
handleCheckboxClick(event: AuthorCheckboxClickEvent): void {
|
||||
const {index, author, selected, shiftKey} = event;
|
||||
|
||||
if (!shiftKey || this.lastSelectedIndex === null) {
|
||||
if (selected) {
|
||||
this.select(author.id);
|
||||
} else {
|
||||
this.deselect(author.id);
|
||||
}
|
||||
this.lastSelectedIndex = index;
|
||||
} else {
|
||||
const start = Math.min(this.lastSelectedIndex, index);
|
||||
const end = Math.max(this.lastSelectedIndex, index);
|
||||
for (let i = start; i <= end; i++) {
|
||||
const a = this.currentAuthors[i];
|
||||
if (!a) continue;
|
||||
if (selected) {
|
||||
this.select(a.id);
|
||||
} else {
|
||||
this.deselect(a.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
selectAll(): void {
|
||||
this._selectedAuthors.update(current => {
|
||||
const next = new Set(current);
|
||||
for (const author of this.currentAuthors) {
|
||||
next.add(author.id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
deselectAll(): void {
|
||||
this._selectedAuthors.set(new Set());
|
||||
this.lastSelectedIndex = null;
|
||||
}
|
||||
|
||||
getSelectedIds(): number[] {
|
||||
return Array.from(this.selectedAuthors());
|
||||
}
|
||||
|
||||
private select(id: number): void {
|
||||
this._selectedAuthors.update(current => {
|
||||
const next = new Set(current);
|
||||
next.add(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
private deselect(id: number): void {
|
||||
this._selectedAuthors.update(current => {
|
||||
const next = new Set(current);
|
||||
next.delete(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import {computed, effect, inject, Injectable} from '@angular/core';
|
||||
import {HttpClient, HttpHeaders} from '@angular/common/http';
|
||||
import {lastValueFrom, Observable} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {SseClient} from 'ngx-sse-client';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {AuthorSummary, AuthorDetails, AuthorSearchResult, AuthorMatchRequest, AuthorUpdateRequest, AuthorPhotoResult} from '../model/author.model';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {AUTHORS_QUERY_KEY} from './author-query-keys';
|
||||
import {patchAuthorInCache} from './author-query-cache';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthorService {
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private authService = inject(AuthService);
|
||||
private sseClient = inject(SseClient);
|
||||
private queryClient = inject(QueryClient);
|
||||
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/authors`;
|
||||
private readonly mediaBaseUrl = `${API_CONFIG.BASE_URL}/api/v1/media`;
|
||||
private readonly token = this.authService.token;
|
||||
|
||||
private authorsQuery = injectQuery(() => ({
|
||||
...this.getAuthorsQueryOptions(),
|
||||
enabled: !!this.token(),
|
||||
}));
|
||||
|
||||
allAuthors = computed(() => this.authorsQuery.data() ?? null);
|
||||
isAuthorsLoading = computed(() => !!this.token() && this.authorsQuery.isPending());
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const token = this.token();
|
||||
if (token === null) {
|
||||
this.queryClient.removeQueries({queryKey: AUTHORS_QUERY_KEY});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getAuthorsQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: AUTHORS_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<AuthorSummary[]>(this.baseUrl))
|
||||
});
|
||||
}
|
||||
|
||||
invalidateAuthors(): void {
|
||||
void this.queryClient.invalidateQueries({queryKey: AUTHORS_QUERY_KEY, exact: true});
|
||||
}
|
||||
|
||||
patchAuthorInCache(authorId: number, fields: Partial<AuthorSummary>): void {
|
||||
patchAuthorInCache(this.queryClient, authorId, fields);
|
||||
}
|
||||
|
||||
getAuthorDetails(authorId: number): Observable<AuthorDetails> {
|
||||
return this.http.get<AuthorDetails>(`${this.baseUrl}/${authorId}`);
|
||||
}
|
||||
|
||||
getAuthorByName(name: string): Observable<AuthorDetails> {
|
||||
return this.http.get<AuthorDetails>(`${this.baseUrl}/by-name`, {params: {name}});
|
||||
}
|
||||
|
||||
searchAuthorMetadata(authorId: number, query: string, region: string, asin?: string): Observable<AuthorSearchResult[]> {
|
||||
const params: Record<string, string> = {region};
|
||||
if (asin) {
|
||||
params['asin'] = asin;
|
||||
} else {
|
||||
params['q'] = query;
|
||||
}
|
||||
return this.http.get<AuthorSearchResult[]>(`${this.baseUrl}/${authorId}/search-metadata`, {params});
|
||||
}
|
||||
|
||||
matchAuthor(authorId: number, request: AuthorMatchRequest): Observable<AuthorDetails> {
|
||||
return this.http.post<AuthorDetails>(`${this.baseUrl}/${authorId}/match`, request);
|
||||
}
|
||||
|
||||
quickMatchAuthor(authorId: number, region: string = 'us'): Observable<AuthorDetails> {
|
||||
return this.http.post<AuthorDetails>(`${this.baseUrl}/${authorId}/quick-match`, null, {
|
||||
params: {region}
|
||||
});
|
||||
}
|
||||
|
||||
autoMatchAuthors(authorIds: number[]): Observable<AuthorSummary> {
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
const headers = new HttpHeaders()
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
|
||||
return this.sseClient.stream(
|
||||
`${this.baseUrl}/auto-match`,
|
||||
{keepAlive: false, reconnectionDelay: 1000, responseType: 'event'},
|
||||
{headers, body: authorIds, withCredentials: true},
|
||||
'POST'
|
||||
).pipe(
|
||||
map(event => {
|
||||
if (event.type === 'error') {
|
||||
throw new Error((event as ErrorEvent).message);
|
||||
}
|
||||
return JSON.parse((event as MessageEvent).data) as AuthorSummary;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateAuthor(authorId: number, request: AuthorUpdateRequest): Observable<AuthorDetails> {
|
||||
return this.http.put<AuthorDetails>(`${this.baseUrl}/${authorId}`, request);
|
||||
}
|
||||
|
||||
unmatchAuthors(authorIds: number[]): Observable<void> {
|
||||
return this.http.post<void>(`${this.baseUrl}/unmatch`, authorIds);
|
||||
}
|
||||
|
||||
deleteAuthors(authorIds: number[]): Observable<void> {
|
||||
return this.http.delete<void>(this.baseUrl, {body: authorIds});
|
||||
}
|
||||
|
||||
searchAuthorPhotos(authorId: number, query: string): Observable<AuthorPhotoResult[]> {
|
||||
return this.http.get<AuthorPhotoResult[]>(`${this.baseUrl}/${authorId}/search-photos`, {
|
||||
params: {q: query}
|
||||
});
|
||||
}
|
||||
|
||||
uploadAuthorPhotoFromUrl(authorId: number, imageUrl: string): Observable<void> {
|
||||
return this.http.post<void>(`${this.baseUrl}/${authorId}/photo/url`, null, {
|
||||
params: {url: imageUrl}
|
||||
});
|
||||
}
|
||||
|
||||
getUploadAuthorPhotoUrl(authorId: number): string {
|
||||
return `${this.baseUrl}/${authorId}/photo/upload`;
|
||||
}
|
||||
|
||||
getAuthorPhotoUrl(authorId: number): string {
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
let url = `${this.mediaBaseUrl}/author/${authorId}/photo`;
|
||||
if (token) {
|
||||
url += `?token=${token}`;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
getAuthorThumbnailUrl(authorId: number, cacheBuster?: number): string {
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
let url = `${this.mediaBaseUrl}/author/${authorId}/thumbnail`;
|
||||
if (token) {
|
||||
url += `?token=${token}`;
|
||||
}
|
||||
if (cacheBuster) {
|
||||
url += (token ? '&' : '?') + 't=' + cacheBuster;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.addPhysicalBook'">
|
||||
<div class="add-physical-book">
|
||||
<div class="panel-header">
|
||||
<div class="header-icon-wrapper">
|
||||
<i class="pi pi-book header-icon"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h2 class="panel-title">{{ t('title') }}</h2>
|
||||
<p class="panel-description">{{ t('description') }}</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
(click)="cancel()"
|
||||
severity="secondary"
|
||||
[text]="true"
|
||||
[rounded]="true"
|
||||
class="close-button"
|
||||
[pTooltip]="t('closeTooltip')"
|
||||
tooltipPosition="left"/>
|
||||
</div>
|
||||
|
||||
<div class="form-container">
|
||||
<div class="form-group highlight-group">
|
||||
<label for="library" class="form-label">
|
||||
<i class="pi pi-folder label-icon"></i>
|
||||
{{ t('libraryLabel') }}
|
||||
<span class="required-indicator">*</span>
|
||||
</label>
|
||||
<p-select
|
||||
id="library"
|
||||
[options]="libraries"
|
||||
[(ngModel)]="selectedLibraryId"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[placeholder]="t('libraryPlaceholder')"
|
||||
[style]="{'width': '100%'}"/>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="top-section">
|
||||
@if (coverUrl) {
|
||||
<div class="cover-preview">
|
||||
<img [src]="coverUrl" alt="Book cover"/>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="top-fields">
|
||||
<div class="form-row">
|
||||
<div class="form-group highlight-group flex-2">
|
||||
<label for="title" class="form-label">
|
||||
<i class="pi pi-tag label-icon"></i>
|
||||
{{ t('titleLabel') }}
|
||||
</label>
|
||||
<div class="input-wrapper">
|
||||
<input
|
||||
id="title"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="title"
|
||||
class="input-full"
|
||||
[placeholder]="t('titlePlaceholder')"
|
||||
[class.filled]="title.trim()"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="isbn" class="form-label">
|
||||
<i class="pi pi-barcode label-icon"></i>
|
||||
{{ t('isbnLabel') }}
|
||||
</label>
|
||||
<div class="isbn-input-row">
|
||||
<input
|
||||
id="isbn"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="isbn"
|
||||
class="input-full"
|
||||
[placeholder]="t('isbnPlaceholder')"/>
|
||||
<p-button
|
||||
icon="pi pi-search"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="info"
|
||||
(onClick)="fetchMetadataByIsbn()"
|
||||
[disabled]="!isbn.trim() || isFetchingMetadata"
|
||||
[loading]="isFetchingMetadata"
|
||||
[pTooltip]="t('fetchMetadataTooltip')"
|
||||
tooltipPosition="top"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group highlight-group">
|
||||
<label for="authors" class="form-label">
|
||||
<i class="pi pi-user label-icon"></i>
|
||||
{{ t('authorsLabel') }}
|
||||
</label>
|
||||
<div class="autocomplete-wrapper">
|
||||
<p-autoComplete
|
||||
appendTo="body"
|
||||
[(ngModel)]="authors"
|
||||
[multiple]="true"
|
||||
[fluid]="true"
|
||||
[dropdown]="false"
|
||||
[suggestions]="filteredAuthors"
|
||||
[forceSelection]="false"
|
||||
[showClear]="false"
|
||||
[placeholder]="t('authorsPlaceholder')"
|
||||
(completeMethod)="filterAuthors($event)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp('authors', $event)"
|
||||
(onSelect)="onAutoCompleteSelect('authors', $event)">
|
||||
</p-autoComplete>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-group highlight-group">
|
||||
<label for="description" class="form-label">
|
||||
<i class="pi pi-align-left label-icon"></i>
|
||||
{{ t('descriptionLabel') }}
|
||||
</label>
|
||||
<textarea
|
||||
id="description"
|
||||
pTextarea
|
||||
[(ngModel)]="description"
|
||||
rows="3"
|
||||
[placeholder]="t('descriptionPlaceholder')"
|
||||
class="input-full"></textarea>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="publisher" class="form-label">
|
||||
<i class="pi pi-building label-icon"></i>
|
||||
{{ t('publisherLabel') }}
|
||||
</label>
|
||||
<input
|
||||
id="publisher"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="publisher"
|
||||
class="input-full"
|
||||
[placeholder]="t('publisherPlaceholder')"/>
|
||||
</div>
|
||||
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="publishedDate" class="form-label">
|
||||
<i class="pi pi-calendar label-icon"></i>
|
||||
{{ t('publishedDateLabel') }}
|
||||
</label>
|
||||
<input
|
||||
id="publishedDate"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="publishedDate"
|
||||
class="input-full"
|
||||
[placeholder]="t('publishedDatePlaceholder')"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="language" class="form-label">
|
||||
<i class="pi pi-globe label-icon"></i>
|
||||
{{ t('languageLabel') }}
|
||||
</label>
|
||||
<input
|
||||
id="language"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="language"
|
||||
class="input-full"
|
||||
[placeholder]="t('languagePlaceholder')"/>
|
||||
</div>
|
||||
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="pageCount" class="form-label">
|
||||
<i class="pi pi-file label-icon"></i>
|
||||
{{ t('pageCountLabel') }}
|
||||
</label>
|
||||
<p-inputnumber
|
||||
id="pageCount"
|
||||
[(ngModel)]="pageCount"
|
||||
[useGrouping]="false"
|
||||
[placeholder]="t('pageCountPlaceholder')"
|
||||
class="input-full">
|
||||
</p-inputnumber>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-group highlight-group">
|
||||
<label for="categories" class="form-label">
|
||||
<i class="pi pi-tags label-icon"></i>
|
||||
{{ t('categoriesLabel') }}
|
||||
</label>
|
||||
<div class="autocomplete-wrapper">
|
||||
<p-autoComplete
|
||||
appendTo="body"
|
||||
[(ngModel)]="categories"
|
||||
[multiple]="true"
|
||||
[fluid]="true"
|
||||
[dropdown]="false"
|
||||
[suggestions]="filteredCategories"
|
||||
[forceSelection]="false"
|
||||
[showClear]="true"
|
||||
[placeholder]="t('categoriesPlaceholder')"
|
||||
(completeMethod)="filterCategories($event)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp('categories', $event)"
|
||||
(onSelect)="onAutoCompleteSelect('categories', $event)">
|
||||
</p-autoComplete>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dialog-footer">
|
||||
<div class="validation-status">
|
||||
@if (!selectedLibraryId) {
|
||||
<div class="validation-message error">
|
||||
<i class="pi pi-exclamation-circle"></i>
|
||||
<span>{{ t('validationLibraryRequired') }}</span>
|
||||
</div>
|
||||
} @else if (!title.trim() && !isbn.trim()) {
|
||||
<div class="validation-message error">
|
||||
<i class="pi pi-exclamation-circle"></i>
|
||||
<span>{{ t('validationTitleOrIsbn') }}</span>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="validation-message success">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
<span>{{ t('validationReady') }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="footer-actions">
|
||||
<p-button
|
||||
[label]="t('cancelButton')"
|
||||
severity="secondary"
|
||||
[outlined]="true"
|
||||
(onClick)="cancel()"/>
|
||||
<p-button
|
||||
[label]="t('addButton')"
|
||||
icon="pi pi-plus"
|
||||
severity="success"
|
||||
(onClick)="createBook()"
|
||||
[disabled]="!canCreate() || isLoading"
|
||||
[loading]="isLoading"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
@use '../../../../shared/styles/panel-shared' as panel;
|
||||
|
||||
.add-physical-book {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 700px;
|
||||
max-height: 90vh;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
min-width: auto;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
@include panel.panel-header;
|
||||
}
|
||||
|
||||
.form-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 1.25rem;
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-top: none;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
|
||||
overflow-y: auto;
|
||||
max-height: calc(90vh - 200px);
|
||||
|
||||
@media (max-width: 480px) {
|
||||
padding: 0.75rem;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
|
||||
@media (max-width: 640px) {
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.flex-1 {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.flex-2 {
|
||||
flex: 2;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
|
||||
&.highlight-group {
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
gap: 0.25rem;
|
||||
|
||||
&.highlight-group {
|
||||
padding: 0.375rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.form-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
|
||||
.label-icon {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.required-indicator {
|
||||
color: var(--p-red-500);
|
||||
margin-left: 0.125rem;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
.input-wrapper {
|
||||
position: relative;
|
||||
|
||||
.input-full {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
.input-full {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.isbn-input-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
|
||||
.input-full {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.top-section {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
align-items: flex-start;
|
||||
|
||||
@media (max-width: 640px) {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.top-fields {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.cover-preview {
|
||||
flex-shrink: 0;
|
||||
padding: 0.5rem;
|
||||
|
||||
img {
|
||||
height: 180px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--border-color);
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
img {
|
||||
height: 150px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.autocomplete-wrapper {
|
||||
width: 100%;
|
||||
|
||||
p-autocomplete {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.dialog-footer {
|
||||
@include panel.dialog-footer;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.validation-message {
|
||||
@include panel.validation-message;
|
||||
}
|
||||
|
||||
::ng-deep {
|
||||
.p-inputnumber {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.p-inputnumber-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.p-autocomplete .p-chip .p-chip-label {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.p-autocomplete-input-chip {
|
||||
width: 2rem;
|
||||
}
|
||||
|
||||
.p-autocomplete-clearable ul {
|
||||
padding-inline-end: 2rem !important;
|
||||
}
|
||||
|
||||
.p-autocomplete-clearable .p-autocomplete-clear-icon {
|
||||
right: 0px;
|
||||
margin-top: -1rem;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import {Component, computed, effect, inject} from '@angular/core';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Button} from 'primeng/button';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {Select} from 'primeng/select';
|
||||
import {Textarea} from 'primeng/textarea';
|
||||
import {InputNumber} from 'primeng/inputnumber';
|
||||
import {AutoComplete, AutoCompleteCompleteEvent} from 'primeng/autocomplete';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {BookMetadataService} from '../../service/book-metadata.service';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {CreatePhysicalBookRequest} from '../../model/book.model';
|
||||
import {TranslocoDirective} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
selector: 'app-add-physical-book-dialog',
|
||||
standalone: true,
|
||||
templateUrl: './add-physical-book-dialog.component.html',
|
||||
imports: [
|
||||
FormsModule,
|
||||
Button,
|
||||
InputText,
|
||||
Tooltip,
|
||||
Select,
|
||||
Textarea,
|
||||
InputNumber,
|
||||
AutoComplete,
|
||||
TranslocoDirective
|
||||
],
|
||||
styleUrl: './add-physical-book-dialog.component.scss',
|
||||
})
|
||||
export class AddPhysicalBookDialogComponent {
|
||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
||||
private dialogConfig = inject(DynamicDialogConfig);
|
||||
private bookService = inject(BookService);
|
||||
private bookMetadataService = inject(BookMetadataService);
|
||||
private libraryService = inject(LibraryService);
|
||||
|
||||
selectedLibraryId: number | null = null;
|
||||
title: string = '';
|
||||
isbn: string = '';
|
||||
authors: string[] = [];
|
||||
description: string = '';
|
||||
publisher: string = '';
|
||||
publishedDate: string = '';
|
||||
language: string = '';
|
||||
pageCount: number | null = null;
|
||||
categories: string[] = [];
|
||||
|
||||
private readonly metadata = computed(() => this.bookService.uniqueMetadata());
|
||||
get allAuthors(): string[] { return this.metadata().authors; }
|
||||
get allCategories(): string[] { return this.metadata().categories; }
|
||||
filteredAuthors: string[] = [];
|
||||
filteredCategories: string[] = [];
|
||||
|
||||
coverUrl: string | null = null;
|
||||
isLoading: boolean = false;
|
||||
isFetchingMetadata: boolean = false;
|
||||
private readonly initializeSelectedLibraryEffect = effect(() => {
|
||||
const libraries = this.libraries;
|
||||
if (libraries.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.dialogConfig.data?.libraryId) {
|
||||
this.selectedLibraryId = this.dialogConfig.data.libraryId;
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.selectedLibraryId == null && this.libraries[0].id !== undefined) {
|
||||
this.selectedLibraryId = this.libraries[0].id;
|
||||
}
|
||||
});
|
||||
|
||||
get libraries(): Library[] {
|
||||
return this.libraryService.libraries();
|
||||
}
|
||||
|
||||
filterAuthors(event: AutoCompleteCompleteEvent): void {
|
||||
const query = event.query.toLowerCase();
|
||||
this.filteredAuthors = this.allAuthors.filter((author) =>
|
||||
author.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
filterCategories(event: AutoCompleteCompleteEvent): void {
|
||||
const query = event.query.toLowerCase();
|
||||
this.filteredCategories = this.allCategories.filter((category) =>
|
||||
category.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
onAutoCompleteKeyUp(fieldName: 'authors' | 'categories', event: KeyboardEvent): void {
|
||||
if (event.key === 'Enter') {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const value = input.value?.trim();
|
||||
if (value) {
|
||||
const values = this[fieldName];
|
||||
if (!values.includes(value)) {
|
||||
this[fieldName] = [...values, value];
|
||||
}
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onAutoCompleteSelect(fieldName: 'authors' | 'categories', event: { value: string, originalEvent: Event }): void {
|
||||
const values = this[fieldName];
|
||||
if (!values.includes(event.value)) {
|
||||
this[fieldName] = [...values, event.value];
|
||||
}
|
||||
(event.originalEvent.target as HTMLInputElement).value = '';
|
||||
}
|
||||
|
||||
fetchMetadataByIsbn(): void {
|
||||
const isbnValue = this.isbn.trim();
|
||||
if (!isbnValue || this.isFetchingMetadata) return;
|
||||
|
||||
this.isFetchingMetadata = true;
|
||||
this.bookMetadataService.lookupByIsbn(isbnValue).subscribe({
|
||||
next: (metadata) => {
|
||||
if (metadata.title) this.title = metadata.title;
|
||||
if (metadata.authors?.length) this.authors = [...metadata.authors];
|
||||
if (metadata.description) this.description = metadata.description;
|
||||
if (metadata.publisher) this.publisher = metadata.publisher;
|
||||
if (metadata.publishedDate) this.publishedDate = metadata.publishedDate;
|
||||
if (metadata.language) this.language = metadata.language;
|
||||
if (metadata.pageCount) this.pageCount = metadata.pageCount;
|
||||
if (metadata.categories?.length) this.categories = [...metadata.categories];
|
||||
this.coverUrl = metadata.thumbnailUrl || null;
|
||||
this.isFetchingMetadata = false;
|
||||
},
|
||||
error: () => {
|
||||
this.isFetchingMetadata = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.dynamicDialogRef.close();
|
||||
}
|
||||
|
||||
canCreate(): boolean {
|
||||
return !!this.selectedLibraryId && (!!this.title.trim() || !!this.isbn.trim());
|
||||
}
|
||||
|
||||
createBook(): void {
|
||||
if (!this.canCreate() || this.isLoading) return;
|
||||
|
||||
this.isLoading = true;
|
||||
|
||||
const request: CreatePhysicalBookRequest = {
|
||||
libraryId: this.selectedLibraryId!,
|
||||
title: this.title.trim() || undefined,
|
||||
isbn: this.isbn.trim() || undefined,
|
||||
authors: this.authors.length > 0 ? this.authors : undefined,
|
||||
description: this.description.trim() || undefined,
|
||||
publisher: this.publisher.trim() || undefined,
|
||||
publishedDate: this.publishedDate.trim() || undefined,
|
||||
language: this.language.trim() || undefined,
|
||||
pageCount: this.pageCount ?? undefined,
|
||||
categories: this.categories.length > 0 ? this.categories : undefined,
|
||||
thumbnailUrl: this.coverUrl || undefined
|
||||
};
|
||||
|
||||
this.bookService.createPhysicalBook(request).subscribe({
|
||||
next: (book) => {
|
||||
this.isLoading = false;
|
||||
this.dynamicDialogRef.close(book);
|
||||
},
|
||||
error: () => {
|
||||
this.isLoading = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.fileUploader'">
|
||||
<div class="additional-file-uploader-container">
|
||||
<div class="panel-header">
|
||||
<div class="header-icon-wrapper">
|
||||
<i class="pi pi-file-plus header-icon"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h2 class="panel-title">{{ t('title') }}</h2>
|
||||
<p class="panel-description">{{ book.metadata?.title || t('unknownTitle') }}</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(click)="closeDialog()"
|
||||
class="close-button">
|
||||
</p-button>
|
||||
</div>
|
||||
|
||||
<div class="dialog-content">
|
||||
<!-- File Type Selection -->
|
||||
<p-select
|
||||
[options]="fileTypeOptions"
|
||||
[(ngModel)]="fileType"
|
||||
(ngModelChange)="onFileTypeChange()"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
[placeholder]="t('selectFileType')"
|
||||
class="full-width"
|
||||
[disabled]="isUploading"
|
||||
></p-select>
|
||||
|
||||
<!-- File Upload -->
|
||||
<p-fileupload class="file-upload" name="file"
|
||||
[customUpload]="true"
|
||||
[multiple]="false"
|
||||
[accept]="acceptedFormats"
|
||||
(onSelect)="onFilesSelect($event)"
|
||||
(uploadHandler)="uploadFiles($event)"
|
||||
[disabled]="isUploading">
|
||||
<ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback">
|
||||
<div class="upload-header-actions">
|
||||
<div class="action-buttons">
|
||||
<p-button (onClick)="choose($event, chooseCallback)"
|
||||
icon="pi pi-images"
|
||||
[rounded]="true"
|
||||
[outlined]="true"
|
||||
[disabled]="isChooseDisabled()"/>
|
||||
<p-button (onClick)="uploadEvent(uploadCallback)"
|
||||
icon="pi pi-cloud-upload"
|
||||
[rounded]="true"
|
||||
[outlined]="true"
|
||||
severity="success"
|
||||
[disabled]="isUploadDisabled()"/>
|
||||
<p-button (onClick)="onClear(clearCallback)"
|
||||
icon="pi pi-times"
|
||||
[rounded]="true"
|
||||
[outlined]="true"
|
||||
severity="danger"
|
||||
[disabled]="!filesPresent() || isUploading"/>
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
<ng-template #content let-files let-removeFileCallback="removeFileCallback">
|
||||
<div class="upload-content">
|
||||
@if (files?.length > 0) {
|
||||
<div>
|
||||
<div class="file-list-scroll">
|
||||
<div class="file-list">
|
||||
@for (uploadFile of this.files; track uploadFile; let i = $index) {
|
||||
<div class="file-row">
|
||||
<div class="file-info">
|
||||
<p-badge [value]="getFileStatusLabel(uploadFile)" [severity]="getBadgeSeverity(uploadFile.status)" class="file-badge"/>
|
||||
<span class="file-name">
|
||||
{{ uploadFile.file.name }}
|
||||
</span>
|
||||
<div class="file-size">{{ formatSize(uploadFile.file.size) }}</div>
|
||||
</div>
|
||||
@switch (uploadFile.status) {
|
||||
@case ('Pending') {
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
(click)="onRemoveTemplatingFile($event, uploadFile.file, removeFileCallback, i)"
|
||||
severity="danger"
|
||||
[text]="true"/>
|
||||
}
|
||||
@case ('Uploading') {
|
||||
<i
|
||||
class="pi pi-spin pi-spinner status-icon"
|
||||
style="color: slateblue"
|
||||
[pTooltip]="t('statusUploading')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
}
|
||||
@case ('Uploaded') {
|
||||
<i
|
||||
class="pi pi-check status-icon"
|
||||
style="color: green"
|
||||
[pTooltip]="t('statusUploaded')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
}
|
||||
@case ('Failed') {
|
||||
<i
|
||||
class="pi pi-exclamation-triangle status-icon"
|
||||
style="color: darkred"
|
||||
[pTooltip]="uploadFile.errorMessage || t('statusUploadFailed')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
<ng-template #file></ng-template>
|
||||
<ng-template #empty>
|
||||
<div class="empty-state">
|
||||
<i class="pi pi-cloud-upload empty-icon"></i>
|
||||
<p class="empty-text">{{ t('dragDropText') }}</p>
|
||||
<p class="empty-subtext">
|
||||
@if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
|
||||
<span [innerHTML]="t('supportedFormats')"></span>
|
||||
<br/>
|
||||
} @else {
|
||||
<span>{{ t('supplementaryAllFormats') }}</span>
|
||||
<br/>
|
||||
}
|
||||
{{ t('maxFileSize', { size: maxFileSizeDisplay }) }}
|
||||
</p>
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-fileupload>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
@use '../../../../shared/styles/panel-shared' as panel;
|
||||
|
||||
.additional-file-uploader-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
@include panel.panel-header;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.dialog-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
min-height: 0;
|
||||
padding: 1.5rem;
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-top: none;
|
||||
border-radius: 0 0 10px 10px;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
:host ::ng-deep {
|
||||
.p-fileupload-content p-progressbar {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.full-width {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.file-upload {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.upload-header-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 1;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.upload-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
padding: 0 1rem;
|
||||
}
|
||||
|
||||
.file-list-scroll {
|
||||
max-height: 24rem;
|
||||
max-width: 22rem;
|
||||
overflow-y: auto;
|
||||
padding-right: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
.file-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.file-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.file-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
overflow: hidden;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.file-badge {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.file-size {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-icon {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-icon {
|
||||
border: 2px solid;
|
||||
border-radius: 9999px;
|
||||
padding: 2rem;
|
||||
font-size: 2.25rem;
|
||||
color: var(--p-text-muted-color);
|
||||
}
|
||||
|
||||
.empty-text {
|
||||
margin-top: 1.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.empty-subtext {
|
||||
margin-top: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
import {ChangeDetectorRef, Component, effect, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
|
||||
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Select} from 'primeng/select';
|
||||
import {Button} from 'primeng/button';
|
||||
import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload';
|
||||
import {Badge} from 'primeng/badge';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {Subject} from 'rxjs';
|
||||
import {BookFileService} from '../../service/book-file.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
import {AdditionalFileType, Book} from '../../model/book.model';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface FileTypeOption {
|
||||
label: string;
|
||||
value: AdditionalFileType;
|
||||
}
|
||||
|
||||
interface UploadingFile {
|
||||
file: File;
|
||||
status: 'Pending' | 'Uploading' | 'Uploaded' | 'Failed';
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-additional-file-uploader',
|
||||
standalone: true,
|
||||
imports: [
|
||||
FormsModule,
|
||||
Select,
|
||||
Button,
|
||||
FileUpload,
|
||||
Badge,
|
||||
Tooltip,
|
||||
TranslocoDirective
|
||||
],
|
||||
templateUrl: './additional-file-uploader.component.html',
|
||||
styleUrls: ['./additional-file-uploader.component.scss']
|
||||
})
|
||||
export class AdditionalFileUploaderComponent implements OnInit, OnDestroy {
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
book!: Book;
|
||||
files: UploadingFile[] = [];
|
||||
fileType: AdditionalFileType = AdditionalFileType.ALTERNATIVE_FORMAT;
|
||||
isUploading = false;
|
||||
readonly AdditionalFileType = AdditionalFileType;
|
||||
private static readonly BOOK_FORMAT_ACCEPT = '.pdf,.epub,.cbz,.cbr,.cb7,.fb2,.mobi,.azw,.azw3,.m4b,.m4a,.mp3,.opus';
|
||||
maxFileSizeBytes?: number;
|
||||
maxFileSizeDisplay: string = '100 MB';
|
||||
|
||||
fileTypeOptions: FileTypeOption[] = [];
|
||||
|
||||
@ViewChild(FileUpload) private fileUpload!: FileUpload;
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
constructor(
|
||||
private dialogRef: DynamicDialogRef,
|
||||
private config: DynamicDialogConfig,
|
||||
private bookFileService: BookFileService,
|
||||
private appSettingsService: AppSettingsService,
|
||||
private messageService: MessageService,
|
||||
private cdr: ChangeDetectorRef
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.book = this.config.data.book;
|
||||
this.fileTypeOptions = [
|
||||
{ label: this.t.translate('book.fileUploader.typeAlternativeFormat'), value: AdditionalFileType.ALTERNATIVE_FORMAT },
|
||||
{ label: this.t.translate('book.fileUploader.typeSupplementary'), value: AdditionalFileType.SUPPLEMENTARY }
|
||||
];
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
if (settings) {
|
||||
const maxSizeMb = settings.maxFileUploadSizeInMb || 100;
|
||||
this.maxFileSizeBytes = maxSizeMb * 1024 * 1024;
|
||||
this.maxFileSizeDisplay = `${maxSizeMb} MB`;
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
onFileTypeChange(): void {
|
||||
this.files = [];
|
||||
if (this.fileUpload) {
|
||||
this.fileUpload.clear();
|
||||
}
|
||||
}
|
||||
|
||||
get acceptedFormats(): string {
|
||||
return this.fileType === AdditionalFileType.ALTERNATIVE_FORMAT
|
||||
? AdditionalFileUploaderComponent.BOOK_FORMAT_ACCEPT
|
||||
: '';
|
||||
}
|
||||
|
||||
hasPendingFiles(): boolean {
|
||||
return this.files.some(f => f.status === 'Pending');
|
||||
}
|
||||
|
||||
filesPresent(): boolean {
|
||||
return this.files.length > 0;
|
||||
}
|
||||
|
||||
choose(_event: unknown, chooseCallback: () => void): void {
|
||||
chooseCallback();
|
||||
}
|
||||
|
||||
onClear(clearCallback: () => void): void {
|
||||
clearCallback();
|
||||
this.files = [];
|
||||
}
|
||||
|
||||
onFilesSelect(event: FileSelectEvent): void {
|
||||
const newFiles = event.currentFiles;
|
||||
// Only take the first file for single file upload
|
||||
if (newFiles.length > 0) {
|
||||
const file = newFiles[0];
|
||||
|
||||
if (this.maxFileSizeBytes && file.size > this.maxFileSizeBytes) {
|
||||
const maxSize = this.formatSize(this.maxFileSizeBytes);
|
||||
const errorMsg = this.t.translate('book.fileUploader.toast.fileTooLargeError', { maxSize });
|
||||
this.files = [{
|
||||
file,
|
||||
status: 'Failed',
|
||||
errorMessage: errorMsg
|
||||
}];
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.fileUploader.toast.fileTooLargeSummary'),
|
||||
detail: this.t.translate('book.fileUploader.toast.fileTooLargeDetail', { fileName: file.name, maxSize }),
|
||||
life: 5000
|
||||
});
|
||||
} else {
|
||||
this.files = [{
|
||||
file,
|
||||
status: 'Pending'
|
||||
}];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onRemoveTemplatingFile(_event: unknown, _file: File, removeFileCallback: (event: unknown, index: number) => void, index: number): void {
|
||||
removeFileCallback(_event, index);
|
||||
}
|
||||
|
||||
uploadEvent(uploadCallback: () => void): void {
|
||||
uploadCallback();
|
||||
}
|
||||
|
||||
uploadFiles(event: FileUploadHandlerEvent): void {
|
||||
const filesToUpload = this.files.filter(f => f.status === 'Pending');
|
||||
|
||||
if (filesToUpload.length === 0) return;
|
||||
|
||||
this.isUploading = true;
|
||||
let pending = filesToUpload.length;
|
||||
|
||||
for (const uploadFile of filesToUpload) {
|
||||
uploadFile.status = 'Uploading';
|
||||
|
||||
this.bookFileService.uploadAdditionalFile(
|
||||
this.book.id,
|
||||
uploadFile.file,
|
||||
this.fileType
|
||||
).subscribe({
|
||||
next: () => {
|
||||
uploadFile.status = 'Uploaded';
|
||||
if (--pending === 0) {
|
||||
this.isUploading = false;
|
||||
this.dialogRef.close({ success: true });
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
uploadFile.status = 'Failed';
|
||||
uploadFile.errorMessage = err?.error?.message || this.t.translate('book.fileUploader.toast.uploadFailedUnknown');
|
||||
console.error('Upload failed for', uploadFile.file.name, err);
|
||||
if (--pending === 0) {
|
||||
this.isUploading = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
isChooseDisabled(): boolean {
|
||||
return this.isUploading;
|
||||
}
|
||||
|
||||
isUploadDisabled(): boolean {
|
||||
return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles();
|
||||
}
|
||||
|
||||
formatSize(bytes: number): string {
|
||||
const k = 1024;
|
||||
const dm = 2;
|
||||
if (bytes < k) return `${bytes} B`;
|
||||
if (bytes < k * k) return `${(bytes / k).toFixed(dm)} KB`;
|
||||
return `${(bytes / (k * k)).toFixed(dm)} MB`;
|
||||
}
|
||||
|
||||
getBadgeSeverity(status: UploadingFile['status']): 'info' | 'warn' | 'success' | 'danger' {
|
||||
switch (status) {
|
||||
case 'Pending':
|
||||
return 'warn';
|
||||
case 'Uploading':
|
||||
return 'info';
|
||||
case 'Uploaded':
|
||||
return 'success';
|
||||
case 'Failed':
|
||||
return 'danger';
|
||||
default:
|
||||
return 'info';
|
||||
}
|
||||
}
|
||||
|
||||
getFileStatusLabel(uploadFile: UploadingFile): string {
|
||||
if (uploadFile.status === 'Failed' && uploadFile.errorMessage?.includes('maximum size')) {
|
||||
return this.t.translate('book.fileUploader.statusTooLarge');
|
||||
}
|
||||
switch (uploadFile.status) {
|
||||
case 'Pending':
|
||||
return this.t.translate('book.fileUploader.statusReady');
|
||||
case 'Uploading':
|
||||
return this.t.translate('book.fileUploader.statusUploading');
|
||||
case 'Uploaded':
|
||||
return this.t.translate('book.fileUploader.statusUploaded');
|
||||
case 'Failed':
|
||||
return this.t.translate('book.fileUploader.statusFailed');
|
||||
default:
|
||||
return uploadFile.status;
|
||||
}
|
||||
}
|
||||
|
||||
closeDialog(): void {
|
||||
this.dialogRef.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {ParamMap} from '@angular/router';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
|
||||
import {EntityType} from './book-browser.component';
|
||||
|
||||
export interface EntityInfo {
|
||||
entityId: number;
|
||||
entityType: EntityType;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookBrowserEntityService {
|
||||
private libraryService = inject(LibraryService);
|
||||
private shelfService = inject(ShelfService);
|
||||
private magicShelfService = inject(MagicShelfService);
|
||||
private bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||
|
||||
getEntityInfo(paramMap: ParamMap): EntityInfo {
|
||||
const libraryId = Number(paramMap.get('libraryId') || NaN);
|
||||
const shelfId = Number(paramMap.get('shelfId') || NaN);
|
||||
const magicShelfId = Number(paramMap.get('magicShelfId') || NaN);
|
||||
|
||||
if (!Number.isNaN(libraryId)) {
|
||||
return {entityId: libraryId, entityType: EntityType.LIBRARY};
|
||||
}
|
||||
|
||||
if (!Number.isNaN(shelfId)) {
|
||||
return {entityId: shelfId, entityType: EntityType.SHELF};
|
||||
}
|
||||
|
||||
if (!Number.isNaN(magicShelfId)) {
|
||||
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
|
||||
}
|
||||
|
||||
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
|
||||
}
|
||||
|
||||
getEntity(entityId: number, entityType: EntityType): Library | Shelf | MagicShelf | null {
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return this.libraryService.libraries().find(lib => lib.id === entityId) ?? null;
|
||||
case EntityType.SHELF:
|
||||
return this.shelfService.shelves().find(shelf => shelf.id === entityId) ?? null;
|
||||
case EntityType.MAGIC_SHELF:
|
||||
return this.magicShelfService.findShelfById(entityId) ?? null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
getBooksByEntity(books: Book[], entityId: number, entityType: EntityType): Book[] {
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return books.filter(book => book.libraryId === entityId);
|
||||
case EntityType.SHELF:
|
||||
return books.filter(book => book.shelves?.some(shelf => shelf.id === entityId) ?? false);
|
||||
case EntityType.MAGIC_SHELF: {
|
||||
const magicShelf = this.getEntity(entityId, entityType);
|
||||
return this.isMagicShelf(magicShelf) ? this.filterByMagicShelf(books, magicShelf) : [];
|
||||
}
|
||||
case EntityType.UNSHELVED:
|
||||
return books.filter(book => !book.shelves || book.shelves.length === 0);
|
||||
case EntityType.ALL_BOOKS:
|
||||
default:
|
||||
return books;
|
||||
}
|
||||
}
|
||||
|
||||
isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
|
||||
return (entity as Library).paths !== undefined;
|
||||
}
|
||||
|
||||
isMagicShelf(entity: Library | Shelf | MagicShelf | null): entity is MagicShelf {
|
||||
return !!entity && 'filterJson' in entity;
|
||||
}
|
||||
|
||||
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
|
||||
if (!magicShelf.filterJson) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const groupRule = JSON.parse(magicShelf.filterJson) as GroupRule;
|
||||
return books.filter(book => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule, books));
|
||||
} catch {
|
||||
console.warn('Invalid filterJson for MagicShelf');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {ActivatedRoute, ParamMap, Router} from '@angular/router';
|
||||
import {SortDirection, SortOption} from '../../model/sort.model';
|
||||
import {BookFilterMode, EntityViewPreference, EntityViewPreferences, SortCriterion} from '../../../settings/user-management/user.service';
|
||||
import {EntityType} from './book-browser.component';
|
||||
|
||||
export const QUERY_PARAMS = {
|
||||
VIEW: 'view',
|
||||
SORT: 'sort',
|
||||
DIRECTION: 'direction',
|
||||
FILTER: 'filter',
|
||||
FMODE: 'fmode',
|
||||
SIDEBAR: 'sidebar',
|
||||
FROM: 'from',
|
||||
} as const;
|
||||
|
||||
export const VIEW_MODES = {
|
||||
GRID: 'grid',
|
||||
TABLE: 'table',
|
||||
} as const;
|
||||
|
||||
export const SORT_DIRECTION = {
|
||||
ASCENDING: 'asc',
|
||||
DESCENDING: 'desc',
|
||||
} as const;
|
||||
|
||||
export interface BookBrowserQueryState {
|
||||
viewMode: 'grid' | 'table';
|
||||
sortField: string;
|
||||
sortDirection: SortDirection;
|
||||
filters: Record<string, string[]>;
|
||||
filterMode: BookFilterMode;
|
||||
}
|
||||
|
||||
export interface QueryParseResult {
|
||||
viewMode: string;
|
||||
sortOption: SortOption;
|
||||
sortCriteria: SortOption[];
|
||||
filters: Record<string, string[]>;
|
||||
filterMode: BookFilterMode;
|
||||
viewModeFromToggle: boolean;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookBrowserQueryParamsService {
|
||||
private router = inject(Router);
|
||||
private activatedRoute = inject(ActivatedRoute);
|
||||
|
||||
parseQueryParams(
|
||||
queryParamMap: ParamMap,
|
||||
userPrefs: EntityViewPreferences | undefined,
|
||||
entityType: EntityType | undefined,
|
||||
entityId: number | undefined,
|
||||
sortOptions: SortOption[],
|
||||
defaultFilterMode: BookFilterMode
|
||||
): QueryParseResult {
|
||||
const viewParam = queryParamMap.get(QUERY_PARAMS.VIEW);
|
||||
const sortParam = queryParamMap.get(QUERY_PARAMS.SORT);
|
||||
const directionParam = queryParamMap.get(QUERY_PARAMS.DIRECTION);
|
||||
const filterParams = queryParamMap.get(QUERY_PARAMS.FILTER);
|
||||
const filterModeParam = queryParamMap.get(QUERY_PARAMS.FMODE);
|
||||
const fromParam = queryParamMap.get(QUERY_PARAMS.FROM);
|
||||
|
||||
const filterMode = (filterModeParam || defaultFilterMode) as BookFilterMode;
|
||||
|
||||
// Parse filters
|
||||
const filters = this.deserializeFilters(filterParams);
|
||||
|
||||
// Determine effective preferences
|
||||
const globalPrefs = userPrefs?.global;
|
||||
const currentEntityTypeStr = entityType?.toString().toUpperCase().replaceAll(' ', '_');
|
||||
const override = userPrefs?.overrides?.find(o =>
|
||||
o.entityType?.toUpperCase() === currentEntityTypeStr &&
|
||||
o.entityId === entityId
|
||||
);
|
||||
|
||||
const effectivePrefs: EntityViewPreference = override?.preferences ?? globalPrefs ?? {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'ASC',
|
||||
view: 'GRID',
|
||||
coverSize: 1.0,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
};
|
||||
|
||||
// Parse sort criteria - supports both legacy and new multi-sort format
|
||||
let sortCriteria: SortOption[];
|
||||
|
||||
if (sortParam) {
|
||||
// Check if it's new multi-sort format (contains colons like "author:asc,title:desc")
|
||||
if (sortParam.includes(':')) {
|
||||
sortCriteria = this.deserializeSort(sortParam, sortOptions);
|
||||
} else {
|
||||
// Legacy format: separate sort and direction params
|
||||
const effectiveSortDir = directionParam
|
||||
? (directionParam.toLowerCase() === SORT_DIRECTION.DESCENDING ? SortDirection.DESCENDING : SortDirection.ASCENDING)
|
||||
: SortDirection.ASCENDING;
|
||||
const matchedSort = sortOptions.find(opt => opt.field === sortParam);
|
||||
sortCriteria = matchedSort ? [{
|
||||
label: matchedSort.label,
|
||||
field: matchedSort.field,
|
||||
direction: effectiveSortDir
|
||||
}] : [];
|
||||
}
|
||||
} else {
|
||||
// Use user preferences
|
||||
if (effectivePrefs.sortCriteria && effectivePrefs.sortCriteria.length > 0) {
|
||||
sortCriteria = effectivePrefs.sortCriteria.map((c: SortCriterion) => {
|
||||
const matchedSort = sortOptions.find(opt => opt.field === c.field);
|
||||
return {
|
||||
label: matchedSort?.label ?? c.field,
|
||||
field: c.field,
|
||||
direction: c.direction === 'DESC' ? SortDirection.DESCENDING : SortDirection.ASCENDING
|
||||
};
|
||||
});
|
||||
} else {
|
||||
// Fall back to legacy single sort preference
|
||||
const userSortKey = effectivePrefs.sortKey;
|
||||
const userSortDir = effectivePrefs.sortDir?.toUpperCase() === 'DESC'
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING;
|
||||
const matchedSort = sortOptions.find(opt => opt.field === userSortKey);
|
||||
sortCriteria = matchedSort ? [{
|
||||
label: matchedSort.label,
|
||||
field: matchedSort.field,
|
||||
direction: userSortDir
|
||||
}] : [];
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure we have at least a default sort
|
||||
if (sortCriteria.length === 0) {
|
||||
sortCriteria = [{
|
||||
label: 'Added On',
|
||||
field: 'addedOn',
|
||||
direction: SortDirection.DESCENDING
|
||||
}];
|
||||
}
|
||||
|
||||
// For backward compatibility, expose the first sort as sortOption
|
||||
const sortOption = sortCriteria[0];
|
||||
|
||||
// Determine view mode
|
||||
const viewModeFromToggle = fromParam === 'toggle';
|
||||
const viewMode = viewModeFromToggle
|
||||
? (viewParam === VIEW_MODES.TABLE || viewParam === VIEW_MODES.GRID
|
||||
? viewParam
|
||||
: VIEW_MODES.GRID)
|
||||
: (effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID);
|
||||
|
||||
return {
|
||||
viewMode,
|
||||
sortOption,
|
||||
sortCriteria,
|
||||
filters,
|
||||
filterMode,
|
||||
viewModeFromToggle
|
||||
};
|
||||
}
|
||||
|
||||
updateViewMode(mode: 'grid' | 'table'): void {
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
[QUERY_PARAMS.VIEW]: mode,
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
updateSort(sortOption: SortOption): void {
|
||||
this.updateMultiSort([sortOption]);
|
||||
}
|
||||
|
||||
updateMultiSort(sortCriteria: SortOption[]): void {
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
const newParams = {
|
||||
...currentParams,
|
||||
[QUERY_PARAMS.SORT]: this.serializeSort(sortCriteria),
|
||||
[QUERY_PARAMS.DIRECTION]: null // Remove legacy direction param
|
||||
};
|
||||
|
||||
this.router.navigate([], {
|
||||
queryParams: newParams,
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
serializeSort(criteria: SortOption[]): string {
|
||||
return criteria.map(c =>
|
||||
`${c.field}:${c.direction === SortDirection.ASCENDING ? 'asc' : 'desc'}`
|
||||
).join(',');
|
||||
}
|
||||
|
||||
deserializeSort(sortParam: string, sortOptions: SortOption[]): SortOption[] {
|
||||
const criteria: SortOption[] = [];
|
||||
|
||||
sortParam.split(',').forEach(part => {
|
||||
const [field, dir] = part.split(':');
|
||||
if (field) {
|
||||
const matchedSort = sortOptions.find(opt => opt.field === field);
|
||||
if (matchedSort) {
|
||||
criteria.push({
|
||||
label: matchedSort.label,
|
||||
field: matchedSort.field,
|
||||
direction: dir?.toLowerCase() === 'desc' ? SortDirection.DESCENDING : SortDirection.ASCENDING
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return criteria;
|
||||
}
|
||||
|
||||
updateFilters(filters: Record<string, string[]> | null): void {
|
||||
const queryParam = filters && Object.keys(filters).length > 0
|
||||
? this.serializeFilters(filters)
|
||||
: null;
|
||||
|
||||
if (queryParam !== this.activatedRoute.snapshot.queryParamMap.get(QUERY_PARAMS.FILTER)) {
|
||||
this.router.navigate([], {
|
||||
relativeTo: this.activatedRoute,
|
||||
queryParams: {[QUERY_PARAMS.FILTER]: queryParam},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
updateFilterMode(mode: BookFilterMode, currentFilters: Record<string, string[]>): void {
|
||||
const params: Record<string, string | null> = {[QUERY_PARAMS.FMODE]: mode};
|
||||
|
||||
// Clear filters if switching from multiple selected to single mode
|
||||
if (mode === 'single') {
|
||||
const categories = Object.keys(currentFilters);
|
||||
if (categories.length > 1 || (categories.length === 1 && currentFilters[categories[0]].length > 1)) {
|
||||
params[QUERY_PARAMS.FILTER] = null;
|
||||
}
|
||||
}
|
||||
|
||||
this.router.navigate([], {
|
||||
relativeTo: this.activatedRoute,
|
||||
queryParams: params,
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: false
|
||||
});
|
||||
}
|
||||
|
||||
serializeFilters(filters: Record<string, string[]>): string {
|
||||
return Object.entries(filters)
|
||||
.map(([k, v]) => `${k}:${v.map(val => encodeURIComponent(val)).join('|')}`)
|
||||
.join(',');
|
||||
}
|
||||
|
||||
deserializeFilters(filterParam: string | null): Record<string, string[]> {
|
||||
const parsedFilters: Record<string, string[]> = {};
|
||||
|
||||
if (!filterParam) return parsedFilters;
|
||||
|
||||
filterParam.split(',').forEach(pair => {
|
||||
const [key, ...valueParts] = pair.split(':');
|
||||
const value = valueParts.join(':');
|
||||
if (key && value) {
|
||||
parsedFilters[key] = value.split('|').map(v => decodeURIComponent(v.trim())).filter(Boolean);
|
||||
}
|
||||
});
|
||||
|
||||
return parsedFilters;
|
||||
}
|
||||
|
||||
syncQueryParams(
|
||||
viewMode: string,
|
||||
filterMode: BookFilterMode,
|
||||
filters: Record<string, string[]>
|
||||
): void {
|
||||
const queryParams: Record<string, string | number | null | undefined> = {
|
||||
[QUERY_PARAMS.VIEW]: viewMode,
|
||||
[QUERY_PARAMS.FMODE]: filterMode,
|
||||
};
|
||||
|
||||
if (Object.keys(filters).length > 0) {
|
||||
queryParams[QUERY_PARAMS.FILTER] = this.serializeFilters(filters);
|
||||
}
|
||||
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
const changed = Object.keys(queryParams).some(k => (queryParams[k] ?? undefined) !== (currentParams[k] ?? undefined));
|
||||
|
||||
if (changed) {
|
||||
const mergedParams = {...currentParams, ...queryParams};
|
||||
this.router.navigate([], {
|
||||
queryParams: mergedParams,
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
shouldForceExpandSeries(queryParamMap: ParamMap): boolean {
|
||||
const filterParam = queryParamMap.get(QUERY_PARAMS.FILTER);
|
||||
return (
|
||||
!!filterParam &&
|
||||
typeof filterParam === 'string' &&
|
||||
filterParam.split(',').some(pair => pair.trim().startsWith('series:'))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookBrowserScrollService {
|
||||
private scrollPositions = new Map<string, number>();
|
||||
|
||||
savePosition(key: string, position: number): void {
|
||||
this.scrollPositions.set(key, position);
|
||||
}
|
||||
|
||||
getPosition(key: string): number | undefined {
|
||||
return this.scrollPositions.get(key);
|
||||
}
|
||||
|
||||
clearPosition(key: string): void {
|
||||
this.scrollPositions.delete(key);
|
||||
}
|
||||
|
||||
createKey(path: string, params: Record<string, string>): string {
|
||||
const paramValues = Object.values(params).join('-');
|
||||
return paramValues ? `${path}:${paramValues}` : path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.browser'">
|
||||
<div class="book-browser-container">
|
||||
<div class="book-browser-main">
|
||||
|
||||
<div class="book-browser-header">
|
||||
<div class="entity-info-wrapper">
|
||||
@if (entityType(); as entityType) {
|
||||
<div class="entity-info">
|
||||
<p class="entity-title">
|
||||
@if (entityType === EntityType.ALL_BOOKS) {
|
||||
@if (currentFilterLabel && rawFilterParamFromUrl) {
|
||||
{{ currentFilterLabel }}
|
||||
} @else if (isFilterActive || hasSearchTerm) {
|
||||
{{ computedFilterLabel }}
|
||||
} @else {
|
||||
{{ t('labels.allBooks') }}
|
||||
}
|
||||
} @else if (entityType === EntityType.UNSHELVED) {
|
||||
{{ (isFilterActive || hasSearchTerm) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
|
||||
} @else {
|
||||
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive || hasSearchTerm) ? ' ' + t('labels.filteredSuffix') : '' }}
|
||||
}
|
||||
</p>
|
||||
@if (seriesCollapseFilter.seriesCollapsed() && books(); as books) {
|
||||
<p class="series-collapsed-info">
|
||||
{{ t('labels.seriesCollapsedInfo', { count: books.length, itemWord: books.length === 1 ? t('labels.item') : t('labels.items') }) }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (userService.currentUser(); as currentUser) {
|
||||
@if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED &&
|
||||
(currentUser.permissions.admin || currentUser.permissions.canManageLibrary)) {
|
||||
<div class="entity-menu-wrapper">
|
||||
<p-button
|
||||
icon="pi pi-ellipsis-v"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="info"
|
||||
(click)="entitymenu.toggle($event)">
|
||||
</p-button>
|
||||
<p-menu #entitymenu [model]="entityOptions()" [popup]="true" appendTo="body"></p-menu>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<div class="toolbar-actions">
|
||||
<div class="toolbar-icons">
|
||||
@if (isFilterActive) {
|
||||
<a class="topbar-items topbar-item" (click)="clearFilter()">
|
||||
<i
|
||||
class="pi pi-filter-slash filter-clear-icon"
|
||||
[pTooltip]="t('tooltip.clearFilters')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (currentViewMode === 'table') {
|
||||
<div>
|
||||
<a class="topbar-items topbar-item" (click)="columnPopover.toggle($event)">
|
||||
<i
|
||||
class="pi pi-eye"
|
||||
[pTooltip]="t('tooltip.visibleColumns')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
<p-popover #columnPopover [dismissable]="true" appendTo="body">
|
||||
<div class="column-popover-content">
|
||||
<p-multiSelect
|
||||
optionLabel="header"
|
||||
[options]="columnPreferenceService.allColumns"
|
||||
[(ngModel)]="visibleColumns"
|
||||
(ngModelChange)="onVisibleColumnsChange($event)"
|
||||
display="chip"
|
||||
[placeholder]="t('placeholder.selectColumns')"
|
||||
[style]="{ width: '100%' }"
|
||||
[filter]="true"
|
||||
[showClear]="true"
|
||||
></p-multiSelect>
|
||||
</div>
|
||||
<div class="column-popover-footer">
|
||||
<p>{{ t('labels.setAsDefault') }}</p>
|
||||
<p-button
|
||||
[label]="t('labels.save')"
|
||||
outlined
|
||||
size="small"
|
||||
(click)="columnPreferenceService.saveVisibleColumns(visibleColumns)"></p-button>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
}
|
||||
<div>
|
||||
<a
|
||||
class="topbar-items topbar-item"
|
||||
(click)="seriesCollapseOverlay.toggle($event)"
|
||||
[pTooltip]="t('tooltip.displaySettings')"
|
||||
tooltipPosition="top">
|
||||
<i class="pi pi-cog"></i>
|
||||
</a>
|
||||
<p-popover #seriesCollapseOverlay [dismissable]="true" appendTo="body">
|
||||
<div class="display-settings-popover">
|
||||
<div class="display-settings-section">
|
||||
<div class="display-settings-checkbox-row">
|
||||
<p-checkbox
|
||||
inputId="collapse-series-checkbox"
|
||||
[binary]="true"
|
||||
[ngModel]="seriesCollapseFilter.seriesCollapsed()"
|
||||
(onChange)="onSeriesCollapseCheckboxChange($event.checked)">
|
||||
</p-checkbox>
|
||||
<label for="collapse-series-checkbox" class="display-settings-label">{{ t('labels.collapseSeries') }}</label>
|
||||
</div>
|
||||
</div>
|
||||
@if (isMobile) {
|
||||
<div class="display-settings-section">
|
||||
<label class="display-settings-label">{{ t('labels.gridColumns') }}</label>
|
||||
<div class="column-options">
|
||||
<button
|
||||
type="button"
|
||||
class="column-option-btn"
|
||||
[class.active]="mobileColumnCount === 2"
|
||||
(click)="setMobileColumns(2)">2</button>
|
||||
<button
|
||||
type="button"
|
||||
class="column-option-btn"
|
||||
[class.active]="mobileColumnCount === 3"
|
||||
(click)="setMobileColumns(3)">3</button>
|
||||
<button
|
||||
type="button"
|
||||
class="column-option-btn"
|
||||
[class.active]="mobileColumnCount === 4"
|
||||
(click)="setMobileColumns(4)">4</button>
|
||||
</div>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="display-settings-section">
|
||||
<label class="display-settings-label">{{ t('labels.gridItemSize') }}</label>
|
||||
<p-slider
|
||||
[ngModel]="coverScalePreferenceService.scaleFactor()"
|
||||
(ngModelChange)="coverScalePreferenceService.setScale($event)"
|
||||
[min]="0.5"
|
||||
[max]="1.5"
|
||||
[step]="0.01"
|
||||
[style]="{ width: '100%' }">
|
||||
</p-slider>
|
||||
<div class="scale-value-display">
|
||||
{{ coverScalePreferenceService.scaleFactor().toFixed(2) }}x
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<div class="display-settings-section">
|
||||
<div class="display-settings-checkbox-row">
|
||||
<p-checkbox
|
||||
inputId="show-book-type-pill-checkbox"
|
||||
[binary]="true"
|
||||
[ngModel]="bookCardOverlayPreferenceService.showBookTypePill()"
|
||||
(onChange)="bookCardOverlayPreferenceService.setShowBookTypePill($event.checked)">
|
||||
</p-checkbox>
|
||||
<label for="show-book-type-pill-checkbox" class="display-settings-label">{{ t('labels.bookTypeOverlay') }}</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
|
||||
<div class="sort-button-wrapper">
|
||||
<a class="topbar-items topbar-item" (click)="sortPopover.toggle($event)">
|
||||
<i
|
||||
class="pi pi-sort"
|
||||
[pTooltip]="t('tooltip.selectSorting')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
@if (sortCriteriaCount > 1) {
|
||||
<p-badge [value]="sortCriteriaCount.toString()" class="sort-badge"/>
|
||||
}
|
||||
</a>
|
||||
<p-popover #sortPopover [dismissable]="true" appendTo="body">
|
||||
<app-multi-sort-popover
|
||||
[sortCriteria]="this.bookSorter.selectedSortCriteria"
|
||||
[availableSortOptions]="visibleSortOptions"
|
||||
[showSaveButton]="canSaveSort"
|
||||
(criteriaChange)="onSortCriteriaChange($event)"
|
||||
(saveSortConfig)="onSaveSortConfig($event)">
|
||||
</app-multi-sort-popover>
|
||||
</p-popover>
|
||||
</div>
|
||||
|
||||
<a class="topbar-items topbar-item" (click)="toggleTableGrid()">
|
||||
<i
|
||||
[ngClass]="viewIcon"
|
||||
[pTooltip]="t('tooltip.toggleView')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- MOBILE SEARCH (only visible below md) -->
|
||||
<div class="mobile-search-wrapper">
|
||||
<button
|
||||
type="button"
|
||||
class="topbar-items topbar-item"
|
||||
(click)="searchDropdown.toggle($event)"
|
||||
[pTooltip]="t('tooltip.search')"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<i class="pi pi-search"></i>
|
||||
</button>
|
||||
|
||||
<p-popover #searchDropdown [dismissable]="true" appendTo="body" [style]="{ width: '24rem' }">
|
||||
<div class="search-popover-content">
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
[placeholder]="t('placeholder.search')"
|
||||
[(ngModel)]="bookTitle"
|
||||
(ngModelChange)="onSearchTermChange($event)"
|
||||
class="search-input-full"
|
||||
/>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[text]="true"
|
||||
size="small"
|
||||
[rounded]="true"
|
||||
class="search-clear-btn"
|
||||
(click)="clearSearch(); searchDropdown.hide()"
|
||||
></p-button>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
|
||||
<div class="desktop-search-wrapper">
|
||||
<i class="pi pi-search search-icon"></i>
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
[placeholder]="t('placeholder.search')"
|
||||
[(ngModel)]="bookTitle"
|
||||
(ngModelChange)="onSearchTermChange($event)"
|
||||
class="search-input"
|
||||
/>
|
||||
@if (bookTitle) {
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[text]="true"
|
||||
size="small"
|
||||
[rounded]="true"
|
||||
class="search-clear-btn"
|
||||
(click)="clearSearch()"
|
||||
></p-button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<a class="topbar-items topbar-item" (click)="toggleSidebar()">
|
||||
<i
|
||||
[ngClass]="showFilter() ? 'pi pi-angle-double-right' : 'pi pi-angle-double-left'"
|
||||
[pTooltip]="t('tooltip.toggleSidebar')"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (books(); as books) {
|
||||
<div>
|
||||
@if (isBooksLoading()) {
|
||||
<div>
|
||||
<p-progressSpinner></p-progressSpinner>
|
||||
</div>
|
||||
}
|
||||
<div class="book-state-wrapper">
|
||||
@if (booksError()) {
|
||||
<div class="no-books-container">
|
||||
<p class="no-books-text">
|
||||
{{ entityType() === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
|
||||
</p>
|
||||
</div>
|
||||
} @else if (!isBooksLoading() && books.length === 0) {
|
||||
<div class="no-books-container">
|
||||
<p class="no-books-text">
|
||||
{{ t('labels.noBooks') }}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
@if (currentViewMode === 'table' && books.length > 0) {
|
||||
<app-book-table
|
||||
[books]="books"
|
||||
[preselectedBookIds]="selectedBooks()"
|
||||
(selectedBooksChange)="onSelectedBooksChange($event)"
|
||||
[sortOption]="this.bookSorter.selectedSort!"
|
||||
[visibleColumns]="visibleColumns"
|
||||
></app-book-table>
|
||||
}
|
||||
@if (currentViewMode === 'grid') {
|
||||
<virtual-scroller class="virtual-scroller" #scroll [items]="books">
|
||||
<div
|
||||
class="grid"
|
||||
#container
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
||||
@for (book of scroll.viewPortItems; let i = $index; track book.id) {
|
||||
<div
|
||||
class="virtual-scroller-item"
|
||||
[ngStyle]="{width: currentCardSize.width + 'px', height: getCardHeight(book) + 'px'}">
|
||||
<app-book-card
|
||||
[index]="books.indexOf(book)"
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="true"
|
||||
[seriesViewEnabled]="seriesViewEnabled"
|
||||
[onBookSelect]="handleBookSelect.bind(this)"
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
||||
(checkboxClick)="onCheckboxClicked($event)"
|
||||
[isSelected]="selectedBooks().has(book.id)"
|
||||
[useSquareCovers]="isAudiobookOnlyLibrary"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</virtual-scroller>
|
||||
}
|
||||
@if (userService.currentUser(); as currentUser) {
|
||||
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
|
||||
<div class="footer-content">
|
||||
<div class="footer-left">
|
||||
<div class="selected-count-badge">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
<span class="selected-count">{{ selectedCount() }}</span>
|
||||
<span class="selected-label">{{ t('labels.selected') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer-center">
|
||||
@if (entityType(); as entityType) {
|
||||
<div class="action-buttons-group">
|
||||
@if (hasMetadataMenuItems) {
|
||||
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
|
||||
<p-button
|
||||
(click)="menu.toggle($event)"
|
||||
[pTooltip]="t('tooltip.metadataActions')"
|
||||
tooltipPosition="top"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
icon="pi pi-database">
|
||||
</p-button>
|
||||
}
|
||||
<p-button
|
||||
icon="pi pi-bookmark-fill"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
(onClick)="openShelfAssigner()"
|
||||
[pTooltip]="t('tooltip.assignToShelf')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
@if (entityType === EntityType.SHELF) {
|
||||
<p-button
|
||||
icon="pi pi-bookmark"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
(click)="unshelfBooks()"
|
||||
[pTooltip]="t('tooltip.removeFromShelf')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (currentUser.permissions.canBulkLockUnlockMetadata) {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-lock"
|
||||
severity="info"
|
||||
(click)="lockUnlockMetadata()"
|
||||
[pTooltip]="t('tooltip.lockUnlockMetadata')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (currentUser.permissions.canMoveOrganizeFiles && appSettingsService.appSettings()?.diskType === 'LOCAL') {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-arrows-h"
|
||||
severity="info"
|
||||
(click)="moveFiles()"
|
||||
[pTooltip]="t('tooltip.organizeFiles')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (currentUser.permissions.canManageLibrary || currentUser.permissions.admin) {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-link"
|
||||
severity="info"
|
||||
(click)="attachFilesToBook()"
|
||||
[disabled]="!canAttachFiles()"
|
||||
[pTooltip]="t('tooltip.attachToBook')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (hasMoreActionsItems) {
|
||||
<div class="more-actions-wrapper">
|
||||
<p-button
|
||||
(click)="menu.toggle($event)"
|
||||
[pTooltip]="t('tooltip.moreActions')"
|
||||
tooltipPosition="top"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
icon="pi pi-ellipsis-v">
|
||||
</p-button>
|
||||
<p-tieredMenu #menu [model]="moreActionsMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<div class="action-buttons-group">
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-check-square"
|
||||
severity="success"
|
||||
(click)="selectAllBooks()"
|
||||
[pTooltip]="t('tooltip.selectAll')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-times"
|
||||
severity="warn"
|
||||
(click)="deselectAllBooks()"
|
||||
[pTooltip]="t('tooltip.deselectAll')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
</div>
|
||||
@if (currentUser?.permissions?.admin || currentUser?.permissions?.canDeleteBook) {
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-trash"
|
||||
severity="danger"
|
||||
(click)="confirmDeleteBooks()"
|
||||
[pTooltip]="t('tooltip.deleteSelected')"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
<div class="footer-right"></div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (showFilter()) {
|
||||
<div
|
||||
class="mobile-filter-mask"
|
||||
(click)="toggleSidebar()">
|
||||
</div>
|
||||
<app-book-filter
|
||||
[showFilter]="showFilter()"
|
||||
class="filter-overlay-container"
|
||||
[ngClass]="{ 'active': showFilter() }"
|
||||
[entity]="entity()"
|
||||
[entityType]="entityType()"
|
||||
[resetFilter$]="resetFilterSubject"
|
||||
(filterSelected)="onFilterSelected($event)"
|
||||
(filterModeChanged)="onFilterModeChanged($event)">
|
||||
</app-book-filter>
|
||||
}
|
||||
|
||||
</div>
|
||||
</ng-container>
|
||||
@@ -0,0 +1,536 @@
|
||||
// Layout containers
|
||||
.book-browser-container {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
.book-browser-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
// Header bar
|
||||
.book-browser-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
gap: 0.25rem;
|
||||
padding: 0.35rem 0.35rem;
|
||||
border-radius: 0.75rem 0.75rem 0 0;
|
||||
margin-bottom: 0.5rem;
|
||||
background-color: var(--card-background);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
|
||||
@media (min-width: 768px) {
|
||||
gap: 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Entity info section
|
||||
.entity-info-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
flex-shrink: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.entity-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.125rem;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
gap: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.entity-title {
|
||||
font-size: 1.25rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin: 0;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
font-size: 1rem;
|
||||
padding-left: 0.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.series-collapsed-info {
|
||||
font-size: 0.875rem;
|
||||
color: #6b7280;
|
||||
margin: 0;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
display: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.entity-menu-wrapper {
|
||||
margin-left: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// Toolbar actions
|
||||
.toolbar-actions {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
flex-shrink: 0;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
gap: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.toolbar-icons {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
gap: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Icon with orange color for filter
|
||||
.filter-clear-icon {
|
||||
color: orange;
|
||||
}
|
||||
|
||||
// Popover content containers
|
||||
.column-popover-content {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.column-popover-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding-top: 1rem;
|
||||
padding-left: 0.25rem;
|
||||
}
|
||||
|
||||
.display-settings-popover {
|
||||
width: 220px;
|
||||
padding: 0.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.display-settings-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.display-settings-checkbox-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.display-settings-label {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.scale-value-display {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.column-options {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.column-option-btn {
|
||||
flex: 1;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 6px;
|
||||
background-color: var(--card-background);
|
||||
color: var(--text-color);
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary-color);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background-color: var(--primary-color);
|
||||
border-color: var(--primary-color);
|
||||
color: var(--primary-color-text);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort button wrapper
|
||||
.sort-button-wrapper {
|
||||
position: relative;
|
||||
|
||||
.sort-badge {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: -6px;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort menu item (kept for backward compat)
|
||||
.sort-menu-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.5rem 1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
// Search section
|
||||
.mobile-search-wrapper {
|
||||
position: relative;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.desktop-search-wrapper {
|
||||
display: none;
|
||||
position: relative;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.search-popover-content {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.search-input-full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.search-clear-btn {
|
||||
position: absolute;
|
||||
right: 0.5rem;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
// Footer bar
|
||||
.book-browser-footer {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 10%;
|
||||
right: 10%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
padding: 1rem 0.5rem 0.5rem;
|
||||
z-index: 1;
|
||||
border-radius: 10px 10px 0 0;
|
||||
border: 1px solid rgba(255, 255, 255, 0.5);
|
||||
border-width: 1px 1px 0 1px;
|
||||
background-color: var(--card-background);
|
||||
transition: transform 0.15s ease-out, opacity 0.15s ease-out;
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
|
||||
&.footer-hidden {
|
||||
transform: translateY(100%);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
left: 0;
|
||||
right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.footer-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-left: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
width: 120px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-center {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
mask-image: linear-gradient(to right, transparent 0, black 12px, black calc(100% - 32px), transparent 100%);
|
||||
-webkit-mask-image: linear-gradient(to right, transparent 0, black 12px, black calc(100% - 32px), transparent 100%);
|
||||
padding: 0 16px;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-right {
|
||||
flex-shrink: 0;
|
||||
width: 120px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.selected-count-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.9rem;
|
||||
color: #e4e4e7;
|
||||
|
||||
i {
|
||||
font-size: 1rem;
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 0.4rem 0.8rem;
|
||||
font-size: 0.85rem;
|
||||
|
||||
i {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.selected-count {
|
||||
font-weight: 700;
|
||||
font-size: 1rem;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.selected-label {
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
|
||||
.action-buttons-group {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
gap: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
gap: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.more-actions-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
// Virtual scroller and grid
|
||||
.virtual-scroller {
|
||||
width: 100%;
|
||||
height: calc(100dvh - 10.9rem);
|
||||
padding: 1rem;
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
height: calc(100dvh - 9rem);
|
||||
}
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(1px, 1fr));
|
||||
gap: 1.3rem;
|
||||
align-items: start;
|
||||
width: 100%;
|
||||
|
||||
// Mobile: fixed 2 or 3 columns based on phone width
|
||||
@media (max-width: 767px) {
|
||||
gap: 0.5rem;
|
||||
padding: 0 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.virtual-scroller-item {
|
||||
position: relative;
|
||||
transition: width 0.2s ease, height 0.2s ease;
|
||||
}
|
||||
|
||||
// No books state
|
||||
.no-books-container {
|
||||
padding-top: 3rem;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.no-books-text {
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-color);
|
||||
background: var(--card-background);
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
// Topbar items (icon buttons)
|
||||
.topbar-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--border-color);
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
transition: outline-color 0.2s, border-color 0.2s;
|
||||
border-radius: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
outline-color: transparent;
|
||||
background-color: var(--card-background);
|
||||
cursor: pointer;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary-color);
|
||||
}
|
||||
|
||||
i, span {
|
||||
color: var(--primary-color);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 100;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Search input styling
|
||||
.search-icon {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 10px;
|
||||
transform: translateY(-50%);
|
||||
color: var(--text-secondary-color);
|
||||
font-size: 1rem;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
min-width: 22rem;
|
||||
padding-left: 30px;
|
||||
height: 2.5rem;
|
||||
line-height: 2.5rem;
|
||||
font-size: 1rem;
|
||||
box-sizing: border-box;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Filter overlay (mobile sidebar)
|
||||
.mobile-filter-mask {
|
||||
@media (max-width: 991px) {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 998;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
}
|
||||
|
||||
.filter-overlay-container {
|
||||
flex-shrink: 0;
|
||||
z-index: 50;
|
||||
|
||||
@media (max-width: 991px) {
|
||||
width: var(--sidebar-width, 225px);
|
||||
position: fixed;
|
||||
top: 3.85rem;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
height: calc(100% - 3.85rem);
|
||||
background-color: var(--card-background);
|
||||
box-shadow: -2px 0 10px rgba(0, 0, 0, 0.15);
|
||||
transform: translateX(100%);
|
||||
transition: transform 0.3s ease;
|
||||
z-index: 1001;
|
||||
|
||||
&.active {
|
||||
transform: translateX(0);
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
|
||||
&:not(.active) {
|
||||
width: 0 !important;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
&.active {
|
||||
width: var(--sidebar-width, 225px);
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
margin-left: 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Book state container
|
||||
.book-state-wrapper {
|
||||
position: relative;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+115
@@ -0,0 +1,115 @@
|
||||
import {effect, inject, Injectable, signal} from '@angular/core';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookCardOverlayPreferenceService {
|
||||
private static readonly PERSIST_DELAY_MS = 500;
|
||||
|
||||
private readonly userService = inject(UserService);
|
||||
|
||||
private readonly _showBookTypePill = signal(true);
|
||||
readonly showBookTypePill = this._showBookTypePill.asReadonly();
|
||||
|
||||
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
|
||||
private persistTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const user = this.userService.currentUser();
|
||||
if (user) {
|
||||
this.loadPreferencesFromUser();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setShowBookTypePill(show: boolean): void {
|
||||
this._showBookTypePill.set(show);
|
||||
this.schedulePersist(show);
|
||||
}
|
||||
|
||||
private loadPreferencesFromUser(): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
const prefs = user?.userSettings?.entityViewPreferences;
|
||||
|
||||
let show = true;
|
||||
if (prefs) {
|
||||
const globalAny = prefs.global as any;
|
||||
show = prefs.global?.overlayBookType ?? globalAny?.showBookTypePill ?? true;
|
||||
|
||||
if (this.currentContext) {
|
||||
const override = prefs.overrides?.find(o =>
|
||||
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
||||
);
|
||||
if (override) {
|
||||
const prefAny = override.preferences as any;
|
||||
if (override.preferences.overlayBookType !== undefined) {
|
||||
show = override.preferences.overlayBookType;
|
||||
} else if (prefAny?.showBookTypePill !== undefined) {
|
||||
show = prefAny.showBookTypePill;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this._showBookTypePill() !== show) {
|
||||
this._showBookTypePill.set(show);
|
||||
}
|
||||
}
|
||||
|
||||
private schedulePersist(show: boolean): void {
|
||||
if (this.persistTimeout) {
|
||||
clearTimeout(this.persistTimeout);
|
||||
}
|
||||
|
||||
this.persistTimeout = setTimeout(() => {
|
||||
this.persistPreference(show);
|
||||
}, BookCardOverlayPreferenceService.PERSIST_DELAY_MS);
|
||||
}
|
||||
|
||||
private persistPreference(show: boolean): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
if (!user) return;
|
||||
|
||||
const prefs = structuredClone(user.userSettings.entityViewPreferences ?? {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'DESC',
|
||||
view: 'GRID',
|
||||
coverSize: 1.0,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: []
|
||||
});
|
||||
|
||||
if (!prefs.overrides) {
|
||||
prefs.overrides = [];
|
||||
}
|
||||
|
||||
if (this.currentContext) {
|
||||
let override = prefs.overrides.find(o =>
|
||||
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
||||
);
|
||||
|
||||
if (!override) {
|
||||
override = {
|
||||
entityType: this.currentContext.type,
|
||||
entityId: this.currentContext.id,
|
||||
preferences: {
|
||||
...prefs.global,
|
||||
overlayBookType: show
|
||||
}
|
||||
};
|
||||
prefs.overrides.push(override);
|
||||
} else {
|
||||
override.preferences.overlayBookType = show;
|
||||
}
|
||||
} else {
|
||||
prefs.global.overlayBookType = show;
|
||||
}
|
||||
|
||||
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
<div class="book-card"
|
||||
[class.selected]="isSelected"
|
||||
(click)="onCardClick($event)">
|
||||
|
||||
<div class="cover-container" [ngClass]="{ 'center-info-btn': _isSeriesViewActive || !hasDigitalFile(), 'loaded': isImageLoaded, 'audiobook-cover': _isAudiobook, 'square-library-cover': useSquareCovers }">
|
||||
<img
|
||||
[src]="coverImageUrl"
|
||||
class="book-cover"
|
||||
[class.loaded]="isImageLoaded"
|
||||
[class.square-cover]="_isAudiobook || useSquareCovers"
|
||||
[alt]="('book.card.alt.cover' | transloco: { title: displayTitle })"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
(load)="onImageLoad()"/>
|
||||
|
||||
<div class="top-left-overlay-stack">
|
||||
@if ((overlayPreferenceService?.showBookTypePill() ?? true) && getDisplayFormat(); as displayFormat) {
|
||||
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + displayFormat.toLowerCase()">
|
||||
{{ displayFormat }}
|
||||
</div>
|
||||
}
|
||||
@if (!book.seriesCount && book.metadata?.seriesNumber != null) {
|
||||
<div class="series-number-overlay">
|
||||
#{{ book.metadata?.seriesNumber }}
|
||||
</div>
|
||||
}
|
||||
@if (book.seriesCount && book.seriesCount >= 1) {
|
||||
<div class="series-items-count-overlay">
|
||||
<i class="pi pi-book series-items-count-icon"></i>{{ book.seriesCount }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (_isSeriesViewActive) {
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openSeriesInfo()" [ariaLabel]="'book.card.alt.viewSeriesInfo' | transloco"></p-button>
|
||||
} @else {
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)" [ariaLabel]="'book.card.alt.viewDetails' | transloco">
|
||||
</p-button>
|
||||
}
|
||||
|
||||
@if (!_isSeriesViewActive && hasDigitalFile()) {
|
||||
<a [routerLink]="urlHelper.getBookPrimaryReadingUrl(book)" (click)="readBook(book)"><p-button [rounded]="true" [icon]="readButtonIcon" class="read-btn" (click)="readBook(book)"
|
||||
[pTooltip]="_isContinueReading ? ('book.card.alt.continueReading' | transloco) : ''"
|
||||
tooltipPosition="bottom"
|
||||
[ariaLabel]="_isContinueReading ? ('book.card.alt.continueReading' | transloco) : (_isAudiobook ? ('book.card.alt.playAudiobook' | transloco) : ('book.card.alt.readBook' | transloco))"></p-button></a>
|
||||
}
|
||||
|
||||
@if (isCheckboxEnabled) {
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
class="select-checkbox"
|
||||
(click)="captureMouseEvent($event)"
|
||||
[ngModel]="isSelected"
|
||||
(onChange)="toggleSelection($event)">
|
||||
</p-checkbox>
|
||||
}
|
||||
|
||||
@if (hasProgress) {
|
||||
<div class="cover-progress-bar-container" [pTooltip]="progressTooltip" tooltipPosition="top">
|
||||
@if (_progressPercentage !== null) {
|
||||
<p-progressBar
|
||||
[value]="_progressPercentage"
|
||||
[showValue]="false"
|
||||
class="cover-progress-bar"
|
||||
[ngClass]="{ 'progress-complete': _progressPercentage === 100, 'progress-incomplete': _progressPercentage < 100 }">
|
||||
</p-progressBar>
|
||||
}
|
||||
@if (_koProgressPercentage !== null) {
|
||||
<p-progressBar
|
||||
[value]="_koProgressPercentage"
|
||||
[showValue]="false"
|
||||
class="cover-progress-bar"
|
||||
[ngClass]="_koProgressPercentage === 100 ? 'progress-complete-ko' : 'progress-incomplete-ko'">
|
||||
</p-progressBar>
|
||||
}
|
||||
@if (_koboProgressPercentage !== null) {
|
||||
<p-progressBar
|
||||
[value]="_koboProgressPercentage"
|
||||
[showValue]="false"
|
||||
class="cover-progress-bar"
|
||||
[ngClass]="_koboProgressPercentage === 100 ? 'progress-complete-kobo' : 'progress-incomplete-kobo'">
|
||||
</p-progressBar>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (!bottomBarHidden) {
|
||||
<div class="book-title-container">
|
||||
<div class="read-status-indicator"
|
||||
[ngClass]="_readStatusClass"
|
||||
[pTooltip]="readStatusTooltip"
|
||||
tooltipPosition="bottom"
|
||||
(click)="toggleReadStatusMenu($event, readStatusMenu)"
|
||||
[attr.aria-label]="'book.card.alt.readStatusMenu' | transloco">
|
||||
<i [class]="_readStatusIcon" style="font-size: 0.9rem"></i>
|
||||
</div>
|
||||
<p-tieredmenu #readStatusMenu [model]="readStatusMenuItems" [popup]="true" appendTo="body"></p-tieredmenu>
|
||||
<h4 class="book-title"
|
||||
tooltipPosition="bottom"
|
||||
[pTooltip]="titleTooltip">
|
||||
{{ displayTitle }}
|
||||
</h4>
|
||||
<p-tieredmenu #menu [model]="items" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()"></p-tieredmenu>
|
||||
<p-button
|
||||
class="custom-button-padding"
|
||||
size="small"
|
||||
[text]="true"
|
||||
(click)="onMenuToggle($event, menu)"
|
||||
icon="pi pi-ellipsis-v"
|
||||
[ariaLabel]="'book.card.alt.bookMenu' | transloco">
|
||||
</p-button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
.book-card {
|
||||
background-color: var(--card-background);
|
||||
border-radius: 8px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
transition: box-shadow 0.25s ease, transform 0.25s ease;
|
||||
|
||||
&:hover {
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
&.selected {
|
||||
border: 2px solid var(--primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% {
|
||||
background-position: -200% 0;
|
||||
}
|
||||
100% {
|
||||
background-position: 200% 0;
|
||||
}
|
||||
}
|
||||
|
||||
.cover-container {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 5/7;
|
||||
background-color: var(--card-background);
|
||||
border-radius: 8px 8px 0 0;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.cover-container:not(.loaded) {
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--surface-ground) 25%,
|
||||
var(--surface-hover, rgba(255, 255, 255, 0.08)) 50%,
|
||||
var(--surface-ground) 75%
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.cover-container.audiobook-cover {
|
||||
aspect-ratio: 5/7;
|
||||
background-color: var(--surface-ground);
|
||||
}
|
||||
|
||||
.cover-container.square-library-cover {
|
||||
aspect-ratio: 1/1;
|
||||
background-color: var(--surface-ground);
|
||||
}
|
||||
|
||||
.book-cover {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 8px 8px 0 0;
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s ease-in, transform 0.35s ease;
|
||||
}
|
||||
|
||||
.book-cover.loaded {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.book-card:hover .book-cover.loaded {
|
||||
transform: scale(1.04);
|
||||
}
|
||||
|
||||
.book-cover.square-cover {
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.cover-container::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: radial-gradient(circle, rgba(0, 0, 0, 0) 25%, rgba(0, 0, 0, 0.6) 100%);
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s ease-in-out;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.cover-container:hover::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.book-title-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.book-title {
|
||||
flex-grow: 1;
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-color);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: center;
|
||||
margin: 0;
|
||||
padding-left: 0.5rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
font-size: 0.75rem;
|
||||
padding-left: 0.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.info-btn,
|
||||
.read-btn {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.15s ease, visibility 0.15s ease;
|
||||
z-index: 2;
|
||||
will-change: opacity, visibility;
|
||||
|
||||
::ng-deep .p-button {
|
||||
box-shadow:
|
||||
0 2px 8px rgba(0, 0, 0, 0.4),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.15);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.08);
|
||||
box-shadow:
|
||||
0 4px 12px rgba(0, 0, 0, 0.5),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
width: clamp(1.5rem, 8vw, 2.5rem);
|
||||
height: clamp(1.5rem, 8vw, 2.5rem);
|
||||
padding: 0;
|
||||
|
||||
.pi {
|
||||
font-size: clamp(0.65rem, 3.5vw, 1rem);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.info-btn {
|
||||
top: 21%;
|
||||
}
|
||||
|
||||
.read-btn {
|
||||
bottom: 21%;
|
||||
}
|
||||
|
||||
.cover-container:hover .info-btn,
|
||||
.cover-container:hover .read-btn {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.cover-container.center-info-btn .info-btn {
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.select-checkbox {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.15s ease, visibility 0.15s ease;
|
||||
z-index: 2;
|
||||
will-change: opacity, visibility;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.select-checkbox .p-checkbox {
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.cover-container:hover .select-checkbox,
|
||||
.book-card.selected .select-checkbox {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.cover-progress-bar-container {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 7.5px;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.cover-progress-bar {
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 2.5px;
|
||||
z-index: 1;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.series-number-overlay {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
color: white;
|
||||
font-size: 0.75rem;
|
||||
padding: 1px 3px;
|
||||
border-radius: 3px;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.series-items-count-overlay {
|
||||
position: absolute;
|
||||
background-color: var(--primary-color);
|
||||
color: var(--primary-text-color-dark);
|
||||
font-size: 0.7rem;
|
||||
padding: 0 5px;
|
||||
border-radius: 6px;
|
||||
z-index: 3;
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
font-weight: 700;
|
||||
text-align: center;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.series-items-count-icon {
|
||||
font-size: 0.6rem;
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
.book-type-pill-overlay {
|
||||
position: absolute;
|
||||
background: var(--primary-color, #6366f1);
|
||||
color: var(--primary-text-color-dark, #fff);
|
||||
font-size: 0.675rem;
|
||||
font-weight: 700;
|
||||
padding: 1px 6px;
|
||||
border-radius: 6px;
|
||||
z-index: 3;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
|
||||
letter-spacing: 0.03em;
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
text-transform: uppercase;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.top-left-overlay-stack {
|
||||
position: absolute;
|
||||
top: 7px;
|
||||
left: 7px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
z-index: 4;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
top: 4px;
|
||||
left: 4px;
|
||||
gap: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.book-type-pill-overlay,
|
||||
.series-number-overlay,
|
||||
.series-items-count-overlay {
|
||||
position: static;
|
||||
margin: 0;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
font-size: 0.6rem;
|
||||
padding: 1px 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.book-type-epub {
|
||||
background: var(--book-type-epub-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-pdf {
|
||||
background: var(--book-type-pdf-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-cbx {
|
||||
background: var(--book-type-cbx-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-mobi {
|
||||
background: var(--book-type-mobi-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-azw3 {
|
||||
background: var(--book-type-azw3-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-fb2 {
|
||||
background: var(--book-type-fb2-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-audiobook {
|
||||
background: var(--book-type-audiobook-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-m4b {
|
||||
background: var(--book-type-m4b-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-mp3 {
|
||||
background: var(--book-type-mp3-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-m4a {
|
||||
background: var(--book-type-m4a-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-opus {
|
||||
background: var(--book-type-opus-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-cbz {
|
||||
background: var(--book-type-cbz-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-cbr {
|
||||
background: var(--book-type-cbr-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-cb7 {
|
||||
background: var(--book-type-cb7-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-phy {
|
||||
background: var(--book-type-physical-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.read-status-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: bold;
|
||||
margin-left: 0.5rem;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
transition: opacity 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
.status-read {
|
||||
color: #22c55e;
|
||||
}
|
||||
|
||||
.status-reading {
|
||||
color: #3b82f6;
|
||||
}
|
||||
|
||||
.status-re-reading {
|
||||
color: #06b6d4;
|
||||
}
|
||||
|
||||
.status-partially-read {
|
||||
color: #f59e0b;
|
||||
}
|
||||
|
||||
.status-paused {
|
||||
color: #eab308;
|
||||
}
|
||||
|
||||
.status-abandoned {
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.status-wont-read {
|
||||
color: #ec4899;
|
||||
}
|
||||
|
||||
.status-unset {
|
||||
color: var(--text-color-secondary);
|
||||
}
|
||||
|
||||
::ng-deep .progress-incomplete .p-progressbar-value {
|
||||
background-color: #3b82f6;
|
||||
}
|
||||
|
||||
::ng-deep .progress-complete .p-progressbar-value {
|
||||
background-color: #22c55e;
|
||||
}
|
||||
|
||||
::ng-deep .progress-incomplete-ko .p-progressbar-value {
|
||||
background-color: #fbbf24;
|
||||
}
|
||||
|
||||
::ng-deep .progress-complete-ko .p-progressbar-value {
|
||||
background-color: #8b5cf6;
|
||||
}
|
||||
|
||||
::ng-deep .progress-incomplete-kobo .p-progressbar-value {
|
||||
background-color: #bf0000;
|
||||
}
|
||||
|
||||
::ng-deep .progress-complete-kobo .p-progressbar-value {
|
||||
background-color: #f65c9c;
|
||||
}
|
||||
|
||||
::ng-deep .cover-progress-bar {
|
||||
--p-progressbar-border-radius: 0 !important;
|
||||
}
|
||||
|
||||
::ng-deep .custom-button-padding .p-button {
|
||||
padding-block: 0.25rem !important;
|
||||
}
|
||||
|
||||
::ng-deep .book-details-dialog .p-dialog-header {
|
||||
padding: 1rem 1.25rem !important;
|
||||
}
|
||||
+929
@@ -0,0 +1,929 @@
|
||||
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core';
|
||||
import {TooltipModule} from "primeng/tooltip";
|
||||
import {AdditionalFile, Book, BookType, ReadStatus} from '../../../model/book.model';
|
||||
import {Button} from 'primeng/button';
|
||||
import {MenuModule} from 'primeng/menu';
|
||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {BookFileService} from '../../../service/book-file.service';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {CheckboxChangeEvent, CheckboxModule} from 'primeng/checkbox';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {User, UserService} from '../../../../settings/user-management/user.service';
|
||||
import {EmailService} from '../../../../settings/email-v2/email.service';
|
||||
import {TieredMenu} from 'primeng/tieredmenu';
|
||||
import {Router} from '@angular/router';
|
||||
import {RouterLink} from '@angular/router';
|
||||
import {ProgressBar} from 'primeng/progressbar';
|
||||
import {readStatusLabels} from '../book-filter/book-filter.config';
|
||||
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {BookDialogHelperService} from '../book-dialog-helper.service';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {BookNavigationService} from '../../../service/book-navigation.service';
|
||||
import {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card',
|
||||
templateUrl: './book-card.component.html',
|
||||
styleUrls: ['./book-card.component.scss'],
|
||||
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgClass, TieredMenu, ProgressBar, TooltipModule, RouterLink, TranslocoPipe],
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class BookCardComponent implements OnInit, OnChanges {
|
||||
|
||||
@Output() checkboxClick = new EventEmitter<{ index: number; book: Book; selected: boolean; shiftKey: boolean }>();
|
||||
@Output() menuToggled = new EventEmitter<boolean>();
|
||||
|
||||
@Input() index!: number;
|
||||
@Input() book!: Book;
|
||||
@Input() isCheckboxEnabled: boolean = false;
|
||||
@Input() onBookSelect?: (book: Book, selected: boolean) => void;
|
||||
@Input() isSelected: boolean = false;
|
||||
@Input() bottomBarHidden: boolean = false;
|
||||
@Input() seriesViewEnabled: boolean = false;
|
||||
@Input() isSeriesCollapsed: boolean = false;
|
||||
@Input() overlayPreferenceService?: BookCardOverlayPreferenceService;
|
||||
@Input() forceEbookMode: boolean = false;
|
||||
@Input() useSquareCovers: boolean = false;
|
||||
|
||||
@ViewChild('checkboxElem') checkboxElem!: ElementRef<HTMLInputElement>;
|
||||
|
||||
items: MenuItem[] | undefined;
|
||||
readStatusMenuItems: MenuItem[] = [];
|
||||
isImageLoaded: boolean = false;
|
||||
isSubMenuLoading = false;
|
||||
private additionalFilesLoaded = 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);
|
||||
protected urlHelper = inject(UrlHelperService);
|
||||
private confirmationService = inject(ConfirmationService);
|
||||
private bookDialogHelperService = inject(BookDialogHelperService);
|
||||
private bookNavigationService = inject(BookNavigationService);
|
||||
private cdr = inject(ChangeDetectorRef);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private queryClient = inject(QueryClient);
|
||||
|
||||
protected _progressPercentage: number | null = null;
|
||||
protected _koProgressPercentage: number | null = null;
|
||||
protected _koboProgressPercentage: number | null = null;
|
||||
protected _displayTitle: string | undefined = undefined;
|
||||
protected _isSeriesViewActive: boolean = false;
|
||||
protected _coverImageUrl: string = '';
|
||||
protected _readStatusIcon: string = '';
|
||||
protected _readStatusClass: string = '';
|
||||
protected _readStatusTooltip: string = '';
|
||||
protected _shouldShowStatusIcon: boolean = false;
|
||||
protected _seriesCountTooltip: string = '';
|
||||
protected _titleTooltip: string = '';
|
||||
protected _hasProgress: boolean = false;
|
||||
protected _isAudiobook: boolean = false;
|
||||
protected _progressTooltip: string = '';
|
||||
protected _isContinueReading: boolean = false;
|
||||
protected _readButtonIcon: string = 'pi pi-book';
|
||||
|
||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||
protected readStatusHelper = inject(ReadStatusHelper);
|
||||
private user: User | null = null;
|
||||
private diskType: string = 'LOCAL';
|
||||
private menuInitialized = false;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.computeAllMemoizedValues();
|
||||
const currentUser = this.userService.currentUser();
|
||||
if (currentUser) {
|
||||
this.user = currentUser;
|
||||
this.metadataCenterViewMode = currentUser.userSettings?.metadataCenterViewMode ?? 'route';
|
||||
}
|
||||
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
if (settings) {
|
||||
this.diskType = settings.diskType ?? 'LOCAL';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['book'] || changes['forceEbookMode'] || changes['useSquareCovers']) {
|
||||
this.computeAllMemoizedValues();
|
||||
if (changes['book'] && !changes['book'].firstChange && this.menuInitialized) {
|
||||
this.additionalFilesLoaded = false;
|
||||
this.initMenu();
|
||||
}
|
||||
}
|
||||
|
||||
if (changes['seriesViewEnabled'] || changes['isSeriesCollapsed']) {
|
||||
this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1;
|
||||
this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata?.seriesName : this.book.metadata?.title;
|
||||
this._titleTooltip = this.t.translate('book.card.alt.titleTooltip', { title: this._displayTitle });
|
||||
}
|
||||
}
|
||||
|
||||
private computeAllMemoizedValues(): void {
|
||||
this._progressPercentage = this.book.epubProgress?.percentage
|
||||
?? this.book.pdfProgress?.percentage
|
||||
?? this.book.cbxProgress?.percentage
|
||||
?? null;
|
||||
|
||||
this._koProgressPercentage = this.book.koreaderProgress?.percentage ?? null;
|
||||
this._koboProgressPercentage = this.book.koboProgress?.percentage ?? null;
|
||||
|
||||
this._hasProgress = this._progressPercentage !== null || this._koProgressPercentage !== null || this._koboProgressPercentage !== null;
|
||||
|
||||
this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1;
|
||||
this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName)
|
||||
? this.book.metadata?.seriesName
|
||||
: this.book.metadata?.title;
|
||||
this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK' && !this.forceEbookMode;
|
||||
this._coverImageUrl = this._isAudiobook
|
||||
? this.urlHelper.getAudiobookThumbnailUrl(this.book.id, this.book.metadata?.audiobookCoverUpdatedOn)
|
||||
: this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
|
||||
|
||||
this._readStatusIcon = this.readStatusHelper.getReadStatusIcon(this.book.readStatus);
|
||||
this._readStatusClass = this.readStatusHelper.getReadStatusClass(this.book.readStatus);
|
||||
this._readStatusTooltip = this.readStatusHelper.getReadStatusTooltip(this.book.readStatus);
|
||||
this._shouldShowStatusIcon = this.readStatusHelper.shouldShowStatusIcon(this.book.readStatus);
|
||||
|
||||
this._seriesCountTooltip = this.t.translate('book.card.alt.seriesCollapsed', { count: this.book.seriesCount });
|
||||
this._titleTooltip = this.t.translate('book.card.alt.titleTooltip', { title: this._displayTitle });
|
||||
|
||||
const progressParts: string[] = [];
|
||||
if (this._progressPercentage !== null) {
|
||||
progressParts.push(`${this._progressPercentage}% (Grimmory)`);
|
||||
}
|
||||
if (this._koProgressPercentage !== null) {
|
||||
progressParts.push(`${this._koProgressPercentage}% (KOReader)`);
|
||||
}
|
||||
if (this._koboProgressPercentage !== null) {
|
||||
progressParts.push(`${this._koboProgressPercentage}% (Kobo)`);
|
||||
}
|
||||
this._progressTooltip = progressParts.join(' | ');
|
||||
|
||||
const maxProgress = Math.max(
|
||||
this._progressPercentage ?? 0,
|
||||
this._koProgressPercentage ?? 0,
|
||||
this._koboProgressPercentage ?? 0
|
||||
);
|
||||
this._isContinueReading = maxProgress > 0 && maxProgress < 100;
|
||||
|
||||
if (this._isAudiobook) {
|
||||
this._readButtonIcon = this._isContinueReading ? 'pi pi-forward' : 'pi pi-play';
|
||||
} else {
|
||||
this._readButtonIcon = this._isContinueReading ? 'pi pi-forward' : 'pi pi-book';
|
||||
}
|
||||
}
|
||||
|
||||
get hasProgress(): boolean {
|
||||
return this._hasProgress;
|
||||
}
|
||||
|
||||
get seriesCountTooltip(): string {
|
||||
return this._seriesCountTooltip;
|
||||
}
|
||||
|
||||
get titleTooltip(): string {
|
||||
return this._titleTooltip;
|
||||
}
|
||||
|
||||
get readStatusTooltip(): string {
|
||||
return this._readStatusTooltip;
|
||||
}
|
||||
|
||||
get progressTooltip(): string {
|
||||
return this._progressTooltip;
|
||||
}
|
||||
|
||||
get readButtonIcon(): string {
|
||||
return this._readButtonIcon;
|
||||
}
|
||||
|
||||
get displayTitle(): string | undefined {
|
||||
return this._displayTitle;
|
||||
}
|
||||
|
||||
get coverImageUrl(): string {
|
||||
return this._coverImageUrl;
|
||||
}
|
||||
|
||||
private buildReadStatusMenuItems(): void {
|
||||
this.readStatusMenuItems = Object.entries(readStatusLabels).map(([status, label]) => ({
|
||||
label,
|
||||
command: () => {
|
||||
this.bookService.updateBookReadStatus(this.book.id, status as ReadStatus).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.card.toast.readStatusUpdatedSummary'),
|
||||
detail: this.t.translate('book.card.toast.readStatusUpdatedDetail', {label}),
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.card.toast.readStatusFailedSummary'),
|
||||
detail: this.t.translate('book.card.toast.readStatusFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
toggleReadStatusMenu(event: Event, menu: TieredMenu): void {
|
||||
event.stopPropagation();
|
||||
if (this.readStatusMenuItems.length === 0) {
|
||||
this.buildReadStatusMenuItems();
|
||||
}
|
||||
menu.toggle(event);
|
||||
}
|
||||
|
||||
onImageLoad(): void {
|
||||
this.isImageLoaded = true;
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
readBook(book: Book): void {
|
||||
if (this.forceEbookMode && book.primaryFile?.bookType === 'AUDIOBOOK') {
|
||||
const ebookType = this.getEbookType(book);
|
||||
if (ebookType) {
|
||||
this.bookService.readBook(book.id, undefined, ebookType);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.bookService.readBook(book.id);
|
||||
}
|
||||
|
||||
private getEbookType(book: Book): BookType | undefined {
|
||||
if (book.epubProgress) return 'EPUB';
|
||||
if (book.pdfProgress) return 'PDF';
|
||||
if (book.cbxProgress) return 'CBX';
|
||||
const alternativeFormat = book.alternativeFormats?.find(f =>
|
||||
f.bookType && ['EPUB', 'PDF', 'CBX', 'FB2', 'MOBI', 'AZW3'].includes(f.bookType)
|
||||
);
|
||||
return alternativeFormat?.bookType;
|
||||
}
|
||||
|
||||
onMenuShow(): void {
|
||||
this.menuToggled.emit(true);
|
||||
}
|
||||
|
||||
onMenuHide(): void {
|
||||
this.menuToggled.emit(false);
|
||||
}
|
||||
|
||||
onMenuToggle(event: Event, menu: TieredMenu): void {
|
||||
if (!this.menuInitialized) {
|
||||
this.menuInitialized = true;
|
||||
this.initMenu();
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
menu.toggle(event);
|
||||
|
||||
if (!this.additionalFilesLoaded && !this.isSubMenuLoading && this.needsAdditionalFilesData()) {
|
||||
this.isSubMenuLoading = true;
|
||||
this.cdr.markForCheck();
|
||||
const requestedBookId = this.book.id;
|
||||
void this.queryClient.fetchQuery(this.bookService.bookDetailQueryOptions(requestedBookId, true))
|
||||
.then((book) => {
|
||||
if (this.book.id !== requestedBookId) {
|
||||
return;
|
||||
}
|
||||
this.book = book;
|
||||
this.additionalFilesLoaded = true;
|
||||
this.isSubMenuLoading = false;
|
||||
this.initMenu();
|
||||
this.cdr.markForCheck();
|
||||
})
|
||||
.catch(() => {
|
||||
if (this.book.id !== requestedBookId) {
|
||||
return;
|
||||
}
|
||||
this.isSubMenuLoading = false;
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private needsAdditionalFilesData(): boolean {
|
||||
if (this.additionalFilesLoaded) {
|
||||
return false;
|
||||
}
|
||||
const hasNoAlternativeFormats = !this.book.alternativeFormats || this.book.alternativeFormats.length === 0;
|
||||
const hasNoSupplementaryFiles = !this.book.supplementaryFiles || this.book.supplementaryFiles.length === 0;
|
||||
const canDownload = !!this.user?.permissions.canDownload;
|
||||
const canDeleteBook = !!this.user?.permissions.canDeleteBook;
|
||||
return (canDownload || canDeleteBook) && hasNoAlternativeFormats && hasNoSupplementaryFiles;
|
||||
}
|
||||
|
||||
private initMenu() {
|
||||
this.items = [
|
||||
{
|
||||
label: this.t.translate('book.card.menu.assignShelf'),
|
||||
icon: 'pi pi-folder',
|
||||
command: () => this.openShelfDialog()
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.card.menu.viewDetails'),
|
||||
icon: 'pi pi-info-circle',
|
||||
command: () => {
|
||||
setTimeout(() => {
|
||||
this.openBookInfo(this.book);
|
||||
}, 150);
|
||||
},
|
||||
},
|
||||
...this.getPermissionBasedMenuItems(),
|
||||
...this.moreMenuItems(),
|
||||
];
|
||||
}
|
||||
|
||||
private getPermissionBasedMenuItems(): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
if (this.user?.permissions.canDownload) {
|
||||
const hasAdditionalFiles = (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
|
||||
(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
|
||||
|
||||
if (hasAdditionalFiles) {
|
||||
const downloadItems = this.getDownloadMenuItems();
|
||||
items.push({
|
||||
label: this.t.translate('book.card.menu.download'),
|
||||
icon: 'pi pi-download',
|
||||
items: downloadItems
|
||||
});
|
||||
} else if (this.additionalFilesLoaded) {
|
||||
items.push({
|
||||
label: this.t.translate('book.card.menu.download'),
|
||||
icon: 'pi pi-download',
|
||||
command: () => {
|
||||
this.bookFileService.downloadFile(this.book);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
label: this.t.translate('book.card.menu.download'),
|
||||
icon: this.isSubMenuLoading ? 'pi pi-spin pi-spinner' : 'pi pi-download',
|
||||
items: [{label: this.t.translate('book.card.menu.loading'), disabled: true}]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (this.user?.permissions.canDeleteBook) {
|
||||
const hasAdditionalFiles = (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
|
||||
(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
|
||||
|
||||
if (hasAdditionalFiles) {
|
||||
const deleteItems = this.getDeleteMenuItems();
|
||||
items.push({
|
||||
label: this.t.translate('book.card.menu.delete'),
|
||||
icon: 'pi pi-trash',
|
||||
items: deleteItems
|
||||
});
|
||||
} else if (this.additionalFilesLoaded) {
|
||||
items.push({
|
||||
label: this.t.translate('book.card.menu.delete'),
|
||||
icon: 'pi pi-trash',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.card.confirm.deleteBookMessage', {title: this.book.metadata?.title}),
|
||||
header: this.t.translate('book.card.confirm.deleteBookHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptLabel: this.t.translate('common.delete'),
|
||||
rejectLabel: this.t.translate('common.cancel'),
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
rejectButtonStyleClass: 'p-button-outlined',
|
||||
accept: () => {
|
||||
this.bookService.deleteBooks(new Set([this.book.id])).subscribe();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
label: this.t.translate('book.card.menu.delete'),
|
||||
icon: this.isSubMenuLoading ? 'pi pi-spin pi-spinner' : 'pi pi-trash',
|
||||
items: [{label: this.t.translate('book.card.menu.loading'), disabled: true}]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (this.user?.permissions.canEmailBook) {
|
||||
items.push(
|
||||
{
|
||||
label: this.t.translate('book.card.menu.emailBook'),
|
||||
icon: 'pi pi-envelope',
|
||||
items: [{
|
||||
label: this.t.translate('book.card.menu.quickSend'),
|
||||
icon: 'pi pi-envelope',
|
||||
command: () => {
|
||||
const doSend = () => {
|
||||
this.emailService.emailBookQuick(this.book.id).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: this.t.translate('common.success'),
|
||||
detail: this.t.translate('book.card.toast.quickSendSuccessDetail'),
|
||||
});
|
||||
},
|
||||
error: (err) => {
|
||||
const errorMessage = err?.error?.message || this.t.translate('book.card.toast.quickSendErrorDetail');
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: errorMessage,
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
if (this.book.primaryFile?.fileSizeKb && this.book.primaryFile.fileSizeKb > 25 * 1024) {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.card.confirm.largeFileMessage'),
|
||||
header: this.t.translate('book.card.confirm.largeFileHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('book.card.confirm.sendAnyway'),
|
||||
rejectLabel: this.t.translate('common.cancel'),
|
||||
acceptButtonProps: { severity: 'warn' },
|
||||
rejectButtonProps: { severity: 'secondary' },
|
||||
accept: doSend,
|
||||
});
|
||||
} else {
|
||||
doSend();
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.card.menu.customSend'),
|
||||
icon: 'pi pi-envelope',
|
||||
command: () => {
|
||||
this.bookDialogHelperService.openCustomSendDialog(this.book);
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
if (this.user?.permissions.canEditMetadata) {
|
||||
items.push({
|
||||
label: this.t.translate('book.card.menu.metadata'),
|
||||
icon: 'pi pi-database',
|
||||
items: [
|
||||
{
|
||||
label: this.t.translate('book.card.menu.searchMetadata'),
|
||||
icon: 'pi pi-sparkles',
|
||||
command: () => {
|
||||
setTimeout(() => {
|
||||
this.router.navigate(['/book', this.book.id], {
|
||||
queryParams: {tab: 'match'}
|
||||
})
|
||||
}, 150);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.card.menu.autoFetch'),
|
||||
icon: 'pi pi-bolt',
|
||||
command: () => {
|
||||
this.taskHelperService.refreshMetadataTask({
|
||||
refreshType: MetadataRefreshType.BOOKS,
|
||||
bookIds: [this.book.id],
|
||||
}).subscribe();
|
||||
}
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.card.menu.customFetch'),
|
||||
icon: 'pi pi-sync',
|
||||
command: () => {
|
||||
this.bookDialogHelperService.openMetadataRefreshDialog(new Set([this.book!.id]))
|
||||
},
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.card.menu.regenerateCover'),
|
||||
icon: 'pi pi-image',
|
||||
command: () => {
|
||||
this.bookMetadataManageService.regenerateCover(this.book.id).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('common.success'),
|
||||
detail: this.t.translate('book.card.toast.coverRegenSuccessDetail')
|
||||
}),
|
||||
error: (err) => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: err?.error?.message || this.t.translate('book.card.toast.coverRegenFailedDetail')
|
||||
})
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.card.menu.generateCustomCover'),
|
||||
icon: 'pi pi-palette',
|
||||
command: () => {
|
||||
this.bookMetadataManageService.generateCustomCover(this.book.id).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('common.success'),
|
||||
detail: this.t.translate('book.card.toast.customCoverSuccessDetail')
|
||||
}),
|
||||
error: (err) => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: err?.error?.message || this.t.translate('book.card.toast.customCoverFailedDetail')
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
private moreMenuItems(): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
const moreActions: MenuItem[] = [];
|
||||
|
||||
if (this.user?.permissions.canMoveOrganizeFiles && this.diskType === 'LOCAL') {
|
||||
moreActions.push({
|
||||
label: this.t.translate('book.card.menu.organizeFile'),
|
||||
icon: 'pi pi-arrows-h',
|
||||
command: () => {
|
||||
this.bookDialogHelperService.openFileMoverDialog(new Set([this.book.id]));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
moreActions.push(
|
||||
{
|
||||
label: this.t.translate('book.card.menu.readStatus'),
|
||||
icon: 'pi pi-book',
|
||||
items: Object.entries(readStatusLabels).map(([status, label]) => ({
|
||||
label,
|
||||
command: () => {
|
||||
this.bookService.updateBookReadStatus(this.book.id, status as ReadStatus).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.card.toast.readStatusUpdatedSummary'),
|
||||
detail: this.t.translate('book.card.toast.readStatusUpdatedDetail', {label}),
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.card.toast.readStatusFailedSummary'),
|
||||
detail: this.t.translate('book.card.toast.readStatusFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}))
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.card.menu.resetGrimmoryProgress'),
|
||||
icon: 'pi pi-undo',
|
||||
command: () => {
|
||||
this.bookService.resetProgress(this.book.id, ResetProgressTypes.GRIMMORY).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.card.toast.progressResetSummary'),
|
||||
detail: this.t.translate('book.card.toast.progressResetGrimmoryDetail'),
|
||||
life: 1500
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.card.toast.progressResetFailedSummary'),
|
||||
detail: this.t.translate('book.card.toast.progressResetGrimmoryFailedDetail'),
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.card.menu.resetKOReaderProgress'),
|
||||
icon: 'pi pi-undo',
|
||||
command: () => {
|
||||
this.bookService.resetProgress(this.book.id, ResetProgressTypes.KOREADER).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.card.toast.progressResetSummary'),
|
||||
detail: this.t.translate('book.card.toast.progressResetKOReaderDetail'),
|
||||
life: 1500
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.card.toast.progressResetFailedSummary'),
|
||||
detail: this.t.translate('book.card.toast.progressResetKOReaderFailedDetail'),
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
items.push({
|
||||
label: this.t.translate('book.card.menu.moreActions'),
|
||||
icon: 'pi pi-ellipsis-h',
|
||||
items: moreActions
|
||||
});
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
private openShelfDialog(): void {
|
||||
this.bookDialogHelperService.openShelfAssignerDialog(this.book, null);
|
||||
}
|
||||
|
||||
openSeriesInfo(): void {
|
||||
const seriesName = this.book?.metadata?.seriesName;
|
||||
if (this.isSeriesCollapsed && seriesName) {
|
||||
const encodedSeriesName = encodeURIComponent(seriesName);
|
||||
this.router.navigate(['/series', encodedSeriesName]);
|
||||
} else {
|
||||
this.openBookInfo(this.book);
|
||||
}
|
||||
}
|
||||
|
||||
openBookInfo(book: Book): void {
|
||||
const allBookIds = this.bookNavigationService.availableBookIds();
|
||||
if (allBookIds.length > 0) {
|
||||
this.bookNavigationService.setNavigationContext(allBookIds, book.id);
|
||||
}
|
||||
|
||||
if (this.metadataCenterViewMode === 'route') {
|
||||
this.router.navigate(['/book', book.id], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
} else {
|
||||
this.bookDialogHelperService.openBookDetailsDialog(book.id);
|
||||
}
|
||||
}
|
||||
|
||||
private getDownloadMenuItems(): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
items.push({
|
||||
label: `${this.book.fileName || 'Book File'}`,
|
||||
icon: 'pi pi-file',
|
||||
command: () => {
|
||||
this.bookFileService.downloadFile(this.book);
|
||||
}
|
||||
});
|
||||
|
||||
if (this.hasAdditionalFiles()) {
|
||||
items.push({separator: true});
|
||||
}
|
||||
|
||||
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) {
|
||||
this.book.alternativeFormats.forEach(format => {
|
||||
const extension = this.getFileExtension(format.filePath);
|
||||
items.push({
|
||||
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.downloadAdditionalFile(this.book, format.id)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0 &&
|
||||
this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
|
||||
items.push({separator: true});
|
||||
}
|
||||
|
||||
if (this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
|
||||
this.book.supplementaryFiles.forEach(file => {
|
||||
const extension = this.getFileExtension(file.filePath);
|
||||
items.push({
|
||||
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.downloadAdditionalFile(this.book, file.id)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
private getDeleteMenuItems(): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
items.push({
|
||||
label: this.t.translate('book.card.menu.book'),
|
||||
icon: 'pi pi-book',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.card.confirm.deleteBookMessage', {title: this.book.metadata?.title}),
|
||||
header: this.t.translate('book.card.confirm.deleteBookHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptLabel: this.t.translate('common.delete'),
|
||||
rejectLabel: this.t.translate('common.cancel'),
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
rejectButtonStyleClass: 'p-button-outlined',
|
||||
accept: () => {
|
||||
this.bookService.deleteBooks(new Set([this.book.id])).subscribe();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (this.hasAdditionalFiles()) {
|
||||
items.push({separator: true});
|
||||
}
|
||||
|
||||
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) {
|
||||
this.book.alternativeFormats.forEach(format => {
|
||||
const extension = this.getFileExtension(format.filePath);
|
||||
items.push({
|
||||
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.deleteAdditionalFile(this.book.id, format.id, format.fileName || 'file')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0 &&
|
||||
this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
|
||||
items.push({separator: true});
|
||||
}
|
||||
|
||||
if (this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
|
||||
this.book.supplementaryFiles.forEach(file => {
|
||||
const extension = this.getFileExtension(file.filePath);
|
||||
items.push({
|
||||
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.deleteAdditionalFile(this.book.id, file.id, file.fileName || 'file')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
private hasAdditionalFiles(): boolean {
|
||||
return !!(this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
|
||||
!!(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
|
||||
}
|
||||
|
||||
private downloadAdditionalFile(book: Book, fileId: number): void {
|
||||
this.bookFileService.downloadAdditionalFile(book, fileId);
|
||||
}
|
||||
|
||||
private deleteAdditionalFile(bookId: number, fileId: number, fileName: string): void {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.card.confirm.deleteFileMessage', {fileName}),
|
||||
header: this.t.translate('book.card.confirm.deleteFileHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
accept: () => {
|
||||
this.bookFileService.deleteAdditionalFile(bookId, fileId).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('common.success'),
|
||||
detail: this.t.translate('book.card.toast.deleteFileSuccessDetail', {fileName})
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('book.card.toast.deleteFileErrorDetail', {error: error.message || 'Unknown error'})
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getFileExtension(filePath?: string): string | null {
|
||||
if (!filePath) return null;
|
||||
const parts = filePath.split('.');
|
||||
if (parts.length < 2) return null;
|
||||
return parts.pop()?.toUpperCase() || null;
|
||||
}
|
||||
|
||||
getDisplayFormat(): string | null {
|
||||
if (!this.book?.primaryFile) {
|
||||
return 'PHY';
|
||||
}
|
||||
if (this.forceEbookMode && this.book.primaryFile?.bookType === 'AUDIOBOOK') {
|
||||
const ebookType = this.getEbookType(this.book);
|
||||
if (ebookType) {
|
||||
return ebookType;
|
||||
}
|
||||
}
|
||||
const ext = this.book?.primaryFile?.extension;
|
||||
if (ext) {
|
||||
return ext.toUpperCase();
|
||||
}
|
||||
return this.getFileExtension(this.book?.primaryFile?.filePath);
|
||||
}
|
||||
|
||||
hasDigitalFile(): boolean {
|
||||
return !!this.book?.primaryFile;
|
||||
}
|
||||
|
||||
private getFileIcon(fileType: string | null): string {
|
||||
if (!fileType) return 'pi pi-file';
|
||||
switch (fileType.toLowerCase()) {
|
||||
case 'pdf':
|
||||
return 'pi pi-file-pdf';
|
||||
case 'epub':
|
||||
case 'mobi':
|
||||
case 'azw3':
|
||||
case 'fb2':
|
||||
return 'pi pi-book';
|
||||
case 'cbz':
|
||||
case 'cbr':
|
||||
case 'cbx':
|
||||
return 'pi pi-image';
|
||||
case 'audiobook':
|
||||
case 'm4b':
|
||||
case 'm4a':
|
||||
case 'mp3':
|
||||
case 'opus':
|
||||
return 'pi pi-headphones';
|
||||
default:
|
||||
return 'pi pi-file';
|
||||
}
|
||||
}
|
||||
|
||||
private getFileSizeInMB(fileInfo: AdditionalFile): string {
|
||||
const sizeKb = fileInfo?.fileSizeKb;
|
||||
return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-';
|
||||
}
|
||||
|
||||
private lastMouseEvent: MouseEvent | null = null;
|
||||
|
||||
captureMouseEvent(event: MouseEvent): void {
|
||||
this.lastMouseEvent = event;
|
||||
}
|
||||
|
||||
onCardClick(event: MouseEvent): void {
|
||||
if (!event.ctrlKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.toggleCardSelection(!this.isSelected)
|
||||
}
|
||||
|
||||
toggleCardSelection(selected: boolean): void {
|
||||
if (!this.isCheckboxEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isSelected = selected;
|
||||
const shiftKey = this.lastMouseEvent?.shiftKey ?? false;
|
||||
|
||||
this.checkboxClick.emit({
|
||||
index: this.index,
|
||||
book: this.book,
|
||||
selected: selected,
|
||||
shiftKey: shiftKey,
|
||||
});
|
||||
|
||||
if (this.onBookSelect) {
|
||||
this.onBookSelect(this.book, selected);
|
||||
}
|
||||
|
||||
this.lastMouseEvent = null;
|
||||
}
|
||||
|
||||
toggleSelection(event: CheckboxChangeEvent): void {
|
||||
this.toggleCardSelection(event.checked);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {DialogLauncherService, DialogSize, DialogStyle} from '../../../../shared/services/dialog-launcher.service';
|
||||
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
|
||||
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component';
|
||||
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {BulkMetadataUpdateComponent} from '../../../metadata/component/bulk-metadata-update/bulk-metadata-update-component';
|
||||
import {MultiBookMetadataEditorComponent} from '../../../metadata/component/multi-book-metadata-editor/multi-book-metadata-editor-component';
|
||||
import {MultiBookMetadataFetchComponent} from '../../../metadata/component/multi-book-metadata-fetch/multi-book-metadata-fetch-component';
|
||||
import {FileMoverComponent} from '../../../../shared/components/file-mover/file-mover-component';
|
||||
import {ShelfCreatorComponent} from '../shelf-creator/shelf-creator.component';
|
||||
import {BookSenderComponent} from '../book-sender/book-sender.component';
|
||||
import {MetadataFetchOptionsComponent} from '../../../metadata/component/metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component';
|
||||
import {BookMetadataCenterComponent} from '../../../metadata/component/book-metadata-center/book-metadata-center.component';
|
||||
import {CoverSearchComponent} from '../../../metadata/component/cover-search/cover-search.component';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {AdditionalFileUploaderComponent} from '../additional-file-uploader/additional-file-uploader.component';
|
||||
import {BookFileAttacherComponent} from '../book-file-attacher/book-file-attacher.component';
|
||||
import {AddPhysicalBookDialogComponent} from '../add-physical-book-dialog/add-physical-book-dialog.component';
|
||||
import {BulkIsbnImportDialogComponent} from '../bulk-isbn-import-dialog/bulk-isbn-import-dialog.component';
|
||||
import {DuplicateMergerComponent} from '../duplicate-merger/duplicate-merger.component';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookDialogHelperService {
|
||||
|
||||
private dialogLauncherService = inject(DialogLauncherService);
|
||||
|
||||
private openDialog(component: unknown, options: {}): DynamicDialogRef | null {
|
||||
return this.dialogLauncherService.openDialog(component, options);
|
||||
}
|
||||
|
||||
openBookDetailsDialog(bookId: number): DynamicDialogRef | null {
|
||||
return this.openDialog(BookMetadataCenterComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `book-details-dialog ${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
bookId: bookId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openShelfAssignerDialog(book: Book | null, bookIds: Set<number> | null): DynamicDialogRef | null {
|
||||
const data: any = {};
|
||||
if (book !== null) {
|
||||
data.isMultiBooks = false;
|
||||
data.book = book;
|
||||
} else if (bookIds !== null) {
|
||||
data.isMultiBooks = true;
|
||||
data.bookIds = bookIds;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
return this.openDialog(ShelfAssignerComponent, {
|
||||
showHeader: false,
|
||||
data: data,
|
||||
styleClass: `${DialogSize.SM} ${DialogStyle.MINIMAL}`,
|
||||
});
|
||||
}
|
||||
|
||||
openShelfCreatorDialog(): DynamicDialogRef {
|
||||
return this.openDialog(ShelfCreatorComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
})!;
|
||||
}
|
||||
|
||||
openLockUnlockMetadataDialog(bookIds: Set<number>): DynamicDialogRef | null {
|
||||
return this.openDialog(LockUnlockMetadataDialogComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
bookIds: Array.from(bookIds),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openMetadataRefreshDialog(bookIds: Set<number>): DynamicDialogRef | null {
|
||||
return this.openDialog(MultiBookMetadataFetchComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
bookIds: Array.from(bookIds),
|
||||
metadataRefreshType: MetadataRefreshType.BOOKS,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openBulkMetadataEditDialog(bookIds: Set<number>): DynamicDialogRef | null {
|
||||
return this.openDialog(BulkMetadataUpdateComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.XL} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
bookIds: Array.from(bookIds),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openMultibookMetadataEditorDialog(bookIds: Set<number>): DynamicDialogRef | null {
|
||||
return this.openDialog(MultiBookMetadataEditorComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
bookIds: Array.from(bookIds),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openFileMoverDialog(bookIds: Set<number>): DynamicDialogRef | null {
|
||||
return this.openDialog(FileMoverComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
maximizable: true,
|
||||
data: {
|
||||
bookIds: Array.from(bookIds),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openCustomSendDialog(book: Book): DynamicDialogRef | null {
|
||||
return this.openDialog(BookSenderComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.SM} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
book: book,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openCoverSearchDialog(bookId: number, coverType?: 'ebook' | 'audiobook'): DynamicDialogRef | null {
|
||||
return this.openDialog(CoverSearchComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
bookId: bookId,
|
||||
coverType: coverType,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openAdditionalFileUploaderDialog(book: Book): DynamicDialogRef | null {
|
||||
return this.openDialog(AdditionalFileUploaderComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
book: book,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openBookFileAttacherDialog(sourceBook: Book): DynamicDialogRef | null {
|
||||
return this.openDialog(BookFileAttacherComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
sourceBook: sourceBook,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openBulkBookFileAttacherDialog(sourceBooks: Book[]): DynamicDialogRef | null {
|
||||
return this.openDialog(BookFileAttacherComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
sourceBooks: sourceBooks,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openDuplicateMergerDialog(libraryId: number): DynamicDialogRef | null {
|
||||
return this.openDialog(DuplicateMergerComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.XL} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
libraryId: libraryId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openAddPhysicalBookDialog(libraryId?: number): DynamicDialogRef | null {
|
||||
return this.openDialog(AddPhysicalBookDialogComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
libraryId: libraryId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openBulkIsbnImportDialog(libraryId?: number): DynamicDialogRef | null {
|
||||
return this.openDialog(BulkIsbnImportDialogComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
libraryId: libraryId,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {ParamMap} from '@angular/router';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {SortOption} from '../../model/sort.model';
|
||||
import {SortService} from '../../service/sort.service';
|
||||
import {filterBooksBySearchTerm} from './filters/HeaderFilter';
|
||||
import {filterBooksByFilters} from './filters/sidebar-filter';
|
||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||
import {QUERY_PARAMS} from './book-browser-query-params.service';
|
||||
import {BookFilterMode} from '../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookFilterOrchestrationService {
|
||||
private sortService = inject(SortService);
|
||||
|
||||
applyFilters(
|
||||
books: Book[],
|
||||
searchTerm: string,
|
||||
activeFilters: Record<string, unknown[]> | null,
|
||||
filterMode: BookFilterMode,
|
||||
seriesCollapseFilter: SeriesCollapseFilter,
|
||||
isSeriesCollapsed: boolean,
|
||||
forceExpandSeries: boolean,
|
||||
sortCriteria: SortOption[]
|
||||
): Book[] {
|
||||
const searchedBooks = filterBooksBySearchTerm(books, searchTerm);
|
||||
const filteredBooks = filterBooksByFilters(searchedBooks, activeFilters, filterMode);
|
||||
const collapsedBooks = seriesCollapseFilter.collapseBooks(filteredBooks, forceExpandSeries, isSeriesCollapsed);
|
||||
return this.sortService.applyMultiSort(collapsedBooks, sortCriteria);
|
||||
}
|
||||
|
||||
shouldForceExpandSeries(queryParamMap: ParamMap): boolean {
|
||||
const filterParam = queryParamMap.get(QUERY_PARAMS.FILTER);
|
||||
return !!filterParam && filterParam.split(',').some(pair => pair.trim().startsWith('series:'));
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.filter'">
|
||||
<div class="book-filter-container">
|
||||
|
||||
<div class="filter-header">
|
||||
<span class="filter-title">{{ t('title') }}</span>
|
||||
<p-selectButton
|
||||
[options]="filterModeOptions"
|
||||
[(ngModel)]="selectedFilterMode"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="filter-mode-select"
|
||||
allowEmpty="false"
|
||||
></p-selectButton>
|
||||
</div>
|
||||
|
||||
<div class="filter-content">
|
||||
<p-accordion [value]="expandedPanels" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
|
||||
@for (filterType of visibleFilterTypes; track trackByFilterType(i, filterType); let i = $index) {
|
||||
@if (filterSignals[filterType](); as filters) {
|
||||
@if (filters.length > 0) {
|
||||
<p-accordion-panel [value]="i">
|
||||
<p-accordion-header>
|
||||
<span class="filter-type-label">
|
||||
<span class="filter-label-text">
|
||||
{{ getFilterLabel(filterType) }}
|
||||
</span>
|
||||
@if (activeFilters[filterType]?.length) {
|
||||
<span class="active-filter-count">
|
||||
({{ activeFilters[filterType].length }})
|
||||
</span>
|
||||
}
|
||||
</span>
|
||||
</p-accordion-header>
|
||||
|
||||
<p-accordion-content>
|
||||
@if (expandedPanels.includes(i)) {
|
||||
<cdk-virtual-scroll-viewport
|
||||
[itemSize]="28"
|
||||
[style.height.px]="getVirtualScrollHeight(filters.length)"
|
||||
class="filter-list">
|
||||
<div
|
||||
*cdkVirtualFor="let filter of filters; trackBy: trackByFilter"
|
||||
class="filter-row"
|
||||
[ngClass]="{
|
||||
'active': activeFilters[filterType]?.includes(getFilterValueId(filter)),
|
||||
'active-not': activeFilters[filterType]?.includes(getFilterValueId(filter)) && selectedFilterMode === 'not'
|
||||
}"
|
||||
(click)="handleFilterClick(filterType, getFilterValueId(filter))">
|
||||
<span class="filter-value-text">{{ getFilterValueDisplay(filter) }}</span>
|
||||
<p-badge class="filter-value-badge" [value]="filter.bookCount"></p-badge>
|
||||
</div>
|
||||
</cdk-virtual-scroll-viewport>
|
||||
@if (truncatedFilters[filterType]) {
|
||||
<div class="truncation-notice">
|
||||
{{ t('showingFirst100') }}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</p-accordion-content>
|
||||
</p-accordion-panel>
|
||||
}
|
||||
}
|
||||
}
|
||||
</p-accordion>
|
||||
|
||||
<div class="footer-notice">
|
||||
{{ t('footerNote') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
Executable
+129
@@ -0,0 +1,129 @@
|
||||
:host ::ng-deep p-accordion-header {
|
||||
--p-accordion-header-padding: 0.6rem 1rem;
|
||||
}
|
||||
|
||||
:host ::ng-deep .p-togglebutton {
|
||||
--p-togglebutton-content-padding: 0.25rem 0.35rem;
|
||||
}
|
||||
|
||||
:host ::ng-deep .cdk-virtual-scroll-orientation-vertical .cdk-virtual-scroll-content-wrapper {
|
||||
width: calc(var(--sidebar-width, 225px) - 35px) !important;
|
||||
min-width: unset;
|
||||
}
|
||||
|
||||
.book-filter-container {
|
||||
height: calc(100dvh - 6.1rem);
|
||||
border-radius: 0.75rem;
|
||||
overflow: hidden;
|
||||
background: var(--card-background);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.filter-header {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.filter-title {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.filter-mode-select {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
:host ::ng-deep .filter-mode-select .p-togglebutton-label {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.filter-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding-bottom: 1rem;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.filter-type-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.filter-label-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 1;
|
||||
max-width: 175px;
|
||||
}
|
||||
|
||||
.active-filter-count {
|
||||
font-size: 0.875rem;
|
||||
color: var(--primary-color);
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.filter-list {
|
||||
padding-right: 0.25rem;
|
||||
}
|
||||
|
||||
.filter-row {
|
||||
cursor: pointer;
|
||||
transition: colors 200ms ease-in-out;
|
||||
height: 26px;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
max-width: 97%;
|
||||
|
||||
&.active {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
&.active-not {
|
||||
color: var(--p-red-400);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-value-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.filter-value-badge {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.truncation-notice {
|
||||
font-size: 0.75rem;
|
||||
color: #6b7280;
|
||||
text-align: center;
|
||||
padding-top: 0.5rem;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.footer-notice {
|
||||
font-size: 0.75rem;
|
||||
color: #6b7280;
|
||||
text-align: center;
|
||||
padding-top: 1rem;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
import {ChangeDetectionStrategy, Component, effect, EventEmitter, inject, Input, OnDestroy, OnInit, Output, Signal, signal} from '@angular/core';
|
||||
import {Subject, takeUntil} from 'rxjs';
|
||||
import {Library} from '../../../model/library.model';
|
||||
import {Shelf} from '../../../model/shelf.model';
|
||||
import {EntityType} from '../book-browser.component';
|
||||
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
|
||||
import {CdkFixedSizeVirtualScroll, CdkVirtualForOf, CdkVirtualScrollViewport} from '@angular/cdk/scrolling';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {Badge} from 'primeng/badge';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {SelectButton} from 'primeng/selectbutton';
|
||||
import {BookFilterMode, DEFAULT_VISIBLE_FILTERS, UserService, VisibleFilterType} from '../../../../settings/user-management/user.service';
|
||||
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
|
||||
import {Filter, FILTER_LABEL_KEYS, FilterType} from './book-filter.config';
|
||||
import {BookFilterService} from './book-filter.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
interface FilterModeOption {
|
||||
label: string;
|
||||
value: BookFilterMode;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-filter',
|
||||
templateUrl: './book-filter.component.html',
|
||||
styleUrls: ['./book-filter.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
standalone: true,
|
||||
imports: [
|
||||
Accordion, AccordionPanel, AccordionHeader, AccordionContent,
|
||||
CdkVirtualScrollViewport, CdkFixedSizeVirtualScroll, CdkVirtualForOf,
|
||||
NgClass, Badge, FormsModule, SelectButton,
|
||||
TranslocoDirective
|
||||
]
|
||||
})
|
||||
export class BookFilterComponent implements OnInit, OnDestroy {
|
||||
@Input() set entity(value: Library | Shelf | MagicShelf | null | undefined) {
|
||||
this.entitySignal.set(value ?? null);
|
||||
}
|
||||
@Input() set entityType(value: EntityType | undefined) {
|
||||
this.entityTypeSignal.set(value ?? EntityType.ALL_BOOKS);
|
||||
}
|
||||
@Input() resetFilter$!: Subject<void>;
|
||||
@Input() showFilter = false;
|
||||
|
||||
@Output() filterSelected = new EventEmitter<Record<string, unknown> | null>();
|
||||
@Output() filterModeChanged = new EventEmitter<BookFilterMode>();
|
||||
|
||||
private readonly filterService = inject(BookFilterService);
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
private readonly entitySignal = signal<Library | Shelf | MagicShelf | null>(null);
|
||||
private readonly entityTypeSignal = signal<EntityType>(EntityType.ALL_BOOKS);
|
||||
private readonly activeFiltersSignal = signal<Record<string, unknown[]> | null>(null);
|
||||
private readonly filterModeSignal = signal<BookFilterMode>('and');
|
||||
|
||||
activeFilters: Record<string, unknown[]> = {};
|
||||
filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.createFilterSignals(
|
||||
this.entitySignal,
|
||||
this.entityTypeSignal,
|
||||
this.activeFiltersSignal,
|
||||
this.filterModeSignal
|
||||
);
|
||||
filterTypes: FilterType[] = Object.keys(this.filterSignals) as FilterType[];
|
||||
visibleFilterTypes: FilterType[] = [];
|
||||
expandedPanels: number[] = [0];
|
||||
truncatedFilters: Record<string, boolean> = {};
|
||||
|
||||
private _selectedFilterMode: BookFilterMode = 'and';
|
||||
private _visibleFilters: VisibleFilterType[] = [...DEFAULT_VISIBLE_FILTERS];
|
||||
|
||||
readonly filterLabelKeys = FILTER_LABEL_KEYS;
|
||||
|
||||
getFilterLabel(type: FilterType): string {
|
||||
const key = this.filterLabelKeys[type];
|
||||
return key ? this.t.translate(key) : type;
|
||||
}
|
||||
readonly filterModeOptions: FilterModeOption[] = [
|
||||
{label: 'AND', value: 'and'},
|
||||
{label: 'OR', value: 'or'},
|
||||
{label: 'NOT', value: 'not'},
|
||||
{label: '1', value: 'single'}
|
||||
];
|
||||
|
||||
get selectedFilterMode(): BookFilterMode {
|
||||
return this._selectedFilterMode;
|
||||
}
|
||||
|
||||
set selectedFilterMode(mode: BookFilterMode) {
|
||||
if (mode === this._selectedFilterMode) return;
|
||||
this._selectedFilterMode = mode;
|
||||
this.filterModeSignal.set(mode);
|
||||
this.filterModeChanged.emit(mode);
|
||||
this.emitFilters();
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.updateVisibleFilterTypes();
|
||||
this.updateExpandedPanels();
|
||||
this.subscribeToUserSettings();
|
||||
this.subscribeToReset();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
handleFilterClick(filterType: string, value: unknown): void {
|
||||
if (this._selectedFilterMode === 'single') {
|
||||
this.handleSingleMode(filterType, value);
|
||||
} else {
|
||||
this.handleMultiMode(filterType, value);
|
||||
}
|
||||
this.emitFilters();
|
||||
}
|
||||
|
||||
setFilters(filters: Record<string, unknown>): void {
|
||||
this.activeFilters = {};
|
||||
for (const [key, value] of Object.entries(filters)) {
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
this.activeFilters[key] = values.map(v => this.filterService.processFilterValue(key, v));
|
||||
}
|
||||
this.emitFilters();
|
||||
}
|
||||
|
||||
clearActiveFilter(): void {
|
||||
this.activeFilters = {};
|
||||
this.expandedPanels = [0];
|
||||
this.activeFiltersSignal.set(null);
|
||||
this.filterSelected.emit(null);
|
||||
}
|
||||
|
||||
onExpandedPanelsChange(value: string | number | string[] | number[] | null | undefined): void {
|
||||
if (Array.isArray(value)) {
|
||||
this.expandedPanels = value.map(Number);
|
||||
}
|
||||
}
|
||||
|
||||
onFiltersChanged(): void {
|
||||
this.updateExpandedPanels();
|
||||
}
|
||||
|
||||
getVirtualScrollHeight = (itemCount: number): number => Math.min(itemCount * 28, 440);
|
||||
|
||||
trackByFilterType = (_: number, type: FilterType): string => type;
|
||||
|
||||
trackByFilter = (_: number, f: Filter): unknown => this.getFilterValueId(f);
|
||||
|
||||
getFilterValueId(f: Filter): unknown {
|
||||
const value = f.value;
|
||||
return typeof value === 'object' && value !== null && 'id' in value
|
||||
? value.id
|
||||
: f.value;
|
||||
}
|
||||
|
||||
getFilterValueDisplay(f: Filter): string {
|
||||
const value = f.value;
|
||||
if (typeof value === 'object' && value !== null && 'name' in value) {
|
||||
return String(value.name ?? '');
|
||||
}
|
||||
return String(value ?? '');
|
||||
}
|
||||
|
||||
private subscribeToUserSettings(): void {
|
||||
effect(() => {
|
||||
const user = this.userService.currentUser();
|
||||
if (!user) return;
|
||||
this._visibleFilters = user.userSettings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS];
|
||||
this.updateVisibleFilterTypes();
|
||||
});
|
||||
}
|
||||
|
||||
private updateVisibleFilterTypes(): void {
|
||||
this.visibleFilterTypes = this._visibleFilters.filter(
|
||||
vf => this.filterTypes.includes(vf as FilterType)
|
||||
) as FilterType[];
|
||||
}
|
||||
|
||||
private subscribeToReset(): void {
|
||||
this.resetFilter$?.pipe(takeUntil(this.destroy$)).subscribe(() => this.clearActiveFilter());
|
||||
}
|
||||
|
||||
private handleSingleMode(filterType: string, value: unknown): void {
|
||||
const id = this.extractId(value);
|
||||
const current = this.activeFilters[filterType];
|
||||
const isSame = current?.length === 1 && this.valuesMatch(current[0], id);
|
||||
|
||||
this.activeFilters = isSame ? {} : {[filterType]: [id]};
|
||||
}
|
||||
|
||||
private handleMultiMode(filterType: string, value: unknown): void {
|
||||
const id = this.extractId(value);
|
||||
|
||||
if (!this.activeFilters[filterType]) {
|
||||
this.activeFilters[filterType] = [];
|
||||
}
|
||||
|
||||
const arr = this.activeFilters[filterType];
|
||||
const index = arr.findIndex(v => this.valuesMatch(v, id));
|
||||
|
||||
if (index > -1) {
|
||||
arr.splice(index, 1);
|
||||
if (arr.length === 0) delete this.activeFilters[filterType];
|
||||
} else {
|
||||
arr.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
private extractId(value: unknown): unknown {
|
||||
return typeof value === 'object' && value !== null && 'id' in value
|
||||
? (value as { id: unknown }).id
|
||||
: value;
|
||||
}
|
||||
|
||||
private valuesMatch(a: unknown, b: unknown): boolean {
|
||||
return a === b || String(a) === String(b);
|
||||
}
|
||||
|
||||
private emitFilters(): void {
|
||||
const hasFilters = Object.keys(this.activeFilters).length > 0;
|
||||
const filtersToEmit = hasFilters ? {...this.activeFilters} : null;
|
||||
this.activeFiltersSignal.set(filtersToEmit);
|
||||
this.filterSelected.emit(filtersToEmit);
|
||||
}
|
||||
|
||||
private updateExpandedPanels(): void {
|
||||
const panels = new Set(this.expandedPanels);
|
||||
this.visibleFilterTypes.forEach((type, i) => {
|
||||
if (this.activeFilters[type]?.length) panels.add(i);
|
||||
});
|
||||
this.expandedPanels = panels.size > 0 ? [...panels] : [0];
|
||||
}
|
||||
}
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
|
||||
// ============================================================================
|
||||
// TYPES
|
||||
// ============================================================================
|
||||
|
||||
export interface FilterValue {
|
||||
id?: string | number;
|
||||
name?: string;
|
||||
sortIndex?: number;
|
||||
}
|
||||
|
||||
export interface Filter<T extends FilterValue = FilterValue> {
|
||||
value: T;
|
||||
bookCount: number;
|
||||
}
|
||||
|
||||
export type FilterType =
|
||||
| 'author' | 'category' | 'series' | 'bookType' | 'readStatus'
|
||||
| 'personalRating' | 'publisher' | 'matchScore' | 'library' | 'shelf'
|
||||
| 'shelfStatus' | 'tag' | 'publishedDate' | 'fileSize' | 'amazonRating'
|
||||
| 'goodreadsRating' | 'hardcoverRating' | 'language' | 'pageCount' | 'mood'
|
||||
| 'ageRating' | 'contentRating'
|
||||
| 'narrator'
|
||||
| 'comicCharacter' | 'comicTeam' | 'comicLocation' | 'comicCreator';
|
||||
|
||||
export type SortMode = 'count' | 'sortIndex';
|
||||
|
||||
export interface RangeConfig {
|
||||
id: number;
|
||||
label: string;
|
||||
min: number;
|
||||
max: number;
|
||||
sortIndex: number;
|
||||
}
|
||||
|
||||
export interface FilterConfig {
|
||||
label: string;
|
||||
extractor: (book: Book) => FilterValue[];
|
||||
sortMode: SortMode;
|
||||
isNumericId?: boolean;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// CONSTANTS
|
||||
// ============================================================================
|
||||
|
||||
export const READ_STATUS_LABELS: Readonly<Record<ReadStatus, string>> = {
|
||||
[ReadStatus.UNREAD]: 'Unread',
|
||||
[ReadStatus.READING]: 'Reading',
|
||||
[ReadStatus.RE_READING]: 'Re-reading',
|
||||
[ReadStatus.PARTIALLY_READ]: 'Partially Read',
|
||||
[ReadStatus.PAUSED]: 'Paused',
|
||||
[ReadStatus.READ]: 'Read',
|
||||
[ReadStatus.WONT_READ]: 'Won\'t Read',
|
||||
[ReadStatus.ABANDONED]: 'Abandoned',
|
||||
[ReadStatus.UNSET]: 'Unset'
|
||||
};
|
||||
|
||||
export const RATING_RANGES_5: readonly RangeConfig[] = [
|
||||
{id: 0, label: '0 to 1', min: 0, max: 1, sortIndex: 0},
|
||||
{id: 1, label: '1 to 2', min: 1, max: 2, sortIndex: 1},
|
||||
{id: 2, label: '2 to 3', min: 2, max: 3, sortIndex: 2},
|
||||
{id: 3, label: '3 to 4', min: 3, max: 4, sortIndex: 3},
|
||||
{id: 4, label: '4 to 4.5', min: 4, max: 4.5, sortIndex: 4},
|
||||
{id: 5, label: '4.5+', min: 4.5, max: Infinity, sortIndex: 5}
|
||||
];
|
||||
|
||||
export const RATING_OPTIONS_10: readonly RangeConfig[] = Array.from({length: 10}, (_, i) => ({
|
||||
id: i + 1,
|
||||
label: `${i + 1}`,
|
||||
min: i + 1,
|
||||
max: i + 2,
|
||||
sortIndex: i
|
||||
}));
|
||||
|
||||
export const FILE_SIZE_RANGES: readonly RangeConfig[] = [
|
||||
{id: 0, label: '< 1 MB', min: 0, max: 1024, sortIndex: 0},
|
||||
{id: 1, label: '1–10 MB', min: 1024, max: 10240, sortIndex: 1},
|
||||
{id: 2, label: '10–50 MB', min: 10240, max: 51200, sortIndex: 2},
|
||||
{id: 3, label: '50–100 MB', min: 51200, max: 102400, sortIndex: 3},
|
||||
{id: 4, label: '250–500 MB', min: 256000, max: 512000, sortIndex: 4},
|
||||
{id: 5, label: '0.5–1 GB', min: 512000, max: 1048576, sortIndex: 5},
|
||||
{id: 6, label: '1–2 GB', min: 1048576, max: 2097152, sortIndex: 6},
|
||||
{id: 7, label: '5+ GB', min: 5242880, max: Infinity, sortIndex: 7}
|
||||
];
|
||||
|
||||
export const PAGE_COUNT_RANGES: readonly RangeConfig[] = [
|
||||
{id: 0, label: '< 50 pages', min: 0, max: 50, sortIndex: 0},
|
||||
{id: 1, label: '50–100 pages', min: 50, max: 100, sortIndex: 1},
|
||||
{id: 2, label: '100–200 pages', min: 100, max: 200, sortIndex: 2},
|
||||
{id: 3, label: '200–400 pages', min: 200, max: 400, sortIndex: 3},
|
||||
{id: 4, label: '400–600 pages', min: 400, max: 600, sortIndex: 4},
|
||||
{id: 5, label: '600–1000 pages', min: 600, max: 1000, sortIndex: 5},
|
||||
{id: 6, label: '1000+ pages', min: 1000, max: Infinity, sortIndex: 6}
|
||||
];
|
||||
|
||||
export const MATCH_SCORE_RANGES: readonly RangeConfig[] = [
|
||||
{id: 0, min: 0.95, max: 1.01, label: 'Outstanding (95–100%)', sortIndex: 0},
|
||||
{id: 1, min: 0.90, max: 0.95, label: 'Excellent (90–94%)', sortIndex: 1},
|
||||
{id: 2, min: 0.80, max: 0.90, label: 'Great (80–89%)', sortIndex: 2},
|
||||
{id: 3, min: 0.70, max: 0.80, label: 'Good (70–79%)', sortIndex: 3},
|
||||
{id: 4, min: 0.50, max: 0.70, label: 'Fair (50–69%)', sortIndex: 4},
|
||||
{id: 5, min: 0.30, max: 0.50, label: 'Weak (30–49%)', sortIndex: 5},
|
||||
{id: 6, min: 0.00, max: 0.30, label: 'Poor (0–29%)', sortIndex: 6}
|
||||
];
|
||||
|
||||
export const AGE_RATING_OPTIONS: readonly RangeConfig[] = [
|
||||
{id: 0, min: 0, max: 1, label: 'All Ages', sortIndex: 0},
|
||||
{id: 6, min: 6, max: 7, label: '6+', sortIndex: 1},
|
||||
{id: 10, min: 10, max: 11, label: '10+', sortIndex: 2},
|
||||
{id: 13, min: 13, max: 14, label: '13+', sortIndex: 3},
|
||||
{id: 16, min: 16, max: 17, label: '16+', sortIndex: 4},
|
||||
{id: 18, min: 18, max: 19, label: '18+', sortIndex: 5},
|
||||
{id: 21, min: 21, max: 22, label: '21+', sortIndex: 6}
|
||||
];
|
||||
|
||||
export const CONTENT_RATING_LABELS: Readonly<Record<string, string>> = {
|
||||
'EVERYONE': 'Everyone',
|
||||
'TEEN': 'Teen',
|
||||
'MATURE': 'Mature',
|
||||
'ADULT': 'Adult',
|
||||
'EXPLICIT': 'Explicit'
|
||||
};
|
||||
|
||||
export const readStatusLabels = READ_STATUS_LABELS;
|
||||
export const ratingRanges = RATING_RANGES_5;
|
||||
export const ratingOptions10 = RATING_OPTIONS_10;
|
||||
export const fileSizeRanges = FILE_SIZE_RANGES;
|
||||
export const pageCountRanges = PAGE_COUNT_RANGES;
|
||||
export const matchScoreRanges = MATCH_SCORE_RANGES;
|
||||
|
||||
export const NUMERIC_ID_FILTER_TYPES = new Set<FilterType>([
|
||||
'personalRating', 'matchScore', 'fileSize', 'amazonRating',
|
||||
'goodreadsRating', 'hardcoverRating', 'pageCount', 'library', 'shelf',
|
||||
'ageRating'
|
||||
]);
|
||||
|
||||
export const FILTER_LABELS: Readonly<Record<FilterType, string>> = {
|
||||
author: 'Author',
|
||||
category: 'Genre',
|
||||
series: 'Series',
|
||||
bookType: 'File Format',
|
||||
readStatus: 'Read Status',
|
||||
personalRating: 'Personal Rating',
|
||||
publisher: 'Publisher',
|
||||
matchScore: 'Metadata Match Score',
|
||||
library: 'Library',
|
||||
shelf: 'Shelf',
|
||||
shelfStatus: 'Shelf Status',
|
||||
tag: 'Tag',
|
||||
publishedDate: 'Published Year',
|
||||
fileSize: 'File Size',
|
||||
amazonRating: 'Amazon Rating',
|
||||
goodreadsRating: 'Goodreads Rating',
|
||||
hardcoverRating: 'Hardcover Rating',
|
||||
language: 'Language',
|
||||
pageCount: 'Page Count',
|
||||
mood: 'Mood',
|
||||
ageRating: 'Age Rating',
|
||||
contentRating: 'Content Rating',
|
||||
narrator: 'Narrator',
|
||||
comicCharacter: 'Comic Character',
|
||||
comicTeam: 'Comic Team',
|
||||
comicLocation: 'Comic Location',
|
||||
comicCreator: 'Comic Creator'
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// FILTER EXTRACTORS
|
||||
// ============================================================================
|
||||
|
||||
const findInRange = (value: number | null | undefined, ranges: readonly RangeConfig[]): FilterValue[] => {
|
||||
if (value == null) return [];
|
||||
const match = ranges.find(r => value >= r.min && value < r.max);
|
||||
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
|
||||
};
|
||||
|
||||
const findExactRating10 = (rating: number | undefined): FilterValue[] => {
|
||||
if (!rating || rating < 1 || rating > 10) return [];
|
||||
const match = RATING_OPTIONS_10.find(r => r.id === rating);
|
||||
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
|
||||
};
|
||||
|
||||
const normalizeMatchScore = (score: number | null | undefined): number | null => {
|
||||
if (score == null) return null;
|
||||
return score > 1 ? score / 100 : score;
|
||||
};
|
||||
|
||||
const extractStringsAsFilters = (values: string[] | undefined): FilterValue[] =>
|
||||
values?.map(name => ({id: name, name})) ?? [];
|
||||
|
||||
const extractSingleString = (value: string | undefined | null): FilterValue[] =>
|
||||
value ? [{id: value, name: value}] : [];
|
||||
|
||||
const findExactAgeRating = (ageRating: number | null | undefined): FilterValue[] => {
|
||||
if (ageRating == null) return [];
|
||||
const match = AGE_RATING_OPTIONS.find(r => r.id === ageRating);
|
||||
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
|
||||
};
|
||||
|
||||
export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>, (book: Book) => FilterValue[]>> = {
|
||||
author: (book) => extractStringsAsFilters(book.metadata?.authors),
|
||||
category: (book) => extractStringsAsFilters(book.metadata?.categories),
|
||||
series: (book) => extractSingleString(book.metadata?.seriesName?.trim()),
|
||||
bookType: (book) => book.isPhysical ? [{id: 'PHYSICAL', name: 'PHYSICAL'}] : extractSingleString(book.primaryFile?.bookType),
|
||||
readStatus: (book) => {
|
||||
const status = book.readStatus ?? ReadStatus.UNSET;
|
||||
const validStatus = status in READ_STATUS_LABELS ? status : ReadStatus.UNSET;
|
||||
return [{id: validStatus, name: READ_STATUS_LABELS[validStatus]}];
|
||||
},
|
||||
personalRating: (book) => findExactRating10(book.personalRating ?? undefined),
|
||||
publisher: (book) => extractSingleString(book.metadata?.publisher),
|
||||
matchScore: (book) => findInRange(normalizeMatchScore(book.metadataMatchScore), MATCH_SCORE_RANGES),
|
||||
shelf: (book) => book.shelves?.map(s => ({id: s.id, name: s.name})) ?? [],
|
||||
shelfStatus: (book) => {
|
||||
const isShelved = (book.shelves?.length ?? 0) > 0;
|
||||
return [{id: isShelved ? 'shelved' : 'unshelved', name: isShelved ? 'Shelved' : 'Unshelved'}];
|
||||
},
|
||||
tag: (book) => extractStringsAsFilters(book.metadata?.tags),
|
||||
publishedDate: (book) => {
|
||||
const date = book.metadata?.publishedDate;
|
||||
if (!date) return [];
|
||||
const year = new Date(date).getFullYear().toString();
|
||||
return [{id: year, name: year}];
|
||||
},
|
||||
fileSize: (book) => findInRange(book.fileSizeKb, FILE_SIZE_RANGES),
|
||||
amazonRating: (book) => findInRange(book.metadata?.amazonRating, RATING_RANGES_5),
|
||||
goodreadsRating: (book) => findInRange(book.metadata?.goodreadsRating, RATING_RANGES_5),
|
||||
hardcoverRating: (book) => findInRange(book.metadata?.hardcoverRating, RATING_RANGES_5),
|
||||
language: (book) => extractSingleString(book.metadata?.language),
|
||||
pageCount: (book) => findInRange(book.metadata?.pageCount, PAGE_COUNT_RANGES),
|
||||
mood: (book) => extractStringsAsFilters(book.metadata?.moods),
|
||||
ageRating: (book) => findExactAgeRating(book.metadata?.ageRating),
|
||||
contentRating: (book) => {
|
||||
const rating = book.metadata?.contentRating;
|
||||
if (!rating) return [];
|
||||
const label = CONTENT_RATING_LABELS[rating] ?? rating;
|
||||
return [{id: rating, name: label}];
|
||||
},
|
||||
narrator: (book) => extractSingleString(book.metadata?.narrator),
|
||||
comicCharacter: (book) => extractStringsAsFilters(book.metadata?.comicMetadata?.characters),
|
||||
comicTeam: (book) => extractStringsAsFilters(book.metadata?.comicMetadata?.teams),
|
||||
comicLocation: (book) => extractStringsAsFilters(book.metadata?.comicMetadata?.locations),
|
||||
comicCreator: (book) => {
|
||||
const comic = book.metadata?.comicMetadata;
|
||||
if (!comic) return [];
|
||||
const creators: FilterValue[] = [];
|
||||
const roleLabels: Record<string, string> = {
|
||||
penciller: 'Penciller', inker: 'Inker', colorist: 'Colorist',
|
||||
letterer: 'Letterer', coverArtist: 'Cover Artist', editor: 'Editor'
|
||||
};
|
||||
const roles: [string[] | undefined, string][] = [
|
||||
[comic.pencillers, 'penciller'],
|
||||
[comic.inkers, 'inker'],
|
||||
[comic.colorists, 'colorist'],
|
||||
[comic.letterers, 'letterer'],
|
||||
[comic.coverArtists, 'coverArtist'],
|
||||
[comic.editors, 'editor']
|
||||
];
|
||||
for (const [names, role] of roles) {
|
||||
if (names) {
|
||||
for (const name of names) {
|
||||
creators.push({id: `${name}:${role}`, name: `${name} (${roleLabels[role]})`});
|
||||
}
|
||||
}
|
||||
}
|
||||
return creators;
|
||||
}
|
||||
};
|
||||
|
||||
// Translation key for each FilterType — used by UI components to translate filter labels
|
||||
export const FILTER_LABEL_KEYS: Readonly<Record<FilterType, string>> = {
|
||||
author: 'book.filter.labels.author',
|
||||
category: 'book.filter.labels.category',
|
||||
series: 'book.filter.labels.series',
|
||||
bookType: 'book.filter.labels.bookType',
|
||||
readStatus: 'book.filter.labels.readStatus',
|
||||
personalRating: 'book.filter.labels.personalRating',
|
||||
publisher: 'book.filter.labels.publisher',
|
||||
matchScore: 'book.filter.labels.matchScore',
|
||||
library: 'book.filter.labels.library',
|
||||
shelf: 'book.filter.labels.shelf',
|
||||
shelfStatus: 'book.filter.labels.shelfStatus',
|
||||
tag: 'book.filter.labels.tag',
|
||||
publishedDate: 'book.filter.labels.publishedDate',
|
||||
fileSize: 'book.filter.labels.fileSize',
|
||||
amazonRating: 'book.filter.labels.amazonRating',
|
||||
goodreadsRating: 'book.filter.labels.goodreadsRating',
|
||||
hardcoverRating: 'book.filter.labels.hardcoverRating',
|
||||
language: 'book.filter.labels.language',
|
||||
pageCount: 'book.filter.labels.pageCount',
|
||||
mood: 'book.filter.labels.mood',
|
||||
ageRating: 'book.filter.labels.ageRating',
|
||||
contentRating: 'book.filter.labels.contentRating',
|
||||
narrator: 'book.filter.labels.narrator',
|
||||
comicCharacter: 'book.filter.labels.comicCharacter',
|
||||
comicTeam: 'book.filter.labels.comicTeam',
|
||||
comicLocation: 'book.filter.labels.comicLocation',
|
||||
comicCreator: 'book.filter.labels.comicCreator'
|
||||
};
|
||||
|
||||
export const READ_STATUS_LABEL_KEYS: Readonly<Record<ReadStatus, string>> = {
|
||||
[ReadStatus.UNREAD]: 'book.filter.readStatus.unread',
|
||||
[ReadStatus.READING]: 'book.filter.readStatus.reading',
|
||||
[ReadStatus.RE_READING]: 'book.filter.readStatus.reReading',
|
||||
[ReadStatus.PARTIALLY_READ]: 'book.filter.readStatus.partiallyRead',
|
||||
[ReadStatus.PAUSED]: 'book.filter.readStatus.paused',
|
||||
[ReadStatus.READ]: 'book.filter.readStatus.read',
|
||||
[ReadStatus.WONT_READ]: 'book.filter.readStatus.wontRead',
|
||||
[ReadStatus.ABANDONED]: 'book.filter.readStatus.abandoned',
|
||||
[ReadStatus.UNSET]: 'book.filter.readStatus.unset'
|
||||
};
|
||||
|
||||
export const CONTENT_RATING_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
'EVERYONE': 'book.filter.contentRating.everyone',
|
||||
'TEEN': 'book.filter.contentRating.teen',
|
||||
'MATURE': 'book.filter.contentRating.mature',
|
||||
'ADULT': 'book.filter.contentRating.adult',
|
||||
'EXPLICIT': 'book.filter.contentRating.explicit'
|
||||
};
|
||||
|
||||
export const SHELF_STATUS_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
'shelved': 'book.filter.shelfStatus.shelved',
|
||||
'unshelved': 'book.filter.shelfStatus.unshelved'
|
||||
};
|
||||
|
||||
|
||||
export const COMIC_ROLE_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
penciller: 'book.filter.comicRoles.penciller',
|
||||
inker: 'book.filter.comicRoles.inker',
|
||||
colorist: 'book.filter.comicRoles.colorist',
|
||||
letterer: 'book.filter.comicRoles.letterer',
|
||||
coverArtist: 'book.filter.comicRoles.coverArtist',
|
||||
editor: 'book.filter.comicRoles.editor'
|
||||
};
|
||||
|
||||
export const FILTER_CONFIGS: Readonly<Record<Exclude<FilterType, 'library'>, Omit<FilterConfig, 'extractor'>>> = {
|
||||
author: {label: 'Author', sortMode: 'count'},
|
||||
category: {label: 'Genre', sortMode: 'count'},
|
||||
series: {label: 'Series', sortMode: 'count'},
|
||||
bookType: {label: 'Book Type', sortMode: 'count'},
|
||||
readStatus: {label: 'Read Status', sortMode: 'count'},
|
||||
personalRating: {label: 'Personal Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
publisher: {label: 'Publisher', sortMode: 'count'},
|
||||
matchScore: {label: 'Metadata Match Score', sortMode: 'sortIndex', isNumericId: true},
|
||||
shelf: {label: 'Shelf', sortMode: 'count', isNumericId: true},
|
||||
shelfStatus: {label: 'Shelf Status', sortMode: 'count'},
|
||||
tag: {label: 'Tag', sortMode: 'count'},
|
||||
publishedDate: {label: 'Published Year', sortMode: 'count'},
|
||||
fileSize: {label: 'File Size', sortMode: 'sortIndex', isNumericId: true},
|
||||
amazonRating: {label: 'Amazon Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
goodreadsRating: {label: 'Goodreads Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
hardcoverRating: {label: 'Hardcover Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
language: {label: 'Language', sortMode: 'count'},
|
||||
pageCount: {label: 'Page Count', sortMode: 'sortIndex', isNumericId: true},
|
||||
mood: {label: 'Mood', sortMode: 'count'},
|
||||
ageRating: {label: 'Age Rating', sortMode: 'sortIndex', isNumericId: true},
|
||||
contentRating: {label: 'Content Rating', sortMode: 'count'},
|
||||
narrator: {label: 'Narrator', sortMode: 'count'},
|
||||
comicCharacter: {label: 'Comic Character', sortMode: 'count'},
|
||||
comicTeam: {label: 'Comic Team', sortMode: 'count'},
|
||||
comicLocation: {label: 'Comic Location', sortMode: 'count'},
|
||||
comicCreator: {label: 'Comic Creator', sortMode: 'count'}
|
||||
};
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
import {computed, inject, Injectable, Signal} from '@angular/core';
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {Library} from '../../../model/library.model';
|
||||
import {Shelf} from '../../../model/shelf.model';
|
||||
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {LibraryService} from '../../../service/library.service';
|
||||
import {BookRuleEvaluatorService} from '../../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
import {GroupRule} from '../../../../magic-shelf/component/magic-shelf-component';
|
||||
import {EntityType} from '../book-browser.component';
|
||||
import {Filter, FILTER_CONFIGS, FILTER_EXTRACTORS, FilterType, FilterValue, NUMERIC_ID_FILTER_TYPES, SortMode} from './book-filter.config';
|
||||
import {filterBooksByFilters} from '../filters/sidebar-filter';
|
||||
import {BookFilterMode} from '../../../../settings/user-management/user.service';
|
||||
|
||||
const MAX_FILTER_ITEMS = 100;
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookFilterService {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly libraryService = inject(LibraryService);
|
||||
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||
|
||||
createFilterSignals(
|
||||
entity: Signal<Library | Shelf | MagicShelf | null>,
|
||||
entityType: Signal<EntityType>,
|
||||
activeFilters: Signal<Record<string, unknown[]> | null>,
|
||||
filterMode: Signal<BookFilterMode>
|
||||
): Record<FilterType, Signal<Filter[]>> {
|
||||
const filteredBooks = computed(() =>
|
||||
this.filterBooksByEntity(this.bookService.books(), entity(), entityType())
|
||||
);
|
||||
|
||||
const signals = {} as Record<FilterType, Signal<Filter[]>>;
|
||||
|
||||
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
|
||||
const filterType = type as Exclude<FilterType, 'library'>;
|
||||
signals[filterType] = computed(() => {
|
||||
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
|
||||
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
|
||||
});
|
||||
}
|
||||
|
||||
signals.library = computed(() => {
|
||||
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
|
||||
const libraries = this.libraryService.libraries();
|
||||
|
||||
const libraryMap = new Map(
|
||||
libraries
|
||||
.filter(lib => lib.id !== undefined)
|
||||
.map(lib => [lib.id!, lib.name])
|
||||
);
|
||||
|
||||
const filterMap = new Map<number, Filter>();
|
||||
|
||||
for (const book of books) {
|
||||
if (book.libraryId == null) continue;
|
||||
|
||||
if (!filterMap.has(book.libraryId)) {
|
||||
filterMap.set(book.libraryId, {
|
||||
value: {
|
||||
id: book.libraryId,
|
||||
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
|
||||
},
|
||||
bookCount: 0
|
||||
});
|
||||
}
|
||||
filterMap.get(book.libraryId)!.bookCount++;
|
||||
}
|
||||
|
||||
return this.sortFiltersByCount(Array.from(filterMap.values()));
|
||||
});
|
||||
|
||||
return signals;
|
||||
}
|
||||
|
||||
filterBooksByEntity(
|
||||
books: Book[],
|
||||
entity: Library | Shelf | MagicShelf | null,
|
||||
entityType: EntityType
|
||||
): Book[] {
|
||||
if (!entity) return books;
|
||||
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return books.filter(book => book.libraryId === (entity as Library).id);
|
||||
|
||||
case EntityType.SHELF: {
|
||||
const shelfId = (entity as Shelf).id;
|
||||
return books.filter(book => book.shelves?.some(s => s.id === shelfId));
|
||||
}
|
||||
|
||||
case EntityType.MAGIC_SHELF:
|
||||
return this.filterByMagicShelf(books, entity as MagicShelf);
|
||||
|
||||
default:
|
||||
return books;
|
||||
}
|
||||
}
|
||||
|
||||
processFilterValue(key: string, value: unknown): unknown {
|
||||
if (NUMERIC_ID_FILTER_TYPES.has(key as FilterType) && typeof value === 'string') {
|
||||
return Number(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
isNumericFilter(filterType: string): boolean {
|
||||
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
|
||||
}
|
||||
|
||||
private buildAndSortFilters(
|
||||
books: Book[],
|
||||
extractor: (book: Book) => FilterValue[],
|
||||
sortMode: SortMode
|
||||
): Filter[] {
|
||||
const filterMap = new Map<unknown, Filter>();
|
||||
|
||||
for (const book of books) {
|
||||
for (const item of extractor(book)) {
|
||||
const id = item.id;
|
||||
if (!filterMap.has(id)) {
|
||||
filterMap.set(id, {value: item, bookCount: 0});
|
||||
}
|
||||
filterMap.get(id)!.bookCount++;
|
||||
}
|
||||
}
|
||||
|
||||
const filters = Array.from(filterMap.values());
|
||||
const sorted = sortMode === 'sortIndex'
|
||||
? this.sortFiltersBySortIndex(filters)
|
||||
: this.sortFiltersByCount(filters);
|
||||
|
||||
return sorted.slice(0, MAX_FILTER_ITEMS);
|
||||
}
|
||||
|
||||
private sortFiltersByCount(filters: Filter[]): Filter[] {
|
||||
return filters.sort((a, b) => {
|
||||
if (b.bookCount !== a.bookCount) return b.bookCount - a.bookCount;
|
||||
return this.compareNames(a, b);
|
||||
});
|
||||
}
|
||||
|
||||
private sortFiltersBySortIndex(filters: Filter[]): Filter[] {
|
||||
return filters.sort((a, b) => {
|
||||
const aIndex = (a.value as { sortIndex?: number }).sortIndex ?? 999;
|
||||
const bIndex = (b.value as { sortIndex?: number }).sortIndex ?? 999;
|
||||
if (aIndex !== bIndex) return aIndex - bIndex;
|
||||
return this.compareNames(a, b);
|
||||
});
|
||||
}
|
||||
|
||||
private compareNames(a: Filter, b: Filter): number {
|
||||
const aName = String((a.value as { name?: string }).name ?? '');
|
||||
const bName = String((b.value as { name?: string }).name ?? '');
|
||||
return aName.localeCompare(bName);
|
||||
}
|
||||
|
||||
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
|
||||
if (!magicShelf.filterJson) return [];
|
||||
try {
|
||||
const groupRule = JSON.parse(magicShelf.filterJson) as GroupRule;
|
||||
return books.filter(book => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule, books));
|
||||
} catch {
|
||||
console.warn('Invalid filterJson for MagicShelf');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import {computed, Injectable, signal} from '@angular/core';
|
||||
import {Book} from '../../model/book.model';
|
||||
|
||||
export interface CheckboxClickEvent {
|
||||
index: number;
|
||||
book: Book;
|
||||
selected: boolean;
|
||||
shiftKey: boolean;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookSelectionService {
|
||||
private readonly _selectedBooks = signal<Set<number>>(new Set());
|
||||
readonly selectedBooks = this._selectedBooks.asReadonly();
|
||||
readonly selectedCount = computed(() => this._selectedBooks().size);
|
||||
|
||||
private currentBooks: Book[] = [];
|
||||
private lastSelectedIndex: number | null = null;
|
||||
|
||||
setCurrentBooks(books: Book[]): void {
|
||||
this.currentBooks = books;
|
||||
}
|
||||
|
||||
selectBook(book: Book): void {
|
||||
this._selectedBooks.update(current => {
|
||||
const next = new Set(current);
|
||||
if (book.seriesBooks) {
|
||||
book.seriesBooks.forEach(seriesBook => next.add(seriesBook.id));
|
||||
} else {
|
||||
next.add(book.id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
deselectBook(book: Book): void {
|
||||
this._selectedBooks.update(current => {
|
||||
const next = new Set(current);
|
||||
if (book.seriesBooks) {
|
||||
book.seriesBooks.forEach(seriesBook => next.delete(seriesBook.id));
|
||||
} else {
|
||||
next.delete(book.id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
handleCheckboxClick(event: CheckboxClickEvent): void {
|
||||
const {index, book, selected, shiftKey} = event;
|
||||
|
||||
if (!shiftKey || this.lastSelectedIndex === null) {
|
||||
this.handleBookSelection(book, selected);
|
||||
this.lastSelectedIndex = index;
|
||||
} else {
|
||||
const start = Math.min(this.lastSelectedIndex, index);
|
||||
const end = Math.max(this.lastSelectedIndex, index);
|
||||
const isUnselectingRange = !selected;
|
||||
|
||||
for (let i = start; i <= end; i++) {
|
||||
const rangeBook = this.currentBooks[i];
|
||||
if (!rangeBook) continue;
|
||||
this.handleBookSelection(rangeBook, !isUnselectingRange);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handleBookSelection(book: Book, selected: boolean): void {
|
||||
if (selected) {
|
||||
this.selectBook(book);
|
||||
} else {
|
||||
this.deselectBook(book);
|
||||
}
|
||||
}
|
||||
|
||||
selectAll(): void {
|
||||
if (!this.currentBooks || this.currentBooks.length === 0) return;
|
||||
|
||||
this._selectedBooks.update(current => {
|
||||
const next = new Set(current);
|
||||
for (const book of this.currentBooks) {
|
||||
next.add(book.id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
deselectAll(): void {
|
||||
this._selectedBooks.set(new Set());
|
||||
this.lastSelectedIndex = null;
|
||||
}
|
||||
|
||||
setSelectedBooks(bookIds: Set<number>): void {
|
||||
this._selectedBooks.set(new Set(bookIds));
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.table'">
|
||||
<p-table
|
||||
[value]="books"
|
||||
[columns]="visibleColumns"
|
||||
[dataKey]="'id'"
|
||||
[resizableColumns]="true"
|
||||
[reorderableColumns]="true"
|
||||
columnResizeMode="expand"
|
||||
[rowTrackBy]="trackByBookId"
|
||||
[metaKeySelection]="true"
|
||||
showGridlines
|
||||
stripedRows
|
||||
[scrollable]="true"
|
||||
[scrollHeight]="scrollHeight"
|
||||
[virtualScroll]="true"
|
||||
[virtualScrollItemSize]="46"
|
||||
[(selection)]="selectedBooks"
|
||||
(onHeaderCheckboxToggle)="onHeaderCheckboxToggle($event)"
|
||||
(onRowSelect)="onRowSelect($event)"
|
||||
(onRowUnselect)="onRowUnselect($event)"
|
||||
>
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th>
|
||||
<p-tableHeaderCheckbox/>
|
||||
</th>
|
||||
<th></th>
|
||||
<th class="cover-header-cell"></th>
|
||||
@for (col of visibleColumns; track col.field) {
|
||||
<th pResizableColumn>{{ col.header }}</th>
|
||||
}
|
||||
</tr>
|
||||
</ng-template>
|
||||
|
||||
<ng-template pTemplate="body" let-book>
|
||||
@if (book.metadata; as metadata) {
|
||||
<tr style="height:46px">
|
||||
<td>
|
||||
<p-tableCheckbox [value]="book"/>
|
||||
</td>
|
||||
<td class="cell-center">
|
||||
<p-button
|
||||
[icon]="isMetadataFullyLocked(metadata) ? 'pi pi-lock' : 'pi pi-lock-open'"
|
||||
[severity]="isMetadataFullyLocked(metadata) ? 'danger' : 'success'"
|
||||
[text]="true"
|
||||
[title]="isMetadataFullyLocked(metadata) ? t('locked') : t('unlocked')"
|
||||
size="small"
|
||||
[style]="{ width: '1.5rem', height: '1.5rem', padding: '0', fontSize: '0.75rem' }"
|
||||
(click)="toggleMetadataLock(metadata)">
|
||||
</p-button>
|
||||
</td>
|
||||
<td>
|
||||
<a [routerLink]="urlHelper.getBookUrl(book)">
|
||||
<img
|
||||
[attr.src]="urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn)"
|
||||
[alt]="t('bookCoverAlt')"
|
||||
class="cover-thumbnail"
|
||||
tooltipPosition="left"
|
||||
[pTooltip]="tooltipContent"
|
||||
tooltipStyleClass="cover-tooltip"
|
||||
/>
|
||||
</a>
|
||||
<ng-template #tooltipContent>
|
||||
<div class="tooltip-cover-container">
|
||||
<img
|
||||
[attr.src]="urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn)"
|
||||
[alt]="t('bookCoverAlt')"
|
||||
class="tooltip-cover-image"
|
||||
/>
|
||||
<em class="tooltip-cover-title">{{ metadata.title }}</em>
|
||||
</div>
|
||||
</ng-template>
|
||||
</td>
|
||||
|
||||
@for (col of visibleColumns; track col.field) {
|
||||
@if (col.field === 'readStatus') {
|
||||
<td class="cell-status">
|
||||
@if (shouldShowStatusIcon(book.readStatus)) {
|
||||
<div class="read-status-indicator"
|
||||
[ngClass]="getReadStatusClass(book.readStatus)"
|
||||
[pTooltip]="t('statusPrefix') + getReadStatusTooltip(book.readStatus)"
|
||||
tooltipPosition="top">
|
||||
<i [class]="getReadStatusIcon(book.readStatus)"></i>
|
||||
</div>
|
||||
}
|
||||
</td>
|
||||
} @else if (col.field === 'amazonRating' || col.field === 'goodreadsRating' || col.field === 'hardcoverRating' || col.field == 'ranobedbRating') {
|
||||
<td class="cell-rating">
|
||||
<span class="rating-wrapper">
|
||||
<p-rating
|
||||
[(ngModel)]="metadata[col.field]"
|
||||
readonly
|
||||
stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata[col.field])"
|
||||
></p-rating>
|
||||
@if (metadata[col.field] != null) {
|
||||
<span>({{ metadata[col.field]?.toFixed(1) }})</span>
|
||||
}
|
||||
</span>
|
||||
</td>
|
||||
} @else {
|
||||
<td
|
||||
[title]="getCellValue(metadata, book, col.field)"
|
||||
class="cell-text">
|
||||
@if(['title', 'authors', 'publisher', 'seriesName', 'categories', 'language'].includes(col.field)) {
|
||||
@for (item of getCellClickableValue(metadata, book, col.field); track $index; let isLast = $last) {
|
||||
<a [routerLink]="item.url" class="cell-link">
|
||||
{{ item.anchor }}</a>@if (!isLast) {<span>, </span>}
|
||||
}
|
||||
} @else {
|
||||
{{ getCellValue(metadata, book, col.field) }}
|
||||
}
|
||||
</td>
|
||||
}
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</ng-template>
|
||||
</p-table>
|
||||
</ng-container>
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
.read-status-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 0.875rem;
|
||||
font-weight: bold;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.status-read {
|
||||
color: #22c55e;
|
||||
}
|
||||
|
||||
.status-reading {
|
||||
color: #3b82f6;
|
||||
}
|
||||
|
||||
.status-re-reading {
|
||||
color: #06b6d4;
|
||||
}
|
||||
|
||||
.status-partially-read {
|
||||
color: #f59e0b;
|
||||
}
|
||||
|
||||
.status-paused {
|
||||
color: #eab308;
|
||||
}
|
||||
|
||||
.status-abandoned {
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.status-wont-read {
|
||||
color: #ec4899;
|
||||
}
|
||||
|
||||
.cover-header-cell {
|
||||
max-width: 3.5rem;
|
||||
min-width: 3.5rem;
|
||||
}
|
||||
|
||||
.cell-center {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cover-thumbnail {
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
}
|
||||
|
||||
.tooltip-cover-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.tooltip-cover-image {
|
||||
width: 40rem;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.tooltip-cover-title {
|
||||
font-size: 0.875rem;
|
||||
text-wrap: balance;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.cell-status {
|
||||
text-align: center;
|
||||
min-width: 4rem;
|
||||
max-width: 4rem;
|
||||
}
|
||||
|
||||
.cell-rating {
|
||||
min-width: 10rem;
|
||||
max-width: 10rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.rating-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.cell-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
min-width: 6rem;
|
||||
max-width: 12rem;
|
||||
}
|
||||
|
||||
.cell-link {
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
color: #60a5fa;
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .cover-tooltip > .p-tooltip-text {
|
||||
padding: 0.25rem;
|
||||
}
|
||||
+348
@@ -0,0 +1,348 @@
|
||||
import {Component, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output} from '@angular/core';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {DatePipe, NgClass} from '@angular/common';
|
||||
import {Rating} from 'primeng/rating';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {TooltipModule} from "primeng/tooltip";
|
||||
import {Book, BookMetadata, ReadStatus} from '../../../model/book.model';
|
||||
import {SortOption} from '../../../model/sort.model';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {RouterLink} from '@angular/router';
|
||||
import {Subject} from 'rxjs';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-table',
|
||||
standalone: true,
|
||||
templateUrl: './book-table.component.html',
|
||||
imports: [
|
||||
TableModule,
|
||||
Rating,
|
||||
FormsModule,
|
||||
Button,
|
||||
TooltipModule,
|
||||
NgClass,
|
||||
RouterLink,
|
||||
TranslocoDirective
|
||||
],
|
||||
styleUrls: ['./book-table.component.scss'],
|
||||
providers: [DatePipe]
|
||||
})
|
||||
export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
||||
selectedBooks: Book[] = [];
|
||||
selectedBookIds = new Set<number>();
|
||||
|
||||
@Output() selectedBooksChange = new EventEmitter<Set<number>>();
|
||||
@Input() books: Book[] = [];
|
||||
@Input() sortOption: SortOption | null = null;
|
||||
@Input() visibleColumns: { field: string; header: string }[] = [];
|
||||
@Input() preselectedBookIds = new Set<number>();
|
||||
|
||||
protected urlHelper = inject(UrlHelperService);
|
||||
private bookService = inject(BookService);
|
||||
private bookMetadataManageService = inject(BookMetadataManageService);
|
||||
private messageService = inject(MessageService);
|
||||
private userService = inject(UserService);
|
||||
private datePipe = inject(DatePipe);
|
||||
private readStatusHelper = inject(ReadStatusHelper);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
readonly allColumns: { field: string; header: string }[] = [
|
||||
{field: 'readStatus', header: this.t.translate('book.columnPref.columns.readStatus')},
|
||||
{field: 'title', header: this.t.translate('book.columnPref.columns.title')},
|
||||
{field: 'authors', header: this.t.translate('book.columnPref.columns.authors')},
|
||||
{field: 'publisher', header: this.t.translate('book.columnPref.columns.publisher')},
|
||||
{field: 'seriesName', header: this.t.translate('book.columnPref.columns.seriesName')},
|
||||
{field: 'seriesNumber', header: this.t.translate('book.columnPref.columns.seriesNumber')},
|
||||
{field: 'categories', header: this.t.translate('book.columnPref.columns.categories')},
|
||||
{field: 'publishedDate', header: this.t.translate('book.columnPref.columns.publishedDate')},
|
||||
{field: 'lastReadTime', header: this.t.translate('book.columnPref.columns.lastReadTime')},
|
||||
{field: 'addedOn', header: this.t.translate('book.columnPref.columns.addedOn')},
|
||||
{field: 'fileName', header: this.t.translate('book.columnPref.columns.fileName')},
|
||||
{field: 'fileSizeKb', header: this.t.translate('book.columnPref.columns.fileSizeKb')},
|
||||
{field: 'language', header: this.t.translate('book.columnPref.columns.language')},
|
||||
{field: 'isbn', header: this.t.translate('book.columnPref.columns.isbn')},
|
||||
{field: 'pageCount', header: this.t.translate('book.columnPref.columns.pageCount')},
|
||||
{field: 'amazonRating', header: this.t.translate('book.columnPref.columns.amazonRating')},
|
||||
{field: 'amazonReviewCount', header: this.t.translate('book.columnPref.columns.amazonReviewCount')},
|
||||
{field: 'goodreadsRating', header: this.t.translate('book.columnPref.columns.goodreadsRating')},
|
||||
{field: 'goodreadsReviewCount', header: this.t.translate('book.columnPref.columns.goodreadsReviewCount')},
|
||||
{field: 'hardcoverRating', header: this.t.translate('book.columnPref.columns.hardcoverRating')},
|
||||
{field: 'hardcoverReviewCount', header: this.t.translate('book.columnPref.columns.hardcoverReviewCount')},
|
||||
{field: 'ranobedbRating', header: this.t.translate('book.columnPref.columns.ranobedbRating')},
|
||||
];
|
||||
|
||||
scrollHeight = 'calc(100dvh - 160px)';
|
||||
|
||||
ngOnInit(): void {
|
||||
const user = this.userService.currentUser();
|
||||
if (user) {
|
||||
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
|
||||
}
|
||||
|
||||
this.selectedBookIds = this.preselectedBookIds;
|
||||
this.selectedBooks = this.bookService.getBooksByIds([...this.selectedBookIds]);
|
||||
this.setScrollHeight();
|
||||
window.addEventListener('resize', this.setScrollHeight.bind(this));
|
||||
}
|
||||
|
||||
setScrollHeight() {
|
||||
const isMobile = window.innerWidth <= 768;
|
||||
this.scrollHeight = isMobile
|
||||
? 'calc(100dvh - 125px)'
|
||||
: 'calc(100dvh - 150px)';
|
||||
}
|
||||
|
||||
ngOnChanges() {
|
||||
const wrapperElements: HTMLCollection = document.getElementsByClassName('p-virtualscroller');
|
||||
Array.prototype.forEach.call(wrapperElements, function (wrapperElement) {
|
||||
wrapperElement.style["height"] = 'calc(100dvh - 160px)';
|
||||
});
|
||||
}
|
||||
|
||||
selectAllBooks(): void {
|
||||
this.selectedBookIds = new Set(this.books.map(book => book.id));
|
||||
this.selectedBooks = [...this.books];
|
||||
this.selectedBooksChange.emit(this.selectedBookIds);
|
||||
}
|
||||
|
||||
clearSelectedBooks(): void {
|
||||
this.selectedBookIds.clear();
|
||||
this.selectedBooks = [];
|
||||
this.selectedBooksChange.emit(this.selectedBookIds);
|
||||
}
|
||||
|
||||
onRowSelect(event: { data?: Book | Book[] }): void {
|
||||
if (event.data && !Array.isArray(event.data)) {
|
||||
this.selectedBookIds.add(event.data.id);
|
||||
this.selectedBooksChange.emit(this.selectedBookIds);
|
||||
}
|
||||
}
|
||||
|
||||
onRowUnselect(event: { data?: Book | Book[] }): void {
|
||||
if (event.data && !Array.isArray(event.data)) {
|
||||
this.selectedBookIds.delete(event.data.id);
|
||||
this.selectedBooksChange.emit(this.selectedBookIds);
|
||||
}
|
||||
}
|
||||
|
||||
onHeaderCheckboxToggle(event: { checked: boolean }): void {
|
||||
if (event.checked) {
|
||||
this.selectedBooks = [...this.books];
|
||||
this.selectedBookIds = new Set(this.books.map(book => book.id));
|
||||
} else {
|
||||
this.clearSelectedBooks();
|
||||
}
|
||||
this.selectedBooksChange.emit(this.selectedBookIds);
|
||||
}
|
||||
|
||||
getStarColor(rating: number): string {
|
||||
if (rating >= 4.5) {
|
||||
return 'rgb(34, 197, 94)';
|
||||
} else if (rating >= 4) {
|
||||
return 'rgb(52, 211, 153)';
|
||||
} else if (rating >= 3.5) {
|
||||
return 'rgb(234, 179, 8)';
|
||||
} else if (rating >= 2.5) {
|
||||
return 'rgb(249, 115, 22)';
|
||||
} else {
|
||||
return 'rgb(239, 68, 68)';
|
||||
}
|
||||
}
|
||||
|
||||
getAuthorNames(authors: string[]): string {
|
||||
return authors?.join(', ') || '';
|
||||
}
|
||||
|
||||
getGenres(genres: string[]) {
|
||||
return genres?.join(', ') || '';
|
||||
}
|
||||
|
||||
trackByBookId(index: number, book: Book): number {
|
||||
return book.id;
|
||||
}
|
||||
|
||||
isMetadataFullyLocked(metadata: BookMetadata): boolean {
|
||||
const lockedKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
|
||||
if (lockedKeys.length === 0) return false;
|
||||
return lockedKeys.every(key => metadata[key] === true);
|
||||
}
|
||||
|
||||
formatFileSize(kb?: number): string {
|
||||
if (kb == null || isNaN(kb)) return '-';
|
||||
const mb = kb / 1024;
|
||||
return mb >= 1 ? `${mb.toFixed(1)} MB` : `${mb.toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
getReadStatusIcon(readStatus: ReadStatus | undefined): string {
|
||||
return this.readStatusHelper.getReadStatusIcon(readStatus);
|
||||
}
|
||||
|
||||
getReadStatusClass(readStatus: ReadStatus | undefined): string {
|
||||
return this.readStatusHelper.getReadStatusClass(readStatus);
|
||||
}
|
||||
|
||||
getReadStatusTooltip(readStatus: ReadStatus | undefined): string {
|
||||
return this.readStatusHelper.getReadStatusTooltip(readStatus);
|
||||
}
|
||||
|
||||
shouldShowStatusIcon(readStatus: ReadStatus | undefined): boolean {
|
||||
return this.readStatusHelper.shouldShowStatusIcon(readStatus);
|
||||
}
|
||||
|
||||
getCellClickableValue(metadata: BookMetadata, book: Book, field: string) {
|
||||
const filterKeys: Record<string, string> = {
|
||||
'authors': 'author',
|
||||
'publisher': 'publisher',
|
||||
'categories': 'category',
|
||||
'language': 'language',
|
||||
'title': 'title',
|
||||
'isbn': 'isbn'
|
||||
} as const;
|
||||
|
||||
let data: string[] = [metadata[field] as string];
|
||||
|
||||
switch (field) {
|
||||
case 'title':
|
||||
return [
|
||||
{
|
||||
url: this.urlHelper.getBookUrl(book),
|
||||
anchor: metadata.title ?? book.fileName
|
||||
}
|
||||
];
|
||||
|
||||
case 'categories':
|
||||
data = metadata.categories ?? [];
|
||||
break;
|
||||
|
||||
case 'authors':
|
||||
data = metadata.authors ?? [];
|
||||
break;
|
||||
|
||||
case 'seriesName':
|
||||
return [
|
||||
{
|
||||
url: this.urlHelper.filterBooksBy('series', metadata.seriesName ?? ''),
|
||||
anchor: metadata.seriesName
|
||||
}
|
||||
]
|
||||
case 'isbn':
|
||||
return [
|
||||
{
|
||||
url: '',
|
||||
anchor: this.getCellValue(metadata, book, 'isbn')
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
return data.map(item => {
|
||||
return {
|
||||
url: this.urlHelper.filterBooksBy(filterKeys[field] ?? field, item),
|
||||
anchor: item
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getCellValue(metadata: BookMetadata, book: Book, field: string): string | number {
|
||||
switch (field) {
|
||||
case 'readStatus':
|
||||
return this.readStatusHelper.getReadStatusTooltip(book?.readStatus);
|
||||
|
||||
case 'title':
|
||||
return metadata.title ?? '';
|
||||
|
||||
case 'authors':
|
||||
return this.getAuthorNames(metadata.authors!);
|
||||
|
||||
case 'publisher':
|
||||
return metadata.publisher ?? '';
|
||||
|
||||
case 'seriesName':
|
||||
return metadata.seriesName ?? '';
|
||||
|
||||
case 'seriesNumber':
|
||||
return metadata.seriesNumber ?? '';
|
||||
|
||||
case 'categories':
|
||||
return this.getGenres(metadata.categories!);
|
||||
|
||||
case 'publishedDate':
|
||||
return metadata.publishedDate ? this.datePipe.transform(metadata.publishedDate, 'dd-MMM-yyyy') ?? '' : '';
|
||||
|
||||
case 'lastReadTime':
|
||||
return book.lastReadTime ? this.datePipe.transform(book.lastReadTime, 'dd-MMM-yyyy') ?? '' : '';
|
||||
|
||||
case 'addedOn':
|
||||
return book.addedOn ? this.datePipe.transform(book.addedOn, 'dd-MMM-yyyy') ?? '' : '';
|
||||
|
||||
case 'fileName':
|
||||
return book.primaryFile?.fileName ?? '';
|
||||
|
||||
case 'fileSizeKb':
|
||||
return this.formatFileSize(book.fileSizeKb);
|
||||
|
||||
case 'language':
|
||||
return metadata.language ?? '';
|
||||
|
||||
case 'pageCount':
|
||||
return metadata.pageCount ?? '';
|
||||
|
||||
case 'amazonRating':
|
||||
case 'goodreadsRating':
|
||||
case 'hardcoverRating':
|
||||
case 'ranobedbRating': {
|
||||
const rating = metadata[field];
|
||||
return typeof rating === 'number' ? rating.toFixed(1) : '';
|
||||
}
|
||||
|
||||
case 'amazonReviewCount':
|
||||
case 'goodreadsReviewCount':
|
||||
case 'hardcoverReviewCount':
|
||||
return metadata[field] ?? '';
|
||||
|
||||
case 'isbn':
|
||||
return metadata.isbn13 || metadata.isbn10 || '';
|
||||
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
toggleMetadataLock(metadata: BookMetadata): void {
|
||||
const lockKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
|
||||
const allLocked = lockKeys.every(key => metadata[key] === true);
|
||||
const lockAction = allLocked ? 'UNLOCK' : 'LOCK';
|
||||
|
||||
this.bookMetadataManageService.toggleAllLock(new Set([metadata.bookId]), lockAction).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedSummary') : this.t.translate('book.table.toast.metadataUnlockedSummary'),
|
||||
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedDetail') : this.t.translate('book.table.toast.metadataUnlockedDetail'),
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedSummary') : this.t.translate('book.table.toast.unlockFailedSummary'),
|
||||
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedDetail') : this.t.translate('book.table.toast.unlockFailedDetail'),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
window.removeEventListener('resize', this.setScrollHeight.bind(this));
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
import {computed, inject, Injectable, signal} from '@angular/core';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class CoverScalePreferenceService {
|
||||
|
||||
private readonly BASE_WIDTH = 135;
|
||||
private readonly BASE_HEIGHT = 220;
|
||||
private readonly TITLE_BAR_HEIGHT = 31;
|
||||
private readonly DEBOUNCE_MS = 1000;
|
||||
private readonly STORAGE_KEY = 'coverScalePreference';
|
||||
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly localStorageService = inject(LocalStorageService);
|
||||
|
||||
private readonly _scaleFactor = signal(1.0);
|
||||
readonly scaleFactor = this._scaleFactor.asReadonly();
|
||||
|
||||
readonly currentCardSize = computed(() => ({
|
||||
width: Math.round(this.BASE_WIDTH * this.scaleFactor()),
|
||||
height: Math.round(this.BASE_HEIGHT * this.scaleFactor()),
|
||||
}));
|
||||
readonly gridColumnMinWidth = computed(() => `${this.currentCardSize().width}px`);
|
||||
|
||||
private saveTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
private lastPersistedScale = 1.0;
|
||||
|
||||
constructor() {
|
||||
const initialScale = this.loadScaleFromStorage();
|
||||
this._scaleFactor.set(initialScale);
|
||||
this.lastPersistedScale = initialScale;
|
||||
}
|
||||
|
||||
setScale(scale: number): void {
|
||||
this._scaleFactor.set(scale);
|
||||
if (scale === this.lastPersistedScale) {
|
||||
return;
|
||||
}
|
||||
this.scheduleSave(scale);
|
||||
}
|
||||
|
||||
getCardHeight(_book: Book): number {
|
||||
// Use uniform height for all book types to ensure smooth virtual scrolling.
|
||||
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
|
||||
// cannot accurately estimate positions when item heights vary.
|
||||
return this.currentCardSize().height;
|
||||
}
|
||||
|
||||
private scheduleSave(scale: number): void {
|
||||
if (this.saveTimeout) {
|
||||
clearTimeout(this.saveTimeout);
|
||||
}
|
||||
|
||||
this.saveTimeout = setTimeout(() => {
|
||||
this.saveScalePreference(scale);
|
||||
}, this.DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
private saveScalePreference(scale: number): void {
|
||||
try {
|
||||
this.localStorageService.set(this.STORAGE_KEY, scale);
|
||||
this.lastPersistedScale = scale;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.coverPref.toast.savedSummary'),
|
||||
detail: this.t.translate('book.coverPref.toast.savedDetail', {scale: scale.toFixed(2)}),
|
||||
life: 1500
|
||||
});
|
||||
} catch (e) {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.coverPref.toast.saveFailedSummary'),
|
||||
detail: this.t.translate('book.coverPref.toast.saveFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private loadScaleFromStorage(): number {
|
||||
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
|
||||
if (saved !== null && !isNaN(saved)) {
|
||||
return saved;
|
||||
}
|
||||
return 1.0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingOptions10, ratingRanges} from './book-filter/book-filter.config';
|
||||
|
||||
export class FilterLabelHelper {
|
||||
private static readonly FILTER_TYPE_MAP: Record<string, string> = {
|
||||
author: 'Author',
|
||||
category: 'Genre',
|
||||
series: 'Series',
|
||||
publisher: 'Publisher',
|
||||
readStatus: 'Read Status',
|
||||
personalRating: 'Personal Rating',
|
||||
publishedDate: 'Year Published',
|
||||
matchScore: 'Metadata Match Score',
|
||||
language: 'Language',
|
||||
bookType: 'Book Type',
|
||||
shelfStatus: 'Shelf Status',
|
||||
fileSize: 'File Size',
|
||||
pageCount: 'Page Count',
|
||||
amazonRating: 'Amazon Rating',
|
||||
goodreadsRating: 'Goodreads Rating',
|
||||
hardcoverRating: 'Hardcover Rating',
|
||||
ranobedbRating: 'Ranobedb Rating',
|
||||
mood: 'Mood',
|
||||
tag: 'Tag',
|
||||
};
|
||||
|
||||
static getFilterTypeName(filterType: string): string {
|
||||
return this.FILTER_TYPE_MAP[filterType] || this.capitalize(filterType);
|
||||
}
|
||||
|
||||
static getFilterDisplayValue(filterType: string, value: string | number): string {
|
||||
const numericValue = typeof value === 'string' ? Number(value) : value;
|
||||
|
||||
switch (filterType.toLowerCase()) {
|
||||
case 'filesize': {
|
||||
const fileSizeRange = fileSizeRanges.find(r => r.id === numericValue);
|
||||
if (fileSizeRange) return fileSizeRange.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
case 'pagecount': {
|
||||
const pageCountRange = pageCountRanges.find(r => r.id === numericValue);
|
||||
if (pageCountRange) return pageCountRange.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
case 'matchscore': {
|
||||
const matchScoreRange = matchScoreRanges.find(r => r.id === numericValue);
|
||||
if (matchScoreRange) return matchScoreRange.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
case 'personalrating': {
|
||||
const personalRating = ratingOptions10.find(r => r.id === numericValue);
|
||||
if (personalRating) return personalRating.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
case 'amazonrating':
|
||||
case 'goodreadsrating':
|
||||
case 'hardcoverrating': {
|
||||
const ratingRange = ratingRanges.find(r => r.id === numericValue);
|
||||
if (ratingRange) return ratingRange.label;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
default:
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static capitalize(str: string): string {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import {Book} from '../../../model/book.model';
|
||||
|
||||
export function normalizeSearchTerm(str: string): string {
|
||||
if (!str) return '';
|
||||
// Normalize Unicode combining characters (e.g., é -> e)
|
||||
let s = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
||||
s = s.replace(/ø/gi, 'o')
|
||||
.replace(/ł/gi, 'l')
|
||||
.replace(/æ/gi, 'ae')
|
||||
.replace(/œ/gi, 'oe')
|
||||
.replace(/ß/g, 'ss');
|
||||
s = s.replace(/[!@$%^&*_=|~`<>?/";']/g, '');
|
||||
s = s.replace(/\s+/g, ' ').trim();
|
||||
return s.toLowerCase();
|
||||
}
|
||||
|
||||
export function filterBooksBySearchTerm(books: Book[], term: string): Book[] {
|
||||
const normalizedTerm = normalizeSearchTerm(term || '').trim();
|
||||
if (normalizedTerm.length < 2) {
|
||||
return books;
|
||||
}
|
||||
|
||||
return books.filter(book => {
|
||||
const title = book.metadata?.title || '';
|
||||
const series = book.metadata?.seriesName || '';
|
||||
const authors = book.metadata?.authors || [];
|
||||
const categories = book.metadata?.categories || [];
|
||||
const isbn = book.metadata?.isbn10 || '';
|
||||
const isbn13 = book.metadata?.isbn13 || '';
|
||||
const fileName = book.primaryFile?.fileName || '';
|
||||
|
||||
const matchesTitle = normalizeSearchTerm(title).includes(normalizedTerm);
|
||||
const matchesSeries = normalizeSearchTerm(series).includes(normalizedTerm);
|
||||
const matchesAuthor = authors.some(author => normalizeSearchTerm(author).includes(normalizedTerm));
|
||||
const matchesCategory = categories.some(category => normalizeSearchTerm(category).includes(normalizedTerm));
|
||||
const matchesIsbn = normalizeSearchTerm(isbn).includes(normalizedTerm) || normalizeSearchTerm(isbn13).includes(normalizedTerm);
|
||||
const matchesFileName = normalizeSearchTerm(fileName).includes(normalizedTerm);
|
||||
|
||||
return matchesTitle || matchesSeries || matchesAuthor || matchesCategory || matchesIsbn || matchesFileName;
|
||||
});
|
||||
}
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
import {effect, inject, Injectable, signal} from '@angular/core';
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class SeriesCollapseFilter {
|
||||
private static readonly PERSIST_DELAY_MS = 500;
|
||||
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
|
||||
private readonly _seriesCollapsed = signal(false);
|
||||
readonly seriesCollapsed = this._seriesCollapsed.asReadonly();
|
||||
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
|
||||
private persistTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const user = this.userService.currentUser();
|
||||
if (user) {
|
||||
this.applyPreference();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setContext(type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF' | null, id: number | null): void {
|
||||
if (type && id) {
|
||||
this.currentContext = {type, id};
|
||||
} else {
|
||||
this.currentContext = null;
|
||||
}
|
||||
this.applyPreference();
|
||||
}
|
||||
|
||||
setCollapsed(value: boolean): void {
|
||||
this._seriesCollapsed.set(value);
|
||||
this.schedulePersist(value);
|
||||
}
|
||||
|
||||
private applyPreference(): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
const prefs = user?.userSettings?.entityViewPreferences;
|
||||
|
||||
let collapsed = false;
|
||||
|
||||
if (prefs) {
|
||||
// Backward compatibility: check for old 'seriesCollapse' field
|
||||
const legacyGlobalSeriesCollapse = (prefs.global as { seriesCollapse?: boolean }).seriesCollapse;
|
||||
collapsed = prefs.global?.seriesCollapsed ?? legacyGlobalSeriesCollapse ?? false;
|
||||
|
||||
if (this.currentContext) {
|
||||
const override = prefs.overrides?.find(o =>
|
||||
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
||||
);
|
||||
if (override) {
|
||||
const legacyOverrideSeriesCollapse = (override.preferences as { seriesCollapse?: boolean }).seriesCollapse;
|
||||
if (override.preferences.seriesCollapsed !== undefined) {
|
||||
collapsed = override.preferences.seriesCollapsed;
|
||||
} else if (legacyOverrideSeriesCollapse !== undefined) {
|
||||
collapsed = legacyOverrideSeriesCollapse;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this._seriesCollapsed() !== collapsed) {
|
||||
this._seriesCollapsed.set(collapsed);
|
||||
}
|
||||
}
|
||||
|
||||
collapseBooks(books: Book[], forceExpandSeries?: boolean, isSeriesCollapsed: boolean = this.seriesCollapsed()): Book[] {
|
||||
const shouldCollapse = forceExpandSeries ? false : isSeriesCollapsed;
|
||||
if (!shouldCollapse || books.length === 0) return books;
|
||||
|
||||
const sourceBooks = [...books];
|
||||
const seriesMap = new Map<string, Book[]>();
|
||||
const collapsedBooks: Book[] = [];
|
||||
|
||||
for (const book of sourceBooks) {
|
||||
const seriesName = book.metadata?.seriesName?.trim();
|
||||
if (seriesName) {
|
||||
if (!seriesMap.has(seriesName)) {
|
||||
seriesMap.set(seriesName, []);
|
||||
}
|
||||
seriesMap.get(seriesName)!.push(book);
|
||||
} else {
|
||||
collapsedBooks.push(book);
|
||||
}
|
||||
}
|
||||
|
||||
for (const group of seriesMap.values()) {
|
||||
const sortedGroup = group.slice().sort((a, b) => {
|
||||
const aNum = a.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
||||
const bNum = b.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
||||
return aNum - bNum;
|
||||
});
|
||||
const firstBook = sortedGroup[0];
|
||||
collapsedBooks.push({
|
||||
...firstBook,
|
||||
seriesBooks: group,
|
||||
seriesCount: group.length
|
||||
});
|
||||
}
|
||||
|
||||
return collapsedBooks;
|
||||
}
|
||||
|
||||
private schedulePersist(isCollapsed: boolean): void {
|
||||
if (this.persistTimeout) {
|
||||
clearTimeout(this.persistTimeout);
|
||||
}
|
||||
|
||||
this.persistTimeout = setTimeout(() => {
|
||||
this.persistCollapsePreference(isCollapsed);
|
||||
}, SeriesCollapseFilter.PERSIST_DELAY_MS);
|
||||
}
|
||||
|
||||
private persistCollapsePreference(isCollapsed: boolean): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
if (!user) return;
|
||||
|
||||
const prefs = structuredClone(user.userSettings.entityViewPreferences ?? {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'DESC',
|
||||
view: 'GRID',
|
||||
coverSize: 1.0,
|
||||
seriesCollapsed: false
|
||||
},
|
||||
overrides: []
|
||||
});
|
||||
|
||||
if (!prefs.overrides) {
|
||||
prefs.overrides = [];
|
||||
}
|
||||
|
||||
if (this.currentContext) {
|
||||
let override = prefs.overrides.find(o =>
|
||||
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
||||
);
|
||||
|
||||
if (!override) {
|
||||
override = {
|
||||
entityType: this.currentContext.type,
|
||||
entityId: this.currentContext.id,
|
||||
preferences: {
|
||||
...prefs.global,
|
||||
seriesCollapsed: isCollapsed
|
||||
}
|
||||
};
|
||||
prefs.overrides.push(override);
|
||||
} else {
|
||||
override.preferences.seriesCollapsed = isCollapsed;
|
||||
}
|
||||
} else {
|
||||
prefs.global.seriesCollapsed = isCollapsed;
|
||||
}
|
||||
|
||||
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Preference Saved',
|
||||
detail: `Series collapse set to ${isCollapsed ? 'enabled' : 'disabled'}${this.currentContext ? ' for this view' : ' globally'}.`,
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import {inject, Injectable, signal} from '@angular/core';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class SidebarFilterTogglePrefService {
|
||||
|
||||
private readonly STORAGE_KEY = 'showSidebarFilter';
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly localStorageService = inject(LocalStorageService);
|
||||
|
||||
private readonly _showFilter = signal(true);
|
||||
readonly showFilter = this._showFilter.asReadonly();
|
||||
|
||||
constructor() {
|
||||
const isNarrow = window.innerWidth <= 768;
|
||||
this._showFilter.set(!isNarrow);
|
||||
this.loadFromStorage();
|
||||
}
|
||||
|
||||
toggle(): void {
|
||||
this.setShowFilter(!this.showFilter());
|
||||
}
|
||||
|
||||
setShowFilter(value: boolean): void {
|
||||
if (this._showFilter() !== value) {
|
||||
this._showFilter.set(value);
|
||||
this.savePreference(value);
|
||||
}
|
||||
}
|
||||
|
||||
private savePreference(value: boolean): void {
|
||||
try {
|
||||
this.localStorageService.set(this.STORAGE_KEY, value);
|
||||
} catch (e) {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.filterPref.toast.saveFailedSummary'),
|
||||
detail: this.t.translate('book.filterPref.toast.saveFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private loadFromStorage(): void {
|
||||
const isNarrow = window.innerWidth <= 768;
|
||||
if (isNarrow) {
|
||||
this._showFilter.set(false);
|
||||
} else {
|
||||
const saved = this.localStorageService.get<boolean>(this.STORAGE_KEY);
|
||||
this._showFilter.set(saved !== null ? saved : true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.config';
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {BookFilterMode} from '../../../../settings/user-management/user.service';
|
||||
|
||||
export function isRatingInRange(rating: number | undefined | null, rangeId: string | number): boolean {
|
||||
if (rating == null) return false;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
const range = ratingRanges.find(r => r.id === numericId);
|
||||
if (!range) return false;
|
||||
return rating >= range.min && rating < range.max;
|
||||
}
|
||||
|
||||
export function isRatingInRange10(rating: number | undefined | null, rangeId: string | number): boolean {
|
||||
if (rating == null) return false;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
return Math.round(rating) === numericId;
|
||||
}
|
||||
|
||||
export function isFileSizeInRange(fileSizeKb: number | undefined, rangeId: string | number): boolean {
|
||||
if (fileSizeKb == null) return false;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
const range = fileSizeRanges.find(r => r.id === numericId);
|
||||
if (!range) return false;
|
||||
return fileSizeKb >= range.min && fileSizeKb < range.max;
|
||||
}
|
||||
|
||||
export function isPageCountInRange(pageCount: number | undefined, rangeId: string | number): boolean {
|
||||
if (pageCount == null) return false;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
const range = pageCountRanges.find(r => r.id === numericId);
|
||||
if (!range) return false;
|
||||
return pageCount >= range.min && pageCount < range.max;
|
||||
}
|
||||
|
||||
export function isMatchScoreInRange(score: number | undefined | null, rangeId: string | number): boolean {
|
||||
if (score == null) return false;
|
||||
const normalizedScore = score > 1 ? score / 100 : score;
|
||||
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
|
||||
const range = matchScoreRanges.find(r => r.id === numericId);
|
||||
if (!range) return false;
|
||||
return normalizedScore >= range.min && normalizedScore < range.max;
|
||||
}
|
||||
|
||||
export function doesBookMatchReadStatus(book: Book, selected: unknown[]): boolean {
|
||||
const status = book.readStatus ?? ReadStatus.UNSET;
|
||||
return selected.includes(status);
|
||||
}
|
||||
|
||||
export function doesBookMatchFilter(
|
||||
book: Book,
|
||||
filterType: string,
|
||||
filterValues: unknown[],
|
||||
mode: BookFilterMode
|
||||
): boolean {
|
||||
if (!Array.isArray(filterValues) || filterValues.length === 0) {
|
||||
return mode === 'or';
|
||||
}
|
||||
|
||||
const effectiveMode = mode === 'not' ? 'or' : mode;
|
||||
|
||||
switch (filterType) {
|
||||
case 'author':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.authors?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.authors?.includes(val as string));
|
||||
case 'category':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.categories?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.categories?.includes(val as string));
|
||||
case 'series':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.seriesName?.trim() === val)
|
||||
: filterValues.every(val => book.metadata?.seriesName?.trim() === val);
|
||||
case 'bookType':
|
||||
return book.isPhysical ? filterValues.includes('PHYSICAL') : filterValues.includes(book.primaryFile?.bookType);
|
||||
case 'readStatus':
|
||||
return doesBookMatchReadStatus(book, filterValues);
|
||||
case 'personalRating':
|
||||
return filterValues.some(range => isRatingInRange10(book.personalRating, range as string | number));
|
||||
case 'publisher':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.publisher === val)
|
||||
: filterValues.every(val => book.metadata?.publisher === val);
|
||||
case 'matchScore':
|
||||
return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range as string | number));
|
||||
case 'library':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => val == book.libraryId)
|
||||
: filterValues.every(val => val == book.libraryId);
|
||||
case 'shelf':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.shelves?.some(s => s.id == val))
|
||||
: filterValues.every(val => book.shelves?.some(s => s.id == val));
|
||||
case 'shelfStatus': {
|
||||
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
|
||||
return filterValues.includes(shelved);
|
||||
}
|
||||
case 'tag':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.tags?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.tags?.includes(val as string));
|
||||
case 'publishedDate': {
|
||||
const bookYear = book.metadata?.publishedDate
|
||||
? new Date(book.metadata.publishedDate).getFullYear()
|
||||
: null;
|
||||
return bookYear ? filterValues.some(val => val == bookYear || val == bookYear.toString()) : false;
|
||||
}
|
||||
case 'fileSize':
|
||||
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range as string | number));
|
||||
case 'amazonRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.amazonRating, range as string | number));
|
||||
case 'goodreadsRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.goodreadsRating, range as string | number));
|
||||
case 'hardcoverRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.hardcoverRating, range as string | number));
|
||||
case 'language':
|
||||
return filterValues.includes(book.metadata?.language);
|
||||
case 'pageCount':
|
||||
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount ?? undefined, range as string | number));
|
||||
case 'mood':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.moods?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.moods?.includes(val as string));
|
||||
case 'ageRating':
|
||||
return filterValues.some(val => {
|
||||
const numVal = typeof val === 'string' ? Number(val) : val;
|
||||
return book.metadata?.ageRating === numVal;
|
||||
});
|
||||
case 'contentRating':
|
||||
return filterValues.includes(book.metadata?.contentRating);
|
||||
case 'narrator':
|
||||
return filterValues.includes(book.metadata?.narrator);
|
||||
case 'comicCharacter':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.comicMetadata?.characters?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.comicMetadata?.characters?.includes(val as string));
|
||||
case 'comicTeam':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.comicMetadata?.teams?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.comicMetadata?.teams?.includes(val as string));
|
||||
case 'comicLocation':
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => book.metadata?.comicMetadata?.locations?.includes(val as string))
|
||||
: filterValues.every(val => book.metadata?.comicMetadata?.locations?.includes(val as string));
|
||||
case 'comicCreator': {
|
||||
const comic = book.metadata?.comicMetadata;
|
||||
if (!comic) return false;
|
||||
const allCreators: string[] = [];
|
||||
const roles: [string[] | undefined, string][] = [
|
||||
[comic.pencillers, 'penciller'],
|
||||
[comic.inkers, 'inker'],
|
||||
[comic.colorists, 'colorist'],
|
||||
[comic.letterers, 'letterer'],
|
||||
[comic.coverArtists, 'coverArtist'],
|
||||
[comic.editors, 'editor']
|
||||
];
|
||||
for (const [names, role] of roles) {
|
||||
if (names) {
|
||||
for (const name of names) {
|
||||
allCreators.push(`${name}:${role}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return effectiveMode === 'or'
|
||||
? filterValues.some(val => allCreators.includes(val as string))
|
||||
: filterValues.every(val => allCreators.includes(val as string));
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function filterBooksByFilters(
|
||||
books: Book[],
|
||||
activeFilters: Record<string, unknown[]> | null,
|
||||
mode: BookFilterMode,
|
||||
excludeFilterType?: string
|
||||
): Book[] {
|
||||
if (!activeFilters) return books;
|
||||
|
||||
const filterEntries = Object.entries(activeFilters)
|
||||
.filter(([type]) => type !== excludeFilterType);
|
||||
|
||||
if (filterEntries.length === 0) return books;
|
||||
|
||||
return books.filter(book => {
|
||||
const matches = filterEntries.map(([filterType, filterValues]) =>
|
||||
doesBookMatchFilter(book, filterType, filterValues, mode)
|
||||
);
|
||||
if (mode === 'not') return matches.every(m => !m);
|
||||
return mode === 'or' ? matches.some(m => m) : matches.every(m => m);
|
||||
});
|
||||
}
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.lockUnlockDialog'">
|
||||
<div class="lock-unlock-container">
|
||||
<div class="panel-header">
|
||||
<div class="header-icon-wrapper">
|
||||
<i class="pi pi-lock header-icon"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h2 class="panel-title">{{ t('title') }}</h2>
|
||||
<p class="panel-description">{{ t('selectedCount', { count: bookIds.size }) }}</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(click)="dialogRef.close()"
|
||||
class="close-button">
|
||||
</p-button>
|
||||
</div>
|
||||
|
||||
<div class="dialog-content">
|
||||
<div class="fields-grid">
|
||||
@for (field of lockableFields; track field) {
|
||||
<div class="field-row">
|
||||
<label class="field-label">{{ fieldLabels[field] || field }}</label>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
[label]="getLockLabel(field)"
|
||||
[icon]="getLockIcon(field)"
|
||||
[severity]="fieldLocks[field] === true ? 'danger' : fieldLocks[field] === false ? 'success' : 'secondary'"
|
||||
(click)="cycleLockState(field)"
|
||||
></p-button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dialog-footer">
|
||||
<div class="footer-actions">
|
||||
<p-button icon="pi pi-refresh" [label]="t('reset')" outlined="true" severity="warn" (onClick)="resetFieldLocks()"></p-button>
|
||||
</div>
|
||||
<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-open" [label]="t('unlockAll')" outlined="true" severity="success" (onClick)="toggleLockAll('UNLOCK')"></p-button>
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
@use '../../../../../shared/styles/panel-shared' as panel;
|
||||
|
||||
.lock-unlock-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
@include panel.panel-header;
|
||||
}
|
||||
|
||||
.dialog-content {
|
||||
padding: 1.5rem;
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-top: none;
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.dialog-footer {
|
||||
@include panel.dialog-footer;
|
||||
}
|
||||
|
||||
.footer-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.fields-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(1, minmax(0, 1fr));
|
||||
column-gap: 6rem;
|
||||
row-gap: 1rem;
|
||||
|
||||
@media (min-width: 576px) {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
.field-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
text-transform: capitalize;
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {LoadingService} from '../../../../../core/services/loading.service';
|
||||
import {finalize} from 'rxjs';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
selector: 'app-lock-unlock-metadata-dialog',
|
||||
standalone: true,
|
||||
imports: [
|
||||
Button,
|
||||
FormsModule,
|
||||
Divider,
|
||||
TranslocoDirective
|
||||
],
|
||||
templateUrl: './lock-unlock-metadata-dialog.component.html',
|
||||
styleUrl: './lock-unlock-metadata-dialog.component.scss'
|
||||
})
|
||||
export class LockUnlockMetadataDialogComponent implements OnInit {
|
||||
private bookMetadataManageService = inject(BookMetadataManageService);
|
||||
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||
dialogRef = inject(DynamicDialogRef);
|
||||
private messageService = inject(MessageService);
|
||||
private loadingService = inject(LoadingService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
fieldLocks: Record<string, boolean | undefined> = {};
|
||||
|
||||
bookIds: Set<number> = this.dynamicDialogConfig.data.bookIds;
|
||||
|
||||
lockableFields: string[] = [
|
||||
'titleLocked', 'subtitleLocked', 'publisherLocked', 'publishedDateLocked', 'descriptionLocked',
|
||||
'isbn13Locked', 'isbn10Locked', 'asinLocked', 'pageCountLocked', 'thumbnailLocked', 'languageLocked', 'coverLocked',
|
||||
'seriesNameLocked', 'seriesNumberLocked', 'seriesTotalLocked', 'authorsLocked', 'categoriesLocked', 'moodsLocked', 'tagsLocked',
|
||||
'amazonRatingLocked', 'amazonReviewCountLocked', 'goodreadsRatingLocked', 'goodreadsReviewCountLocked',
|
||||
'hardcoverRatingLocked', 'hardcoverReviewCountLocked', 'goodreadsIdLocked', 'hardcoverIdLocked', 'hardcoverBookIdLocked', 'googleIdLocked', 'comicvineIdLocked',
|
||||
'ranobedbIdLocked', 'ranobedbRatingLocked'
|
||||
];
|
||||
|
||||
fieldLabels: Record<string, string> = {
|
||||
titleLocked: 'Title',
|
||||
subtitleLocked: 'Subtitle',
|
||||
publisherLocked: 'Publisher',
|
||||
publishedDateLocked: 'Date',
|
||||
descriptionLocked: 'Description',
|
||||
isbn13Locked: 'ISBN-13',
|
||||
isbn10Locked: 'ISBN-10',
|
||||
asinLocked: 'ASIN',
|
||||
pageCountLocked: 'Page Count',
|
||||
thumbnailLocked: 'Thumbnail',
|
||||
languageLocked: 'Language',
|
||||
coverLocked: 'Cover',
|
||||
seriesNameLocked: 'Series',
|
||||
seriesNumberLocked: 'Series #',
|
||||
seriesTotalLocked: 'Series Total #',
|
||||
authorsLocked: 'Authors',
|
||||
categoriesLocked: 'Genres',
|
||||
moodsLocked: 'Moods',
|
||||
tagsLocked: 'Tags',
|
||||
amazonRatingLocked: 'Amazon ★',
|
||||
amazonReviewCountLocked: 'Amazon Reviews',
|
||||
goodreadsRatingLocked: 'Goodreads ★',
|
||||
goodreadsReviewCountLocked: 'Goodreads Reviews',
|
||||
hardcoverRatingLocked: 'Hardcover ★',
|
||||
hardcoverReviewCountLocked: 'Hardcover Reviews',
|
||||
goodreadsIdLocked: 'Goodreads ID',
|
||||
hardcoverIdLocked: 'Hardcover ID',
|
||||
hardcoverBookIdLocked: 'Hardcover Book ID',
|
||||
googleIdLocked: 'Google ID',
|
||||
comicvineIdLocked: 'Comicvine ID',
|
||||
ranobedbIdLocked: 'Ranobedb ID',
|
||||
ranobedbRatingLocked: 'Ranobedb ★',
|
||||
};
|
||||
|
||||
isSaving = false;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.lockableFields.forEach(field => this.fieldLocks[field] = undefined);
|
||||
}
|
||||
|
||||
toggleLockAll(action: 'LOCK' | 'UNLOCK'): void {
|
||||
const lockState = action === 'LOCK' ? true : false;
|
||||
this.lockableFields.forEach(field => {
|
||||
this.fieldLocks[field] = lockState;
|
||||
});
|
||||
}
|
||||
|
||||
getLockLabel(field: string): string {
|
||||
const state = this.fieldLocks[field];
|
||||
if (state === undefined) return this.t.translate('book.lockUnlockDialog.unselected');
|
||||
return state ? this.t.translate('book.lockUnlockDialog.locked') : this.t.translate('book.lockUnlockDialog.unlocked');
|
||||
}
|
||||
|
||||
getLockIcon(field: string): string {
|
||||
const state = this.fieldLocks[field];
|
||||
return state === undefined ? '' : state ? 'pi pi-lock' : 'pi pi-lock-open';
|
||||
}
|
||||
|
||||
resetFieldLocks(): void {
|
||||
this.lockableFields.forEach(field => {
|
||||
this.fieldLocks[field] = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
cycleLockState(field: string): void {
|
||||
const current = this.fieldLocks[field];
|
||||
if (current === undefined) {
|
||||
this.fieldLocks[field] = true;
|
||||
} else if (current) {
|
||||
this.fieldLocks[field] = false;
|
||||
} else {
|
||||
this.fieldLocks[field] = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
applyFieldLocks(): void {
|
||||
const fieldActions: Record<string, 'LOCK' | 'UNLOCK'> = {};
|
||||
for (const [field, locked] of Object.entries(this.fieldLocks)) {
|
||||
if (locked !== undefined) {
|
||||
fieldActions[field] = locked ? 'LOCK' : 'UNLOCK';
|
||||
}
|
||||
}
|
||||
|
||||
this.isSaving = true;
|
||||
const loader = this.loadingService.show(this.t.translate('book.lockUnlockDialog.toast.updatingFieldLocks'));
|
||||
|
||||
this.bookMetadataManageService.toggleFieldLocks(this.bookIds, fieldActions)
|
||||
.pipe(finalize(() => {
|
||||
this.isSaving = false;
|
||||
this.loadingService.hide(loader);
|
||||
}))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.lockUnlockDialog.toast.updatedSummary'),
|
||||
detail: this.t.translate('book.lockUnlockDialog.toast.updatedDetail')
|
||||
});
|
||||
this.dialogRef.close('fields-updated');
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.lockUnlockDialog.toast.failedSummary'),
|
||||
detail: this.t.translate('book.lockUnlockDialog.toast.failedDetail')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import {SortDirection, SortOption} from '../../../model/sort.model';
|
||||
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
export const SORT_OPTION_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
title: 'book.sorting.options.title',
|
||||
fileName: 'book.sorting.options.fileName',
|
||||
filePath: 'book.sorting.options.filePath',
|
||||
author: 'book.sorting.options.author',
|
||||
authorSurnameVorname: 'book.sorting.options.authorSurnameVorname',
|
||||
seriesName: 'book.sorting.options.seriesName',
|
||||
seriesNumber: 'book.sorting.options.seriesNumber',
|
||||
lastReadTime: 'book.sorting.options.lastReadTime',
|
||||
personalRating: 'book.sorting.options.personalRating',
|
||||
addedOn: 'book.sorting.options.addedOn',
|
||||
fileSizeKb: 'book.sorting.options.fileSizeKb',
|
||||
locked: 'book.sorting.options.locked',
|
||||
publisher: 'book.sorting.options.publisher',
|
||||
publishedDate: 'book.sorting.options.publishedDate',
|
||||
readStatus: 'book.sorting.options.readStatus',
|
||||
dateFinished: 'book.sorting.options.dateFinished',
|
||||
readingProgress: 'book.sorting.options.readingProgress',
|
||||
bookType: 'book.sorting.options.bookType',
|
||||
amazonRating: 'book.sorting.options.amazonRating',
|
||||
amazonReviewCount: 'book.sorting.options.amazonReviewCount',
|
||||
goodreadsRating: 'book.sorting.options.goodreadsRating',
|
||||
goodreadsReviewCount: 'book.sorting.options.goodreadsReviewCount',
|
||||
hardcoverRating: 'book.sorting.options.hardcoverRating',
|
||||
hardcoverReviewCount: 'book.sorting.options.hardcoverReviewCount',
|
||||
ranobedbRating: 'book.sorting.options.ranobedbRating',
|
||||
narrator: 'book.sorting.options.narrator',
|
||||
pageCount: 'book.sorting.options.pageCount',
|
||||
random: 'book.sorting.options.random'
|
||||
};
|
||||
|
||||
const SORT_FIELDS: { field: string; defaultLabel: string }[] = [
|
||||
{field: 'title', defaultLabel: 'Title'},
|
||||
{field: 'fileName', defaultLabel: 'File Name'},
|
||||
{field: 'filePath', defaultLabel: 'File Path'},
|
||||
{field: 'author', defaultLabel: 'Author'},
|
||||
{field: 'authorSurnameVorname', defaultLabel: 'Author (Surname)'},
|
||||
{field: 'seriesName', defaultLabel: 'Series Name'},
|
||||
{field: 'seriesNumber', defaultLabel: 'Series Number'},
|
||||
{field: 'lastReadTime', defaultLabel: 'Last Read'},
|
||||
{field: 'personalRating', defaultLabel: 'Personal Rating'},
|
||||
{field: 'addedOn', defaultLabel: 'Added On'},
|
||||
{field: 'fileSizeKb', defaultLabel: 'File Size'},
|
||||
{field: 'locked', defaultLabel: 'Locked'},
|
||||
{field: 'publisher', defaultLabel: 'Publisher'},
|
||||
{field: 'publishedDate', defaultLabel: 'Published Date'},
|
||||
{field: 'readStatus', defaultLabel: 'Read Status'},
|
||||
{field: 'dateFinished', defaultLabel: 'Date Finished'},
|
||||
{field: 'readingProgress', defaultLabel: 'Reading Progress'},
|
||||
{field: 'bookType', defaultLabel: 'Book Type'},
|
||||
{field: 'amazonRating', defaultLabel: 'Amazon Rating'},
|
||||
{field: 'amazonReviewCount', defaultLabel: 'Amazon #'},
|
||||
{field: 'goodreadsRating', defaultLabel: 'Goodreads Rating'},
|
||||
{field: 'goodreadsReviewCount', defaultLabel: 'Goodreads #'},
|
||||
{field: 'hardcoverRating', defaultLabel: 'Hardcover Rating'},
|
||||
{field: 'hardcoverReviewCount', defaultLabel: 'Hardcover #'},
|
||||
{field: 'ranobedbRating', defaultLabel: 'Ranobedb Rating'},
|
||||
{field: 'narrator', defaultLabel: 'Narrator'},
|
||||
{field: 'pageCount', defaultLabel: 'Pages'},
|
||||
{field: 'random', defaultLabel: 'Random'},
|
||||
];
|
||||
|
||||
export class BookSorter {
|
||||
selectedSortCriteria: SortOption[] = [];
|
||||
|
||||
sortOptions: SortOption[];
|
||||
|
||||
constructor(private onSortChange: (criteria: SortOption[]) => void, translocoService?: TranslocoService) {
|
||||
this.sortOptions = SORT_FIELDS.map(({field, defaultLabel}) => {
|
||||
const key = SORT_OPTION_LABEL_KEYS[field];
|
||||
const label = key && translocoService ? translocoService.translate(key) : defaultLabel;
|
||||
return {label, field, direction: SortDirection.ASCENDING};
|
||||
});
|
||||
}
|
||||
|
||||
// For backward compatibility - get first sort option
|
||||
get selectedSort(): SortOption | undefined {
|
||||
return this.selectedSortCriteria[0];
|
||||
}
|
||||
|
||||
// For backward compatibility - set from single sort option
|
||||
set selectedSort(sort: SortOption | undefined) {
|
||||
if (sort) {
|
||||
this.selectedSortCriteria = [sort];
|
||||
} else {
|
||||
this.selectedSortCriteria = [];
|
||||
}
|
||||
}
|
||||
|
||||
setSortCriteria(criteria: SortOption[]): void {
|
||||
this.selectedSortCriteria = [...criteria];
|
||||
this.updateSortOptions();
|
||||
}
|
||||
|
||||
// Quick sort by field - toggles direction if already selected as primary sort
|
||||
sortBooks(field: string): void {
|
||||
const existingSort = this.sortOptions.find(opt => opt.field === field);
|
||||
if (!existingSort) return;
|
||||
|
||||
// If this field is the first (primary) sort, toggle its direction
|
||||
if (this.selectedSortCriteria.length > 0 && this.selectedSortCriteria[0].field === field) {
|
||||
this.selectedSortCriteria[0] = {
|
||||
...this.selectedSortCriteria[0],
|
||||
direction: this.selectedSortCriteria[0].direction === SortDirection.ASCENDING
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING
|
||||
};
|
||||
} else {
|
||||
// Set as the only sort criterion (single click behavior)
|
||||
this.selectedSortCriteria = [{
|
||||
label: existingSort.label,
|
||||
field: existingSort.field,
|
||||
direction: SortDirection.ASCENDING
|
||||
}];
|
||||
}
|
||||
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
addSortCriterion(field: string): void {
|
||||
// Don't add if already exists
|
||||
if (this.selectedSortCriteria.some(c => c.field === field)) return;
|
||||
|
||||
const option = this.sortOptions.find(opt => opt.field === field);
|
||||
if (!option) return;
|
||||
|
||||
this.selectedSortCriteria.push({
|
||||
label: option.label,
|
||||
field: option.field,
|
||||
direction: SortDirection.ASCENDING
|
||||
});
|
||||
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
removeSortCriterion(index: number): void {
|
||||
if (index < 0 || index >= this.selectedSortCriteria.length) return;
|
||||
|
||||
this.selectedSortCriteria.splice(index, 1);
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
toggleCriterionDirection(index: number): void {
|
||||
if (index < 0 || index >= this.selectedSortCriteria.length) return;
|
||||
|
||||
const criterion = this.selectedSortCriteria[index];
|
||||
this.selectedSortCriteria[index] = {
|
||||
...criterion,
|
||||
direction: criterion.direction === SortDirection.ASCENDING
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING
|
||||
};
|
||||
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
reorderCriteria(event: CdkDragDrop<SortOption[]>): void {
|
||||
moveItemInArray(this.selectedSortCriteria, event.previousIndex, event.currentIndex);
|
||||
this.updateSortOptions();
|
||||
this.onSortChange(this.selectedSortCriteria);
|
||||
}
|
||||
|
||||
getAvailableSortOptions(): SortOption[] {
|
||||
const usedFields = new Set(this.selectedSortCriteria.map(c => c.field));
|
||||
return this.sortOptions.filter(opt => !usedFields.has(opt.field));
|
||||
}
|
||||
|
||||
updateSortOptions(): void {
|
||||
const primaryField = this.selectedSortCriteria[0]?.field;
|
||||
const primaryDirection = this.selectedSortCriteria[0]?.direction;
|
||||
|
||||
const directionIcon = primaryDirection === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
|
||||
|
||||
this.sortOptions = this.sortOptions.map((option) => ({
|
||||
...option,
|
||||
icon: option.field === primaryField ? directionIcon : '',
|
||||
}));
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
<ng-container *transloco="let t; prefix: 'book.sorting'">
|
||||
<div class="multi-sort-container">
|
||||
<div class="multi-sort-header">
|
||||
<span class="header-title">{{ t('sortOrder') }}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="sort-criteria-list"
|
||||
cdkDropList
|
||||
[cdkDropListData]="sortCriteria"
|
||||
(cdkDropListDropped)="onDrop($event)">
|
||||
@for (criterion of sortCriteria; track criterion.field; let i = $index) {
|
||||
<div class="sort-criterion" cdkDrag>
|
||||
<div class="criterion-drag-handle" cdkDragHandle>
|
||||
<i class="pi pi-bars"></i>
|
||||
</div>
|
||||
<span class="criterion-rank">{{ i + 1 }}.</span>
|
||||
<span class="criterion-label">{{ criterion.label }}</span>
|
||||
<div class="criterion-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="direction-btn"
|
||||
(click)="onToggleDirection(i)"
|
||||
[pTooltip]="getDirectionTooltip(criterion.direction)"
|
||||
tooltipPosition="top">
|
||||
<i [class]="getDirectionIcon(criterion.direction)"></i>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="remove-btn"
|
||||
(click)="onRemove(i)"
|
||||
[pTooltip]="t('removeTooltip')"
|
||||
tooltipPosition="top"
|
||||
[disabled]="sortCriteria.length === 1">
|
||||
<i class="pi pi-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (unusedOptions.length > 0) {
|
||||
<div class="add-sort-section">
|
||||
<p-select
|
||||
[options]="unusedOptions"
|
||||
[(ngModel)]="selectedField"
|
||||
optionLabel="label"
|
||||
optionValue="field"
|
||||
[placeholder]="t('addSortFieldPlaceholder')"
|
||||
[style]="{ width: '100%' }"
|
||||
size="small"
|
||||
appendTo="body"
|
||||
(onChange)="onAddField()">
|
||||
</p-select>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (showSaveButton) {
|
||||
<div class="save-sort-section">
|
||||
<p-button
|
||||
icon="pi pi-save"
|
||||
[label]="t('saveAsDefault')"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[style]="{ width: '100%' }"
|
||||
(onClick)="onSave()">
|
||||
</p-button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
.multi-sort-container {
|
||||
width: 280px;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.multi-sort-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-bottom: 0.75rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.header-title {
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.sort-criteria-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.sort-criterion {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem;
|
||||
background-color: var(--overlay-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
cursor: move;
|
||||
transition: background-color 0.15s ease, box-shadow 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--ground-background);
|
||||
}
|
||||
}
|
||||
|
||||
.cdk-drag-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem;
|
||||
background-color: var(--card-background);
|
||||
border: 1px solid var(--primary-color);
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.cdk-drag-placeholder {
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.cdk-drag-animating {
|
||||
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.sort-criteria-list.cdk-drop-list-dragging .sort-criterion:not(.cdk-drag-placeholder) {
|
||||
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.criterion-drag-handle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-secondary-color);
|
||||
cursor: grab;
|
||||
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
.criterion-rank {
|
||||
font-weight: 600;
|
||||
color: var(--primary-color);
|
||||
min-width: 1.25rem;
|
||||
}
|
||||
|
||||
.criterion-label {
|
||||
flex: 1;
|
||||
font-size: 0.875rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.criterion-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.direction-btn,
|
||||
.remove-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background-color: transparent;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.15s ease;
|
||||
|
||||
i {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background-color: var(--ground-background);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.direction-btn {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.remove-btn {
|
||||
color: var(--p-red-500);
|
||||
}
|
||||
|
||||
.add-sort-section {
|
||||
margin-top: 0.75rem;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.save-sort-section {
|
||||
margin-top: 0.75rem;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
import {ChangeDetectionStrategy, Component, EventEmitter, inject, Input, Output} from '@angular/core';
|
||||
import {SortDirection, SortOption} from '../../../../model/sort.model';
|
||||
import {CdkDrag, CdkDragDrop, CdkDragHandle, CdkDropList, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||
import {Select} from 'primeng/select';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {Button} from 'primeng/button';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
selector: 'app-multi-sort-popover',
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [
|
||||
CdkDropList,
|
||||
CdkDrag,
|
||||
CdkDragHandle,
|
||||
Select,
|
||||
FormsModule,
|
||||
Tooltip,
|
||||
Button,
|
||||
TranslocoDirective
|
||||
],
|
||||
templateUrl: './multi-sort-popover.component.html',
|
||||
styleUrl: './multi-sort-popover.component.scss'
|
||||
})
|
||||
export class MultiSortPopoverComponent {
|
||||
private readonly t = inject(TranslocoService);
|
||||
@Input() sortCriteria: SortOption[] = [];
|
||||
@Input() availableSortOptions: SortOption[] = [];
|
||||
@Input() showSaveButton = false;
|
||||
|
||||
@Output() criteriaChange = new EventEmitter<SortOption[]>();
|
||||
@Output() saveSortConfig = new EventEmitter<SortOption[]>();
|
||||
|
||||
selectedField: string | null = null;
|
||||
|
||||
get unusedOptions(): SortOption[] {
|
||||
const usedFields = new Set(this.sortCriteria.map(c => c.field));
|
||||
return this.availableSortOptions.filter(opt => !usedFields.has(opt.field));
|
||||
}
|
||||
|
||||
onDrop(event: CdkDragDrop<SortOption[]>): void {
|
||||
const criteria = [...this.sortCriteria];
|
||||
moveItemInArray(criteria, event.previousIndex, event.currentIndex);
|
||||
this.sortCriteria = criteria;
|
||||
this.criteriaChange.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
onToggleDirection(index: number): void {
|
||||
this.sortCriteria = this.sortCriteria.map((c, i) =>
|
||||
i === index
|
||||
? {...c, direction: c.direction === SortDirection.ASCENDING ? SortDirection.DESCENDING : SortDirection.ASCENDING}
|
||||
: c
|
||||
);
|
||||
this.criteriaChange.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
onRemove(index: number): void {
|
||||
this.sortCriteria = this.sortCriteria.filter((_, i) => i !== index);
|
||||
this.criteriaChange.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
onAddField(): void {
|
||||
if (!this.selectedField) return;
|
||||
const option = this.availableSortOptions.find(o => o.field === this.selectedField);
|
||||
if (!option) return;
|
||||
this.sortCriteria = [...this.sortCriteria, {
|
||||
label: option.label,
|
||||
field: option.field,
|
||||
direction: SortDirection.ASCENDING
|
||||
}];
|
||||
this.selectedField = null;
|
||||
this.criteriaChange.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
onSave(): void {
|
||||
this.saveSortConfig.emit(this.sortCriteria);
|
||||
}
|
||||
|
||||
getDirectionIcon(direction: SortDirection): string {
|
||||
return direction === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
|
||||
}
|
||||
|
||||
getDirectionTooltip(direction: SortDirection): string {
|
||||
return direction === SortDirection.ASCENDING
|
||||
? this.t.translate('book.sorting.ascendingTooltip')
|
||||
: this.t.translate('book.sorting.descendingTooltip');
|
||||
}
|
||||
|
||||
protected readonly SortDirection = SortDirection;
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
import {inject, Injectable, signal} from '@angular/core';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class TableColumnPreferenceService {
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
private readonly _preferences = signal<TableColumnPreference[]>([]);
|
||||
readonly preferences = this._preferences.asReadonly();
|
||||
|
||||
private readonly allAvailableFields = [
|
||||
'readStatus', 'title', 'authors', 'publisher', 'seriesName', 'seriesNumber',
|
||||
'categories', 'publishedDate', 'lastReadTime', 'addedOn', 'fileName', 'fileSizeKb',
|
||||
'language', 'isbn', 'pageCount', 'amazonRating', 'amazonReviewCount',
|
||||
'goodreadsRating', 'goodreadsReviewCount', 'hardcoverRating', 'hardcoverReviewCount',
|
||||
'ranobedbRating',
|
||||
];
|
||||
|
||||
private readonly fallbackPreferences: TableColumnPreference[] = this.allAvailableFields.map((field, index) => ({
|
||||
field,
|
||||
visible: true,
|
||||
order: index
|
||||
}));
|
||||
|
||||
initPreferences(savedPrefs: TableColumnPreference[] | undefined): void {
|
||||
const effectivePrefs = savedPrefs?.length ? savedPrefs : this.fallbackPreferences;
|
||||
this._preferences.set(this.mergeWithAllColumns(effectivePrefs));
|
||||
}
|
||||
|
||||
get allColumns(): { field: string; header: string }[] {
|
||||
return this.allAvailableFields.map(field => ({
|
||||
field,
|
||||
header: this.t.translate(`book.columnPref.columns.${field}`)
|
||||
}));
|
||||
}
|
||||
|
||||
get visibleColumns(): { field: string; header: string }[] {
|
||||
return this.preferences()
|
||||
.filter(pref => pref.visible)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map(pref => ({
|
||||
field: pref.field,
|
||||
header: this.t.translate(`book.columnPref.columns.${pref.field}`)
|
||||
}));
|
||||
}
|
||||
|
||||
saveVisibleColumns(selectedColumns: { field: string }[]): void {
|
||||
const selectedFieldSet = new Set(selectedColumns.map(c => c.field));
|
||||
|
||||
const updatedPreferences: TableColumnPreference[] = this.allAvailableFields.map((field, index) => {
|
||||
const selectionIndex = selectedColumns.findIndex(c => c.field === field);
|
||||
return {
|
||||
field,
|
||||
visible: selectedFieldSet.has(field),
|
||||
order: selectionIndex >= 0 ? selectionIndex : index
|
||||
};
|
||||
});
|
||||
|
||||
this._preferences.set(updatedPreferences);
|
||||
|
||||
const currentUser = this.userService.getCurrentUser();
|
||||
if (!currentUser) return;
|
||||
|
||||
this.userService.updateUserSetting(currentUser.id, 'tableColumnPreference', updatedPreferences);
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.columnPref.toast.savedSummary'),
|
||||
detail: this.t.translate('book.columnPref.toast.savedDetail'),
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
|
||||
private mergeWithAllColumns(savedPrefs: TableColumnPreference[]): TableColumnPreference[] {
|
||||
const savedPrefMap = new Map(savedPrefs.map(p => [p.field, p]));
|
||||
|
||||
return this.allAvailableFields.map((field, index) => {
|
||||
const saved = savedPrefMap.get(field);
|
||||
return {
|
||||
field,
|
||||
visible: saved?.visible ?? true,
|
||||
order: saved?.order ?? index
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<div class="book-cover-wrapper" [class.audiobook-only]="isAudiobookOnly()" (mouseenter)="isHovered = true" (mouseleave)="isHovered = false">
|
||||
<img
|
||||
[src]="getThumbnailUrl()"
|
||||
class="book-cover"
|
||||
alt="Cover of {{ book.metadata?.title }}"
|
||||
loading="lazy"/>
|
||||
|
||||
@if (showSeriesNumber && !book.seriesCount && book.metadata?.seriesNumber != null) {
|
||||
<div class="series-number-overlay">
|
||||
#{{ book.metadata?.seriesNumber }}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!this.isActive) {
|
||||
<p-button
|
||||
icon="pi pi-info"
|
||||
class="info-btn"
|
||||
[rounded]="true"
|
||||
[pTooltip]="book.metadata?.title"
|
||||
tooltipPosition="top"
|
||||
[ngClass]="{ 'visible': isHovered }"
|
||||
(onClick)="openBookInfo(book)">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
.book-cover-wrapper {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
|
||||
.book-cover {
|
||||
width: 100%;
|
||||
display: block;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
&.audiobook-only {
|
||||
.book-cover {
|
||||
aspect-ratio: 1 / 1;
|
||||
object-fit: cover;
|
||||
}
|
||||
}
|
||||
|
||||
.info-btn {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.2s ease-in-out;
|
||||
z-index: 2;
|
||||
|
||||
&.visible {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.series-number-overlay {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 4px;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
color: white;
|
||||
font-size: 0.75rem;
|
||||
padding: 1px 3px;
|
||||
border-radius: 3px;
|
||||
z-index: 3;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import {ChangeDetectionStrategy, Component, computed, inject, Input} from '@angular/core';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service';
|
||||
import {TooltipModule} from 'primeng/tooltip';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card-lite-component',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [
|
||||
Button,
|
||||
NgClass,
|
||||
TooltipModule
|
||||
],
|
||||
templateUrl: './book-card-lite-component.html',
|
||||
styleUrl: './book-card-lite-component.scss'
|
||||
})
|
||||
export class BookCardLiteComponent {
|
||||
@Input() book!: Book;
|
||||
@Input() isActive: boolean = false;
|
||||
@Input() showSeriesNumber: boolean = false;
|
||||
|
||||
private router = inject(Router);
|
||||
protected urlHelper = inject(UrlHelperService);
|
||||
private userService = inject(UserService);
|
||||
private bookMetadataHostService = inject(BookMetadataHostService);
|
||||
|
||||
private metadataCenterViewMode = computed(() =>
|
||||
this.userService.currentUser()?.userSettings.metadataCenterViewMode ?? 'route'
|
||||
);
|
||||
isHovered: boolean = false;
|
||||
|
||||
isAudiobookOnly(): boolean {
|
||||
const primaryIsAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK';
|
||||
const hasEbookAlternative = this.book.alternativeFormats?.some(f => f.bookType !== 'AUDIOBOOK') ?? false;
|
||||
return primaryIsAudiobook && !hasEbookAlternative;
|
||||
}
|
||||
|
||||
getThumbnailUrl(): string {
|
||||
if (this.isAudiobookOnly()) {
|
||||
return this.urlHelper.getAudiobookThumbnailUrl(this.book.id, this.book.metadata?.audiobookCoverUpdatedOn);
|
||||
}
|
||||
return this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
|
||||
}
|
||||
|
||||
openBookInfo(book: Book): void {
|
||||
if (this.metadataCenterViewMode() === 'route') {
|
||||
this.router.navigate(['/book', book.id], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
} else {
|
||||
this.bookMetadataHostService.requestBookSwitch(book.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user