feat(ui): New sidebar & search UI (#831)

This commit is contained in:
Alex
2026-05-04 09:46:48 +01:00
committed by GitHub
parent c9b2a5734e
commit f3138a88c5
182 changed files with 8318 additions and 4660 deletions
@@ -136,6 +136,15 @@ export class AppBooksApiService {
}
}
searchBooks(query: string, size = 20): Observable<AppPageResponse<AppBookSummary>> {
const params = new HttpParams()
.set('q', query.trim())
.set('page', '0')
.set('size', Math.max(1, size).toString());
return this.http.get<AppPageResponse<AppBookSummary>>(`${this.booksUrl}/search`, {params});
}
fetchNextPage(): void {
this.booksQuery.fetchNextPage();
}
@@ -1,14 +1,243 @@
import {describe, it} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {of} from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import type {MenuItem, MenuItemCommandEvent} from 'primeng/api';
import {ConfirmationService, MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
// NOTE(frontend-seam): Real coverage here needs a seam around nested Prime confirmation payloads,
// router/navigation side effects, clipboard writes, and multiple dialog/task services so menu-item
// command wiring can be asserted without turning the spec into a brittle integration harness.
describe.skip('LibraryShelfMenuService', () => {
it('needs a menu-command seam to verify library, shelf, and magic-shelf action wiring deterministically', () => {
// TODO(seam): Cover confirmation payloads, delete/refresh commands, and dialog launches after introducing a thin menu-action adapter.
import {LibraryShelfMenuService} from './library-shelf-menu.service';
import {LibraryService} from './library.service';
import {ShelfService} from './shelf.service';
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
import {UserService} from '../../settings/user-management/user.service';
import {LoadingService} from '../../../core/services/loading.service';
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import type {Library} from '../model/library.model';
import type {Shelf} from '../model/shelf.model';
import type {MagicShelf} from '../../magic-shelf/service/magic-shelf.service';
function buildLibrary(overrides: Partial<Library> = {}): Library {
return {
id: 7,
name: 'Main Library',
watch: true,
paths: [],
...overrides,
};
}
function buildShelf(overrides: Partial<Shelf> = {}): Shelf {
return {
id: 11,
name: 'Favorites',
userId: 3,
publicShelf: false,
...overrides,
};
}
function buildMagicShelf(overrides: Partial<MagicShelf> = {}): MagicShelf {
return {
id: 13,
name: 'Magic Shelf',
filterJson: '{}',
isPublic: false,
...overrides,
};
}
function findMenuItem(items: MenuItem[], label: string): MenuItem {
const item = items
.flatMap(candidate => candidate.items ?? [candidate])
.find(candidate => candidate.label === label);
expect(item).toBeDefined();
return item!;
}
function runCommand(item: MenuItem): void {
item.command?.({ item } as MenuItemCommandEvent);
}
describe('LibraryShelfMenuService', () => {
let service: LibraryShelfMenuService;
const confirmationService = {
confirm: vi.fn(),
};
const messageService = {
add: vi.fn(),
};
const libraryService = {
refreshLibrary: vi.fn(() => of(undefined)),
deleteLibrary: vi.fn(() => of(undefined)),
};
const shelfService = {
deleteShelf: vi.fn(() => of(undefined)),
};
const taskHelperService = {
refreshMetadataTask: vi.fn(() => of(undefined)),
};
const userService = {
getCurrentUser: vi.fn(() => ({id: 3, permissions: {admin: false}})),
};
const router = {
navigate: vi.fn(),
};
const dialogLauncherService = {
openLibraryEditDialog: vi.fn(),
openLibraryMetadataFetchDialog: vi.fn(),
openShelfEditDialog: vi.fn(),
openMagicShelfEditDialog: vi.fn(),
};
const magicShelfService = {
deleteShelf: vi.fn(() => of(undefined)),
};
const loadingService = {
show: vi.fn(() => 'loader-token'),
hide: vi.fn(),
};
const bookDialogHelperService = {
openAddPhysicalBookDialog: vi.fn(),
openBulkIsbnImportDialog: vi.fn(),
openDuplicateMergerDialog: vi.fn(),
};
const translocoService = {
translate: vi.fn((key: string) => key),
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
LibraryShelfMenuService,
{provide: ConfirmationService, useValue: confirmationService},
{provide: MessageService, useValue: messageService},
{provide: LibraryService, useValue: libraryService},
{provide: ShelfService, useValue: shelfService},
{provide: TaskHelperService, useValue: taskHelperService},
{provide: UserService, useValue: userService},
{provide: Router, useValue: router},
{provide: DialogLauncherService, useValue: dialogLauncherService},
{provide: MagicShelfService, useValue: magicShelfService},
{provide: LoadingService, useValue: loadingService},
{provide: BookDialogHelperService, useValue: bookDialogHelperService},
{provide: TranslocoService, useValue: translocoService},
],
});
service = TestBed.inject(LibraryShelfMenuService);
});
it('needs a browser-side seam to verify clipboard and navigation behavior without relying on global runtime objects', () => {
// TODO(seam): Cover magic-shelf export and post-delete navigation once clipboard/router effects are injectable.
afterEach(() => {
TestBed.resetTestingModule();
vi.restoreAllMocks();
confirmationService.confirm.mockClear();
messageService.add.mockClear();
libraryService.refreshLibrary.mockClear();
libraryService.deleteLibrary.mockClear();
shelfService.deleteShelf.mockClear();
taskHelperService.refreshMetadataTask.mockClear();
userService.getCurrentUser.mockClear();
router.navigate.mockClear();
dialogLauncherService.openLibraryEditDialog.mockClear();
dialogLauncherService.openLibraryMetadataFetchDialog.mockClear();
dialogLauncherService.openShelfEditDialog.mockClear();
dialogLauncherService.openMagicShelfEditDialog.mockClear();
magicShelfService.deleteShelf.mockClear();
loadingService.show.mockClear();
loadingService.hide.mockClear();
bookDialogHelperService.openAddPhysicalBookDialog.mockClear();
bookDialogHelperService.openBulkIsbnImportDialog.mockClear();
bookDialogHelperService.openDuplicateMergerDialog.mockClear();
translocoService.translate.mockClear();
});
it('disables and guards library actions when the library id is missing', () => {
const items = service.initializeLibraryMenuItems(buildLibrary({id: undefined}));
const actionLabels = [
'book.shelfMenuService.library.addPhysicalBook',
'book.shelfMenuService.library.bulkIsbnImport',
'book.shelfMenuService.library.editLibrary',
'book.shelfMenuService.library.rescanLibrary',
'book.shelfMenuService.library.customFetchMetadata',
'book.shelfMenuService.library.autoFetchMetadata',
'book.shelfMenuService.library.findDuplicates',
'book.shelfMenuService.library.deleteLibrary',
];
for (const label of actionLabels) {
const item = findMenuItem(items, label);
expect(item.disabled).toBe(true);
runCommand(item);
}
expect(bookDialogHelperService.openAddPhysicalBookDialog).not.toHaveBeenCalled();
expect(bookDialogHelperService.openBulkIsbnImportDialog).not.toHaveBeenCalled();
expect(bookDialogHelperService.openDuplicateMergerDialog).not.toHaveBeenCalled();
expect(dialogLauncherService.openLibraryEditDialog).not.toHaveBeenCalled();
expect(dialogLauncherService.openLibraryMetadataFetchDialog).not.toHaveBeenCalled();
expect(taskHelperService.refreshMetadataTask).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
});
it('passes the concrete library id into library actions when available', () => {
const items = service.initializeLibraryMenuItems(buildLibrary({id: 42}));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.addPhysicalBook'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.bulkIsbnImport'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.editLibrary'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.customFetchMetadata'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.autoFetchMetadata'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.findDuplicates'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.rescanLibrary'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.deleteLibrary'));
expect(bookDialogHelperService.openAddPhysicalBookDialog).toHaveBeenCalledWith(42);
expect(bookDialogHelperService.openBulkIsbnImportDialog).toHaveBeenCalledWith(42);
expect(dialogLauncherService.openLibraryEditDialog).toHaveBeenCalledWith(42);
expect(dialogLauncherService.openLibraryMetadataFetchDialog).toHaveBeenCalledWith(42);
expect(taskHelperService.refreshMetadataTask).toHaveBeenCalledWith({
refreshType: MetadataRefreshType.LIBRARY,
libraryId: 42,
});
expect(bookDialogHelperService.openDuplicateMergerDialog).toHaveBeenCalledWith(42);
expect(confirmationService.confirm).toHaveBeenCalledTimes(2);
});
it('guards shelf actions when the shelf id is missing even for the owner', () => {
userService.getCurrentUser.mockReturnValue({id: 3, permissions: {admin: false}});
const items = service.initializeShelfMenuItems(buildShelf({id: undefined, userId: 3}));
const editItem = findMenuItem(items, 'book.shelfMenuService.shelf.editShelf');
const deleteItem = findMenuItem(items, 'book.shelfMenuService.shelf.deleteShelf');
expect(editItem.disabled).toBe(true);
expect(deleteItem.disabled).toBe(true);
runCommand(editItem);
runCommand(deleteItem);
expect(dialogLauncherService.openShelfEditDialog).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
});
it('guards magic shelf actions when the shelf id is missing', () => {
const items = service.initializeMagicShelfMenuItems(buildMagicShelf({id: null}));
const editItem = findMenuItem(items, 'book.shelfMenuService.magicShelf.editMagicShelf');
const deleteItem = findMenuItem(items, 'book.shelfMenuService.magicShelf.deleteMagicShelf');
expect(editItem.disabled).toBe(true);
expect(deleteItem.disabled).toBe(true);
runCommand(editItem);
runCommand(deleteItem);
expect(dialogLauncherService.openMagicShelfEditDialog).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
});
});
@@ -35,295 +35,331 @@ export class LibraryShelfMenuService {
private readonly t = inject(TranslocoService);
initializeLibraryMenuItems(entity: Library | null): MenuItem[] {
const libraryId = entity?.id;
const disableLibraryActions = libraryId == null;
return [
{
label: this.t.translate('book.shelfMenuService.library.optionsLabel'),
items: [
{
label: this.t.translate('book.shelfMenuService.library.addPhysicalBook'),
icon: 'pi pi-book',
command: () => {
this.bookDialogHelperService.openAddPhysicalBookDialog(entity?.id as number);
}
},
{
label: this.t.translate('book.shelfMenuService.library.bulkIsbnImport'),
icon: 'pi pi-barcode',
command: () => {
this.bookDialogHelperService.openBulkIsbnImportDialog(entity?.id as number);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.editLibrary'),
icon: 'pi pi-pen-to-square',
command: () => {
this.dialogLauncherService.openLibraryEditDialog((entity?.id as number));
}
},
{
label: this.t.translate('book.shelfMenuService.library.rescanLibrary'),
icon: 'pi pi-refresh',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.rescanLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
icon: undefined,
acceptLabel: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
rejectLabel: this.t.translate('common.cancel'),
acceptIcon: undefined,
rejectIcon: undefined,
acceptButtonStyleClass: undefined,
rejectButtonStyleClass: undefined,
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
severity: 'success',
},
accept: () => {
const libraryId = entity?.id;
if (libraryId == null) {
return;
}
label: this.t.translate('book.shelfMenuService.library.addPhysicalBook'),
icon: 'pi pi-book',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.libraryService.refreshLibrary(libraryId).subscribe({
complete: () => {
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshSuccessDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshFailedDetail'),
});
}
this.bookDialogHelperService.openAddPhysicalBookDialog(libraryId);
}
},
{
label: this.t.translate('book.shelfMenuService.library.bulkIsbnImport'),
icon: 'pi pi-barcode',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.bookDialogHelperService.openBulkIsbnImportDialog(libraryId);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.editLibrary'),
icon: 'pi pi-pen-to-square',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.dialogLauncherService.openLibraryEditDialog(libraryId);
}
},
{
label: this.t.translate('book.shelfMenuService.library.rescanLibrary'),
icon: 'pi pi-refresh',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.rescanLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
icon: undefined,
acceptLabel: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
rejectLabel: this.t.translate('common.cancel'),
acceptIcon: undefined,
rejectIcon: undefined,
acceptButtonStyleClass: undefined,
rejectButtonStyleClass: undefined,
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
severity: 'success',
},
accept: () => {
this.libraryService.refreshLibrary(libraryId).subscribe({
complete: () => {
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshSuccessDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshFailedDetail'),
});
}
});
}
},
{
label: this.t.translate('book.shelfMenuService.library.customFetchMetadata'),
icon: 'pi pi-sync',
command: () => {
this.dialogLauncherService.openLibraryMetadataFetchDialog((entity?.id as number));
}
},
{
label: this.t.translate('book.shelfMenuService.library.autoFetchMetadata'),
icon: 'pi pi-bolt',
command: () => {
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.LIBRARY,
libraryId: entity?.id ?? undefined
}).subscribe();
}
},
{
label: this.t.translate('book.shelfMenuService.library.findDuplicates'),
icon: 'pi pi-copy',
command: () => {
this.bookDialogHelperService.openDuplicateMergerDialog(entity?.id as number);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.deleteLibrary'),
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger',
},
accept: () => {
const loader = this.loadingService.show(this.t.translate('book.shelfMenuService.loading.deletingLibrary', {name: entity?.name}));
const libraryId = entity?.id;
if (libraryId == null) {
this.loadingService.hide(loader);
return;
}
this.libraryService.deleteLibrary(libraryId)
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryDeleteFailedDetail'),
});
}
});
}
});
}
});
}
},
{
label: this.t.translate('book.shelfMenuService.library.customFetchMetadata'),
icon: 'pi pi-sync',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
]
this.dialogLauncherService.openLibraryMetadataFetchDialog(libraryId);
}
},
{
label: this.t.translate('book.shelfMenuService.library.autoFetchMetadata'),
icon: 'pi pi-bolt',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.LIBRARY,
libraryId
}).subscribe();
}
},
{
label: this.t.translate('book.shelfMenuService.library.findDuplicates'),
icon: 'pi pi-copy',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.bookDialogHelperService.openDuplicateMergerDialog(libraryId);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.deleteLibrary'),
icon: 'pi pi-trash',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger',
},
accept: () => {
const loader = this.loadingService.show(this.t.translate('book.shelfMenuService.loading.deletingLibrary', {name: entity?.name}));
this.libraryService.deleteLibrary(libraryId)
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryDeleteFailedDetail'),
});
}
});
}
});
}
}
];
}
initializeShelfMenuItems(entity: Shelf | null): MenuItem[] {
const user = this.userService.getCurrentUser();
const shelfId = entity?.id;
const isOwner = entity?.userId === user?.id;
const isPublicShelf = entity?.publicShelf ?? false;
const disableOptions = !isOwner;
const disableOptions = !isOwner || shelfId == null;
return [
const items: MenuItem[] = [
{
label: (isPublicShelf ? this.t.translate('book.shelfMenuService.shelf.publicShelfPrefix') : '') + (disableOptions ? this.t.translate('book.shelfMenuService.shelf.readOnly') : this.t.translate('book.shelfMenuService.shelf.optionsLabel')),
items: [
{
label: this.t.translate('book.shelfMenuService.shelf.editShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
this.dialogLauncherService.openShelfEditDialog((entity?.id as number));
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.shelf.deleteShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
const shelfId = entity?.id;
if (shelfId == null) {
return;
}
label: this.t.translate('book.shelfMenuService.shelf.editShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
if (shelfId == null) {
return;
}
this.shelfService.deleteShelf(shelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.shelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.shelfDeleteFailedDetail'),
});
}
this.dialogLauncherService.openShelfEditDialog(shelfId);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.shelf.deleteShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
if (shelfId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
this.shelfService.deleteShelf(shelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.shelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.shelfDeleteFailedDetail'),
});
}
});
}
}
]
});
}
}
];
/* Keep the grouped label only when it conveys state (public/read-only). */
if (isPublicShelf || disableOptions) {
const prefix = isPublicShelf ? this.t.translate('book.shelfMenuService.shelf.publicShelfPrefix') : '';
const suffix = disableOptions
? this.t.translate('book.shelfMenuService.shelf.readOnly')
: this.t.translate('book.shelfMenuService.shelf.optionsLabel');
return [{ label: prefix + suffix, items }];
}
return items;
}
initializeMagicShelfMenuItems(entity: MagicShelf | null): MenuItem[] {
const isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
const magicShelfId = entity?.id;
const isPublicShelf = entity?.isPublic ?? false;
const disableOptions = isPublicShelf && !isAdmin;
const disableOptions = magicShelfId == null || (isPublicShelf && !isAdmin);
return [
{
label: this.t.translate('book.shelfMenuService.magicShelf.optionsLabel'),
items: [
{
label: this.t.translate('book.shelfMenuService.magicShelf.editMagicShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
this.dialogLauncherService.openMagicShelfEditDialog((entity?.id as number));
}
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.exportJson'),
icon: 'pi pi-copy',
command: () => {
if (entity?.filterJson) {
navigator.clipboard.writeText(entity.filterJson).then(() => {
this.messageService.add({severity: 'success', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfJsonCopiedDetail')});
});
}
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.deleteMagicShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteMagicShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
const shelfId = entity?.id;
if (shelfId == null) {
return;
}
label: this.t.translate('book.shelfMenuService.magicShelf.editMagicShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
if (magicShelfId == null) {
return;
}
this.magicShelfService.deleteShelf(shelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeleteFailedDetail'),
});
}
this.dialogLauncherService.openMagicShelfEditDialog(magicShelfId);
}
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.exportJson'),
icon: 'pi pi-copy',
command: () => {
if (entity?.filterJson) {
navigator.clipboard.writeText(entity.filterJson).then(() => {
this.messageService.add({severity: 'success', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfJsonCopiedDetail')});
});
}
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.deleteMagicShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
if (magicShelfId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteMagicShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
this.magicShelfService.deleteShelf(magicShelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeleteFailedDetail'),
});
}
});
}
}
]
});
}
}
];
}
@@ -130,6 +130,16 @@ export class LibraryService {
return this.bookService.books().filter(book => book.libraryId === libraryId).length;
}
readonly bookCountByLibraryId = computed(() => {
const counts = new Map<number, number>();
for (const book of this.bookService.books()) {
if (book.libraryId != null) {
counts.set(book.libraryId, (counts.get(book.libraryId) ?? 0) + 1);
}
}
return counts;
});
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
this.largeLibraryLoading.set({ isLoading, expectedCount });
}
@@ -1,8 +1,9 @@
import {HttpTestingController} from '@angular/common/http/testing';
import {signal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
import {createAuthServiceStub, createQueryClientHarness, flushQueryAsync, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
import type {Book} from '../model/book.model';
import type {Shelf} from '../model/shelf.model';
import {AuthService} from '../../../shared/service/auth.service';
@@ -41,6 +42,7 @@ describe('ShelfService', () => {
let userService: {
getCurrentUser: ReturnType<typeof vi.fn>;
};
let currentUser: ReturnType<typeof signal<{id: number} | null>>;
beforeEach(() => {
authService = createAuthServiceStub();
@@ -49,8 +51,9 @@ describe('ShelfService', () => {
books: vi.fn(() => []),
removeBooksFromShelf: vi.fn(),
};
currentUser = signal<{id: number} | null>(null);
userService = {
getCurrentUser: vi.fn(() => null),
getCurrentUser: vi.fn(() => currentUser()),
};
vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
@@ -79,8 +82,7 @@ describe('ShelfService', () => {
});
async function flushShelvesQueryResult(): Promise<void> {
await Promise.resolve();
flushSignalAndQueryEffects();
await flushQueryAsync();
}
it('eagerly fetches shelves and hydrates the computed shelves signal', async () => {
@@ -94,10 +96,26 @@ describe('ShelfService', () => {
request.flush(response);
await flushShelvesQueryResult();
expect(service.shelves()).toEqual(response);
expect(service.shelves()).toEqual([
expect.objectContaining({id: 1, name: 'Reading', systemKey: null}),
expect.objectContaining({id: 2, name: 'Archive', systemKey: null}),
]);
expect(service.shelvesError()).toBeNull();
});
it('marks the Kobo system shelf when the backend returns the known Kobo shelf shape', async () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([
buildShelf({id: 1, name: 'Kobo', icon: 'pi pi-tablet'}),
buildShelf({id: 2, name: 'Archive', icon: 'pi pi-folder'}),
]);
await flushShelvesQueryResult();
expect(service.shelves()).toEqual([
expect.objectContaining({id: 1, name: 'Kobo', systemKey: 'kobo'}),
expect.objectContaining({id: 2, name: 'Archive', systemKey: null}),
]);
});
it('removes shelf queries when the auth token is cleared', () => {
const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
@@ -149,14 +167,36 @@ describe('ShelfService', () => {
buildBook(3, {shelves: [buildShelf({id: 2, name: 'Archive'})]}),
]);
userService.getCurrentUser.mockReturnValue({id: 7});
currentUser.set({id: 7});
expect(service.getBookCountValue(1)).toBe(2);
userService.getCurrentUser.mockReturnValue({id: 42});
currentUser.set({id: 42});
expect(service.getBookCountValue(2)).toBe(6);
expect(service.getBookCountValue(999)).toBe(0);
});
it('builds shelf count maps with local counts for the owner and persisted counts for shared shelves', async () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([
buildShelf({id: 1, userId: 7, bookCount: 99}),
buildShelf({id: 2, userId: 10, bookCount: 6}),
]);
await flushShelvesQueryResult();
bookService.books.mockReturnValue([
buildBook(1, {shelves: [buildShelf({id: 1, name: 'Reading'})]}),
buildBook(2, {shelves: [buildShelf({id: 1, name: 'Reading'})]}),
buildBook(3, {shelves: [buildShelf({id: 2, name: 'Archive'})]}),
]);
currentUser.set({id: 7});
flushSignalAndQueryEffects();
const counts = service.bookCountByShelfId();
expect(counts.get(1)).toBe(2);
expect(counts.get(2)).toBe(6);
});
it('counts unshelved books from the current book cache snapshot', () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
@@ -12,6 +12,8 @@ import {UserService} from '../../settings/user-management/user.service';
import {AuthService} from '../../../shared/service/auth.service';
const SHELVES_QUERY_KEY = ['shelves'] as const;
const KOBO_SHELF_NAME = 'Kobo';
const KOBO_SHELF_ICON = 'pi pi-tablet';
@Injectable({providedIn: 'root'})
export class ShelfService {
@@ -53,7 +55,7 @@ export class ShelfService {
private getShelvesQueryOptions() {
return queryOptions({
queryKey: SHELVES_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<Shelf[]>(this.url))
queryFn: async () => this.decorateShelves(await lastValueFrom(this.http.get<Shelf[]>(this.url)))
});
}
@@ -110,4 +112,40 @@ export class ShelfService {
return this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length;
}
readonly bookCountByShelfId = computed(() => {
const currentUserId = this.userService.getCurrentUser()?.id;
const counts = new Map<number, number>();
for (const book of this.bookService.books()) {
for (const shelf of book.shelves ?? []) {
if (shelf.id != null) {
counts.set(shelf.id, (counts.get(shelf.id) ?? 0) + 1);
}
}
}
for (const shelf of this.shelves()) {
if (shelf.userId !== currentUserId && shelf.id != null) {
counts.set(shelf.id, shelf.bookCount ?? 0);
}
}
return counts;
});
readonly unshelvedBookCount = computed(() =>
this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length
);
private decorateShelves(shelves: Shelf[]): Shelf[] {
return shelves.map((shelf) => ({
...shelf,
systemKey: this.getSystemKey(shelf),
}));
}
private getSystemKey(shelf: Shelf): Shelf['systemKey'] {
return shelf.name === KOBO_SHELF_NAME && shelf.icon === KOBO_SHELF_ICON ? 'kobo' : null;
}
}