refactor(ui): switch library and shelf menu to app-menu (#2057)

This commit is contained in:
Alex
2026-07-30 20:47:24 +01:00
committed by GitHub
parent 134e97f028
commit 0acd8bcb1e
22 changed files with 631 additions and 845 deletions
@@ -28,19 +28,24 @@
}
</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"
@if (entityMenuTarget(); as menuTarget) {
<div class="entity-menu-wrapper">
<app-library-shelf-menu
#entityMenu
[target]="menuTarget"
[ariaLabel]="'common.moreActionsFor' | transloco: {label: menuTarget.entity.name}" />
@if (entityMenu.available()) {
<button
pButton
type="button"
[rounded]="true"
[text]="true"
(click)="entitymenu.toggle($event)">
</p-button>
<p-menu #entitymenu [model]="entityOptions()" [popup]="true" appendTo="body"></p-menu>
</div>
}
[attr.aria-label]="'common.moreActionsFor' | transloco: {label: menuTarget.entity.name}"
[appMenuTriggerFor]="entityMenu.menu()">
<i class="pi pi-ellipsis-v" aria-hidden="true"></i>
</button>
}
</div>
}
}
</div>
@@ -8,7 +8,6 @@ import {ConfirmationService, MessageService} from '@openng/optimus-ui/api';
import {PageTitleService} from '../../../../shared/service/page-title.service';
import {BookService} from '../../service/book.service';
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
import {Book} from '../../model/book.model';
import {SortDirection, SortOption} from '../../model/sort.model';
import {UserService} from '../../../settings/user-management/user.service';
@@ -294,14 +293,6 @@ function createHarness(options?: {
getMetadataMenuItems: vi.fn(() => []),
},
},
{
provide: LibraryShelfMenuService,
useValue: {
initializeLibraryMenuItems: vi.fn(() => []),
initializeMagicShelfMenuItems: vi.fn(() => []),
initializeShelfMenuItems: vi.fn(() => []),
},
},
{provide: PageTitleService, useValue: {setPageTitle: vi.fn()}},
{provide: LoadingService, useValue: {show: vi.fn(), hide: vi.fn()}},
{provide: LocalStorageService, useValue: {get: vi.fn(), set: vi.fn()}},
@@ -11,13 +11,15 @@ import {DynamicDialogRef} from '@openng/optimus-ui/dynamicdialog';
import {Library} from '../../model/library.model';
import {SortDirection, SortOption} from '../../model/sort.model';
import {Book} from '../../model/book.model';
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
import {
LibraryShelfMenuComponent,
type LibraryShelfMenuTarget,
} from '../library-shelf-menu/library-shelf-menu.component';
import {BookTableComponent} from './book-table/book-table.component';
import {Button} from '@openng/optimus-ui/button';
import {Button, ButtonDirective} from '@openng/optimus-ui/button';
import {NgClass} from '@angular/common';
import {BookCardComponent} from './book-card/book-card.component';
import {Menu} from '@openng/optimus-ui/menu';
import {InputText} from '@openng/optimus-ui/inputtext';
import {FormsModule} from '@angular/forms';
import {BookFilterComponent} from './book-filter/book-filter.component';
@@ -59,6 +61,7 @@ import {filterBooksByFilters} from './filters/sidebar-filter';
import {LayoutService} from '../../../../shared/layout/layout.service';
import {createGridDensity} from '../../../../shared/util/grid-density.util';
import {DeferredRenderState} from './deferred-render-state';
import {AppMenuTriggerDirective} from '../../../../shared/ui/menu/app-menu-trigger.directive';
export enum EntityType {
LIBRARY = 'Library',
@@ -81,9 +84,10 @@ const MOBILE_COLUMNS_STORAGE_KEY = 'mobileColumnsPreference';
styleUrls: ['./book-browser.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
Button, BookCardComponent, Menu, InputText, FormsModule,
Button, ButtonDirective, BookCardComponent, InputText, FormsModule,
BookTableComponent, BookFilterComponent, Tooltip, NgClass, Popover,
Checkbox, Divider, MultiSelect, TieredMenu, Badge, MultiSortPopoverComponent, TranslocoDirective, TranslocoPipe, GridDensityButtonsComponent,
LibraryShelfMenuComponent, AppMenuTriggerDirective,
],
providers: [SeriesCollapseFilter],
})
@@ -105,7 +109,6 @@ export class BookBrowserComponent implements AfterViewInit {
private bookMetadataManageService = inject(BookMetadataManageService);
private dialogHelperService = inject(BookDialogHelperService);
private bookMenuService = inject(BookMenuService);
private libraryShelfMenuService = inject(LibraryShelfMenuService);
private pageTitle = inject(PageTitleService);
private loadingService = inject(LoadingService);
private bookNavigationService = inject(BookNavigationService);
@@ -187,19 +190,17 @@ export class BookBrowserComponent implements AfterViewInit {
const {entityId, entityType} = this.entityInfo();
return this.entityService.getEntity(entityId, entityType);
});
readonly entityOptions = computed<MenuItem[]>(() => {
readonly entityMenuTarget = computed<LibraryShelfMenuTarget | null>(() => {
const entity = this.entity();
if (!entity) {
return [];
if (entity?.id == null) return null;
if (this.entityService.isLibrary(entity)) {
return {type: 'library', entity: {...entity, id: entity.id}};
}
const actions = this.entityService.isLibrary(entity)
? this.libraryShelfMenuService.initializeLibraryMenuItems(entity)
: this.entityService.isMagicShelf(entity)
? this.libraryShelfMenuService.initializeMagicShelfMenuItems(entity)
: this.libraryShelfMenuService.initializeShelfMenuItems(entity);
return actions;
if (this.entityService.isMagicShelf(entity)) {
return {type: 'magicShelf', entity: {...entity, id: entity.id}};
}
return {type: 'shelf', entity: {...entity, id: entity.id}};
});
// Deferred pipeline: heavy filter/sort runs in a setTimeout so the page chrome
// and skeletons paint first, then real books replace them on the next task.
@@ -0,0 +1,82 @@
import {signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {provideRouter} from '@angular/router';
import {beforeEach, describe, expect, it} from 'vitest';
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
import {LayoutService} from '../../../../shared/layout/layout.service';
import {UserService} from '../../../settings/user-management/user.service';
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
import {LibraryShelfMenuComponent} from './library-shelf-menu.component';
describe('LibraryShelfMenuComponent', () => {
let fixture: ComponentFixture<LibraryShelfMenuComponent>;
const currentUser = signal({
id: 3,
permissions: {admin: false, canManageLibrary: true},
});
beforeEach(() => {
TestBed.configureTestingModule({
imports: [LibraryShelfMenuComponent, getTranslocoModule()],
providers: [
provideRouter([]),
{provide: UserService, useValue: {currentUser}},
{provide: LibraryShelfMenuService, useValue: {}},
{provide: LayoutService, useValue: {isDesktop: signal(true)}},
],
});
fixture = TestBed.createComponent(LibraryShelfMenuComponent);
});
it.each([
{
name: 'library manager',
user: {id: 3, permissions: {admin: false, canManageLibrary: true}},
target: {type: 'library', entity: {id: 7, name: 'Library', watch: true, paths: []}},
labels: ['Add Physical Book', 'Import ISBNs from File', 'Edit Library', 'Re-scan Library',
'Custom Fetch Metadata', 'Auto Fetch Metadata', 'Find Duplicates', 'Delete Library'],
disabled: 0,
available: true,
},
{
name: 'library reader',
user: {id: 3, permissions: {admin: false, canManageLibrary: false}},
target: {type: 'library', entity: {id: 7, name: 'Library', watch: true, paths: []}},
labels: [],
disabled: 0,
available: false,
},
{
name: 'public shelf reader',
user: {id: 3, permissions: {admin: false, canManageLibrary: false}},
target: {type: 'shelf', entity: {id: 11, name: 'Shelf', userId: 99, publicShelf: true}},
labels: ['Edit Shelf', 'Delete Shelf'],
disabled: 2,
available: true,
},
{
name: 'public magic-shelf reader',
user: {id: 3, permissions: {admin: false, canManageLibrary: false}},
target: {type: 'magicShelf', entity: {id: 13, name: 'Magic', filterJson: '{}', isPublic: true}},
labels: ['Edit Magic Shelf', 'Copy JSON', 'Delete Magic Shelf'],
disabled: 2,
available: true,
},
])('renders the $name state', async ({user, target, labels, disabled, available}) => {
currentUser.set(user);
fixture.componentRef.setInput('target', target);
fixture.componentRef.setInput('ariaLabel', 'Actions');
await fixture.whenStable();
fixture.componentInstance.menu().open(fixture.nativeElement);
await fixture.whenStable();
const menu = document.querySelector('app-menu[aria-label="Actions"]') as HTMLElement;
const renderedLabels = Array.from(menu.querySelectorAll('app-menu-item'))
.map(item => item.textContent?.trim());
expect(fixture.componentInstance.available()).toBe(available);
expect(renderedLabels).toEqual(labels);
expect(menu.querySelectorAll('app-menu-item[aria-disabled="true"]')).toHaveLength(disabled);
});
});
@@ -0,0 +1,157 @@
import {ChangeDetectionStrategy, Component, computed, inject, input, output, viewChild} from '@angular/core';
import {LucideTrash2} from '@lucide/angular';
import {TranslocoPipe} from '@jsverse/transloco';
import {AppMenuComponent} from '../../../../shared/ui/menu/app-menu.component';
import {AppMenuContentDirective} from '../../../../shared/ui/menu/app-menu-content.directive';
import {AppMenuItemComponent} from '../../../../shared/ui/menu/app-menu-item.component';
import {AppMenuSectionComponent} from '../../../../shared/ui/menu/app-menu-section.component';
import {AppMenuSeparatorComponent} from '../../../../shared/ui/menu/app-menu-separator.component';
import {MagicShelf} from '../../../magic-shelf/service/magic-shelf.service';
import {UserService} from '../../../settings/user-management/user.service';
import {Library} from '../../model/library.model';
import {Shelf} from '../../model/shelf.model';
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
type Persisted<T extends {id?: number | null}> = Omit<T, 'id'> & {id: number};
export type LibraryShelfMenuTarget =
| {type: 'library'; entity: Persisted<Library>}
| {type: 'shelf'; entity: Persisted<Shelf>}
| {type: 'magicShelf'; entity: Persisted<MagicShelf>};
@Component({
selector: 'app-library-shelf-menu',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {class: 'contents'},
imports: [
TranslocoPipe,
AppMenuComponent,
AppMenuContentDirective,
AppMenuItemComponent,
AppMenuSectionComponent,
AppMenuSeparatorComponent,
],
template: `
@let currentTarget = target();
<app-menu
[ariaLabel]="ariaLabel()"
(opened)="opened.emit()"
(closed)="closed.emit()">
<ng-template appMenuContent>
@if (available()) {
@switch (currentTarget.type) {
@case ('library') {
<app-menu-item (selected)="actions.addPhysicalBook(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.addPhysicalBook' | transloco }}
</app-menu-item>
<app-menu-item (selected)="actions.importIsbns(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.bulkIsbnImport' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
(selected)="actions.editLibrary(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.editLibrary' | transloco }}
</app-menu-item>
<app-menu-item (selected)="actions.rescanLibrary(currentTarget.entity)">
{{ 'book.shelfMenuService.library.rescanLibrary' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item (selected)="actions.customFetchLibraryMetadata(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.customFetchMetadata' | transloco }}
</app-menu-item>
<app-menu-item (selected)="actions.autoFetchLibraryMetadata(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.autoFetchMetadata' | transloco }}
</app-menu-item>
<app-menu-item (selected)="actions.findLibraryDuplicates(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.findDuplicates' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
[icon]="trashIcon"
variant="destructive"
(selected)="actions.deleteLibrary(currentTarget.entity)">
{{ 'book.shelfMenuService.library.deleteLibrary' | transloco }}
</app-menu-item>
}
@case ('shelf') {
@if (currentTarget.entity.publicShelf || !canManageShelf()) {
<app-menu-section>
@if (currentTarget.entity.publicShelf) {
{{ 'book.shelfMenuService.shelf.publicShelfPrefix' | transloco }}
}
{{ (canManageShelf()
? 'book.shelfMenuService.shelf.optionsLabel'
: 'book.shelfMenuService.shelf.readOnly') | transloco }}
</app-menu-section>
}
<app-menu-item
[disabled]="!canManageShelf()"
(selected)="actions.editShelf(currentTarget.entity.id)">
{{ 'book.shelfMenuService.shelf.editShelf' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
[icon]="trashIcon"
[disabled]="!canManageShelf()"
variant="destructive"
(selected)="actions.deleteShelf(currentTarget.entity)">
{{ 'book.shelfMenuService.shelf.deleteShelf' | transloco }}
</app-menu-item>
}
@case ('magicShelf') {
<app-menu-item
[disabled]="!canManageMagicShelf()"
(selected)="actions.editMagicShelf(currentTarget.entity.id)">
{{ 'book.shelfMenuService.magicShelf.editMagicShelf' | transloco }}
</app-menu-item>
<app-menu-item (selected)="actions.copyMagicShelfJson(currentTarget.entity.filterJson)">
{{ 'book.shelfMenuService.magicShelf.exportJson' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
[icon]="trashIcon"
[disabled]="!canManageMagicShelf()"
variant="destructive"
(selected)="actions.deleteMagicShelf(currentTarget.entity)">
{{ 'book.shelfMenuService.magicShelf.deleteMagicShelf' | transloco }}
</app-menu-item>
}
}
}
</ng-template>
</app-menu>
`,
})
export class LibraryShelfMenuComponent {
readonly target = input.required<LibraryShelfMenuTarget>();
readonly ariaLabel = input.required<string>();
readonly opened = output<void>();
readonly closed = output<void>();
readonly menu = viewChild.required(AppMenuComponent);
private readonly currentUser = inject(UserService).currentUser;
protected readonly actions = inject(LibraryShelfMenuService);
protected readonly trashIcon = LucideTrash2.icon;
readonly available = computed(() => {
const user = this.currentUser();
if (!user) return false;
return this.target().type !== 'library'
|| user.permissions.admin
|| user.permissions.canManageLibrary;
});
protected readonly canManageShelf = computed(() => {
const target = this.target();
return target.type === 'shelf' && target.entity.userId === this.currentUser()?.id;
});
protected readonly canManageMagicShelf = computed(() => {
const target = this.target();
return target.type === 'magicShelf'
&& (!target.entity.isPublic || !!this.currentUser()?.permissions.admin);
});
}
@@ -1,114 +1,48 @@
import {TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {TranslocoService} from '@jsverse/transloco';
import {ConfirmationService, MessageService} from '@openng/optimus-ui/api';
import {of} from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import type {MenuItem, MenuItemCommandEvent} from '@openng/optimus-ui/api';
import {ConfirmationService, MessageService} from '@openng/optimus-ui/api';
import {TranslocoService} from '@jsverse/transloco';
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);
}
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
import {LibraryService} from './library.service';
import {LibraryShelfMenuService} from './library-shelf-menu.service';
import {ShelfService} from './shelf.service';
describe('LibraryShelfMenuService', () => {
let service: LibraryShelfMenuService;
const confirmationService = {
confirm: vi.fn(),
};
const messageService = {
add: vi.fn(),
};
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 shelfService = {deleteShelf: vi.fn(() => of(undefined))};
const magicShelfService = {deleteShelf: vi.fn(() => of(undefined))};
const taskHelperService = {refreshMetadataTask: vi.fn(() => of(undefined))};
const router = {url: '/', navigate: vi.fn(() => Promise.resolve(true))};
const dialogLauncherService = {
openLibraryEditDialog: vi.fn(() => Promise.resolve(null)),
openShelfEditDialog: vi.fn(() => Promise.resolve(null)),
openMagicShelfEditDialog: vi.fn(() => Promise.resolve(null)),
};
const magicShelfService = {
deleteShelf: vi.fn(() => of(undefined)),
};
const loadingService = {
show: vi.fn(() => 'loader-token'),
hide: vi.fn(),
};
const loadingService = {show: vi.fn(() => 'loader-token'), hide: vi.fn()};
const bookDialogHelperService = {
openAddPhysicalBookDialog: vi.fn(() => Promise.resolve(null)),
openBulkIsbnImportDialog: vi.fn(() => Promise.resolve(null)),
openDuplicateMergerDialog: vi.fn(() => Promise.resolve(null)),
openMetadataRefreshDialogWithContext: vi.fn(() => Promise.resolve(null)),
};
const translocoService = {
translate: vi.fn((key: string) => key),
};
const translocoService = {translate: vi.fn((key: string) => key)};
beforeEach(() => {
router.url = '/';
TestBed.configureTestingModule({
providers: [
LibraryShelfMenuService,
@@ -116,131 +50,79 @@ describe('LibraryShelfMenuService', () => {
{provide: MessageService, useValue: messageService},
{provide: LibraryService, useValue: libraryService},
{provide: ShelfService, useValue: shelfService},
{provide: MagicShelfService, useValue: magicShelfService},
{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);
});
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.openShelfEditDialog.mockClear();
dialogLauncherService.openMagicShelfEditDialog.mockClear();
magicShelfService.deleteShelf.mockClear();
loadingService.show.mockClear();
loadingService.hide.mockClear();
bookDialogHelperService.openAddPhysicalBookDialog.mockClear();
bookDialogHelperService.openBulkIsbnImportDialog.mockClear();
bookDialogHelperService.openDuplicateMergerDialog.mockClear();
bookDialogHelperService.openMetadataRefreshDialogWithContext.mockClear();
translocoService.translate.mockClear();
vi.clearAllMocks();
vi.unstubAllGlobals();
});
it('disables and guards library actions when the library id is missing', () => {
const items = service.initializeLibraryMenuItems(buildLibrary({id: undefined}));
it('runs accepted library confirmation actions with the resolved name', () => {
service.rescanLibrary({id: 7, name: 'Main Library'});
expect(confirmationService.confirm.mock.calls[0][0].message)
.toBe('book.shelfMenuService.confirm.rescanLibraryMessage');
confirmationService.confirm.mock.calls[0][0].accept();
expect(libraryService.refreshLibrary).toHaveBeenCalledWith(7);
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',
];
service.deleteLibrary({id: 7, name: 'Main Library'});
confirmationService.confirm.mock.calls[1][0].accept();
expect(libraryService.deleteLibrary).toHaveBeenCalledWith(7);
expect(loadingService.hide).toHaveBeenCalledWith('loader-token');
expect(router.navigate).not.toHaveBeenCalled();
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(bookDialogHelperService.openMetadataRefreshDialogWithContext).not.toHaveBeenCalled();
expect(taskHelperService.refreshMetadataTask).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
router.url = '/library/7/books?sort=title#results';
service.deleteLibrary({id: 7, name: 'Main Library'});
confirmationService.confirm.mock.calls[2][0].accept();
expect(router.navigate).toHaveBeenCalledWith(['/']);
});
it('passes the concrete library id into library actions when available', () => {
const items = service.initializeLibraryMenuItems(buildLibrary({id: 42}));
it('runs shelf and magic-shelf actions', () => {
service.editShelf(11);
service.deleteShelf({id: 11, name: 'Favorites'});
service.editMagicShelf(13);
service.deleteMagicShelf({id: 13, name: 'Magic Shelf'});
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(bookDialogHelperService.openMetadataRefreshDialogWithContext).toHaveBeenCalledWith({
metadataRefreshType: MetadataRefreshType.LIBRARY,
libraryId: 42
});
expect(taskHelperService.refreshMetadataTask).toHaveBeenCalledWith({
refreshType: MetadataRefreshType.LIBRARY,
libraryId: 42,
});
expect(bookDialogHelperService.openDuplicateMergerDialog).toHaveBeenCalledWith(42);
expect(dialogLauncherService.openShelfEditDialog).toHaveBeenCalledWith(11);
expect(dialogLauncherService.openMagicShelfEditDialog).toHaveBeenCalledWith(13);
expect(confirmationService.confirm).toHaveBeenCalledTimes(2);
confirmationService.confirm.mock.calls[0][0].accept();
confirmationService.confirm.mock.calls[1][0].accept();
expect(shelfService.deleteShelf).toHaveBeenCalledWith(11);
expect(magicShelfService.deleteShelf).toHaveBeenCalledWith(13);
expect(router.navigate).not.toHaveBeenCalled();
router.url = '/shelf/11/books?sort=title#results';
service.deleteShelf({id: 11, name: 'Favorites'});
confirmationService.confirm.mock.calls[2][0].accept();
router.url = '/magic-shelf/13/books?sort=title#results';
service.deleteMagicShelf({id: 13, name: 'Magic Shelf'});
confirmationService.confirm.mock.calls[3][0].accept();
expect(router.navigate).toHaveBeenNthCalledWith(1, ['/']);
expect(router.navigate).toHaveBeenNthCalledWith(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}));
it('copies magic-shelf JSON', async () => {
const writeText = vi.fn(() => Promise.resolve());
vi.stubGlobal('navigator', {clipboard: {writeText}});
const editItem = findMenuItem(items, 'book.shelfMenuService.shelf.editShelf');
const deleteItem = findMenuItem(items, 'book.shelfMenuService.shelf.deleteShelf');
service.copyMagicShelfJson('{"rule":true}');
await Promise.resolve();
expect(editItem.disabled).toBe(true);
expect(deleteItem.disabled).toBe(true);
runCommand(editItem);
runCommand(deleteItem);
expect(dialogLauncherService.openShelfEditDialog).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
expect(writeText).toHaveBeenCalledWith('{"rule":true}');
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
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();
});
});
@@ -1,365 +1,230 @@
import { inject, Injectable } from '@angular/core';
import { ConfirmationService, MessageService } from '@openng/optimus-ui/api';
import { Router } from '@angular/router';
import { LibraryService } from './library.service';
import { ShelfService } from './shelf.service';
import { Library } from '../model/library.model';
import { Shelf } from '../model/shelf.model';
import { MetadataRefreshType } from '../../metadata/model/request/metadata-refresh-type.enum';
import { MagicShelf, MagicShelfService } from '../../magic-shelf/service/magic-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 { finalize } from 'rxjs';
import { DialogLauncherService } from '../../../shared/services/dialog-launcher.service';
import { BookDialogHelperService } from '../components/book-browser/book-dialog-helper.service';
import { TranslocoService } from '@jsverse/transloco';
import type { MenuItem } from '@openng/optimus-ui/api';
import {inject, Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {TranslocoService} from '@jsverse/transloco';
import {ConfirmationService, MessageService} from '@openng/optimus-ui/api';
import {finalize, type Observable} from 'rxjs';
@Injectable({
providedIn: 'root',
})
import {LoadingService} from '../../../core/services/loading.service';
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
import {LibraryService} from './library.service';
import {ShelfService} from './shelf.service';
type LibraryShelfActionTarget = Readonly<{id: number; name: string}>;
@Injectable({providedIn: 'root'})
export class LibraryShelfMenuService {
private confirmationService = inject(ConfirmationService);
private messageService = inject(MessageService);
private libraryService = inject(LibraryService);
private shelfService = inject(ShelfService);
private taskHelperService = inject(TaskHelperService);
private router = inject(Router);
private dialogLauncherService = inject(DialogLauncherService);
private magicShelfService = inject(MagicShelfService);
private userService = inject(UserService);
private loadingService = inject(LoadingService);
private bookDialogHelperService = inject(BookDialogHelperService);
private readonly confirmationService = inject(ConfirmationService);
private readonly messageService = inject(MessageService);
private readonly libraryService = inject(LibraryService);
private readonly shelfService = inject(ShelfService);
private readonly taskHelperService = inject(TaskHelperService);
private readonly router = inject(Router);
private readonly dialogLauncherService = inject(DialogLauncherService);
private readonly magicShelfService = inject(MagicShelfService);
private readonly loadingService = inject(LoadingService);
private readonly bookDialogHelperService = inject(BookDialogHelperService);
private readonly t = inject(TranslocoService);
initializeLibraryMenuItems(entity: Library | null): MenuItem[] {
const libraryId = entity?.id;
return [
{
label: this.t.translate('book.shelfMenuService.library.optionsLabel'),
items: [
{
label: this.t.translate('book.shelfMenuService.library.addPhysicalBook'),
icon: 'pi pi-book',
disabled: libraryId == null,
command: async () => {
if (libraryId == null) {
return;
}
await this.bookDialogHelperService.openAddPhysicalBookDialog(libraryId).catch(() => undefined);
}
},
{
label: this.t.translate('book.shelfMenuService.library.bulkIsbnImport'),
icon: 'pi pi-barcode',
disabled: libraryId == null,
command: async () => {
if (libraryId == null) {
return;
}
await this.bookDialogHelperService.openBulkIsbnImportDialog(libraryId).catch(() => undefined);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.editLibrary'),
icon: 'pi pi-pen-to-square',
disabled: libraryId == null,
command: () => {
if (libraryId == null) {
return;
}
void this.dialogLauncherService.openLibraryEditDialog(libraryId).catch(() => undefined);
}
},
{
label: this.t.translate('book.shelfMenuService.library.rescanLibrary'),
icon: 'pi pi-refresh',
disabled: libraryId == null,
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',
disabled: libraryId == null,
command: async () => {
if (libraryId == null) {
return;
}
await this.bookDialogHelperService.openMetadataRefreshDialogWithContext({
metadataRefreshType: MetadataRefreshType.LIBRARY,
libraryId
}).catch(() => undefined);
}
},
{
label: this.t.translate('book.shelfMenuService.library.autoFetchMetadata'),
icon: 'pi pi-bolt',
disabled: libraryId == null,
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: libraryId == null,
command: async () => {
if (libraryId == null) {
return;
}
await this.bookDialogHelperService.openDuplicateMergerDialog(libraryId).catch(() => undefined);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.deleteLibrary'),
icon: 'pi pi-trash',
disabled: libraryId == null,
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'),
});
}
});
}
});
}
}
]
}
];
addPhysicalBook(libraryId: number): void {
void this.bookDialogHelperService.openAddPhysicalBookDialog(libraryId);
}
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 || shelfId == null;
importIsbns(libraryId: number): void {
void this.bookDialogHelperService.openBulkIsbnImportDialog(libraryId);
}
const items: MenuItem[] = [
{
label: this.t.translate('book.shelfMenuService.shelf.editShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
if (shelfId == null) {
return;
}
editLibrary(libraryId: number): void {
void this.dialogLauncherService.openLibraryEditDialog(libraryId);
}
void this.dialogLauncherService.openShelfEditDialog(shelfId).catch(() => undefined);
}
rescanLibrary(library: LibraryShelfActionTarget): void {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.rescanLibraryMessage', {name: library.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
rejectLabel: this.t.translate('common.cancel'),
rejectButtonProps: {
severity: 'secondary',
},
{
separator: true
acceptButtonProps: {
severity: 'success',
},
{
label: this.t.translate('book.shelfMenuService.shelf.deleteShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
if (shelfId == null) {
return;
}
accept: () => {
this.libraryService.refreshLibrary(library.id).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.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'),
});
}
customFetchLibraryMetadata(libraryId: number): void {
void this.bookDialogHelperService.openMetadataRefreshDialogWithContext({
metadataRefreshType: MetadataRefreshType.LIBRARY,
libraryId,
});
}
autoFetchLibraryMetadata(libraryId: number): void {
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.LIBRARY,
libraryId,
}).subscribe();
}
findLibraryDuplicates(libraryId: number): void {
void this.bookDialogHelperService.openDuplicateMergerDialog(libraryId);
}
deleteLibrary(library: LibraryShelfActionTarget): void {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteLibraryMessage', {name: library.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
rejectButtonProps: {
severity: 'secondary',
},
acceptButtonProps: {
severity: 'danger',
},
accept: () => {
const loader = this.loadingService.show(
this.t.translate('book.shelfMenuService.loading.deletingLibrary', {name: library.name}),
);
this.libraryService.deleteLibrary(library.id)
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
complete: () => {
this.navigateHomeIfViewing(`/library/${library.id}/books`);
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'),
});
},
});
}
}
];
},
});
}
/* 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 }];
editShelf(shelfId: number): void {
void this.dialogLauncherService.openShelfEditDialog(shelfId);
}
deleteShelf(shelf: LibraryShelfActionTarget): void {
this.confirmShelfDeletion(shelf, () => this.shelfService.deleteShelf(shelf.id), {
targetUrl: `/shelf/${shelf.id}/books`,
confirm: 'book.shelfMenuService.confirm.deleteShelfMessage',
success: 'book.shelfMenuService.toast.shelfDeletedDetail',
failure: 'book.shelfMenuService.toast.shelfDeleteFailedDetail',
});
}
editMagicShelf(shelfId: number): void {
void this.dialogLauncherService.openMagicShelfEditDialog(shelfId);
}
copyMagicShelfJson(filterJson: string): void {
if (!navigator.clipboard) {
this.notifyJsonCopyFailed();
return;
}
return items;
void navigator.clipboard.writeText(filterJson).then(
() => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('common.success'),
detail: this.t.translate('book.shelfMenuService.toast.magicShelfJsonCopiedDetail'),
});
},
() => this.notifyJsonCopyFailed(),
);
}
initializeMagicShelfMenuItems(entity: MagicShelf | null): MenuItem[] {
const isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
const magicShelfId = entity?.id;
const isPublicShelf = entity?.isPublic ?? false;
const disableOptions = magicShelfId == null || (isPublicShelf && !isAdmin);
private notifyJsonCopyFailed(): void {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.magicShelfJsonCopyFailedDetail'),
});
}
return [
{
label: this.t.translate('book.shelfMenuService.magicShelf.editMagicShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
if (magicShelfId == null) {
return;
}
deleteMagicShelf(shelf: LibraryShelfActionTarget): void {
this.confirmShelfDeletion(shelf, () => this.magicShelfService.deleteShelf(shelf.id), {
targetUrl: `/magic-shelf/${shelf.id}/books`,
confirm: 'book.shelfMenuService.confirm.deleteMagicShelfMessage',
success: 'book.shelfMenuService.toast.magicShelfDeletedDetail',
failure: 'book.shelfMenuService.toast.magicShelfDeleteFailedDetail',
});
}
void this.dialogLauncherService.openMagicShelfEditDialog(magicShelfId).catch(() => undefined);
}
private confirmShelfDeletion(
shelf: LibraryShelfActionTarget,
deleteShelf: () => Observable<void>,
messages: Readonly<{targetUrl: string; confirm: string; success: string; failure: string}>,
): void {
this.confirmationService.confirm({
message: this.t.translate(messages.confirm, {name: shelf.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
severity: 'danger',
},
{
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')});
rejectButtonProps: {
severity: 'secondary',
},
accept: () => {
deleteShelf().subscribe({
complete: () => {
this.navigateHomeIfViewing(messages.targetUrl);
this.messageService.add({
severity: 'info',
summary: this.t.translate('common.success'),
detail: this.t.translate(messages.success),
});
}
}
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate(messages.failure),
});
},
});
},
{
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'),
});
}
});
}
});
}
}
];
private navigateHomeIfViewing(deletedTargetUrl: string): void {
const currentPath = this.router.url.replace(/[?#].*$/, '');
if (currentPath === deletedTargetUrl) {
void this.router.navigate(['/']);
}
}
}