From 0acd8bcb1ea8cbb3f3db4bdeec929b53141eb789 Mon Sep 17 00:00:00 2001 From: Alex <25013571+alexhb1@users.noreply.github.com> Date: Thu, 30 Jul 2026 20:47:24 +0100 Subject: [PATCH] refactor(ui): switch library and shelf menu to app-menu (#2057) --- .../book-browser/book-browser.component.html | 27 +- .../book-browser.component.spec.ts | 9 - .../book-browser/book-browser.component.ts | 33 +- .../library-shelf-menu.component.spec.ts | 82 +++ .../library-shelf-menu.component.ts | 157 +++++ .../library-shelf-menu.service.spec.ts | 248 +++----- .../service/library-shelf-menu.service.ts | 543 +++++++----------- .../app.sidebar-item-row.component.html | 45 +- .../app.sidebar-item-row.component.spec.ts | 97 +--- .../app.sidebar-item-row.component.ts | 30 +- .../layout-sidebar/app.sidebar.component.html | 32 +- .../layout-sidebar/app.sidebar.component.scss | 4 - .../app.sidebar.component.spec.ts | 9 - .../layout-sidebar/app.sidebar.component.ts | 59 +- .../layout-sidebar/sidebar-sections.spec.ts | 28 +- .../layout/layout-sidebar/sidebar-sections.ts | 23 +- .../layout/navigation/nav-catalog.spec.ts | 19 - .../shared/layout/navigation/nav-catalog.ts | 15 - .../layout/navigation/nav-item.model.ts | 4 +- .../src/app/shared/ui/menu/menu.styles.ts | 2 +- frontend/src/assets/styles/compat.scss | 9 - frontend/src/i18n/en/book.json | 1 + 22 files changed, 631 insertions(+), 845 deletions(-) create mode 100644 frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.spec.ts create mode 100644 frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.ts diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.html b/frontend/src/app/features/book/components/book-browser/book-browser.component.html index e3b8de086..f9e1ffec9 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.html +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.html @@ -28,19 +28,24 @@ } - @if (userService.currentUser(); as currentUser) { - @if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED && - (currentUser.permissions.admin || currentUser.permissions.canManageLibrary)) { -
- + + @if (entityMenu.available()) { +
- } + [attr.aria-label]="'common.moreActionsFor' | transloco: {label: menuTarget.entity.name}" + [appMenuTriggerFor]="entityMenu.menu()"> + + + } + } } diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts index b342982d5..0d3823e4b 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts @@ -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()}}, diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.ts b/frontend/src/app/features/book/components/book-browser/book-browser.component.ts index 7f0f808eb..f1d5f8faa 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.ts @@ -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(() => { + readonly entityMenuTarget = computed(() => { 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. diff --git a/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.spec.ts b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.spec.ts new file mode 100644 index 000000000..4eca99808 --- /dev/null +++ b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.spec.ts @@ -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; + 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); + }); +}); diff --git a/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.ts b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.ts new file mode 100644 index 000000000..6ec318374 --- /dev/null +++ b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.ts @@ -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 = Omit & {id: number}; + +export type LibraryShelfMenuTarget = + | {type: 'library'; entity: Persisted} + | {type: 'shelf'; entity: Persisted} + | {type: 'magicShelf'; entity: Persisted}; + +@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(); + + + @if (available()) { + @switch (currentTarget.type) { + @case ('library') { + + {{ 'book.shelfMenuService.library.addPhysicalBook' | transloco }} + + + {{ 'book.shelfMenuService.library.bulkIsbnImport' | transloco }} + + + + {{ 'book.shelfMenuService.library.editLibrary' | transloco }} + + + {{ 'book.shelfMenuService.library.rescanLibrary' | transloco }} + + + + {{ 'book.shelfMenuService.library.customFetchMetadata' | transloco }} + + + {{ 'book.shelfMenuService.library.autoFetchMetadata' | transloco }} + + + {{ 'book.shelfMenuService.library.findDuplicates' | transloco }} + + + + {{ 'book.shelfMenuService.library.deleteLibrary' | transloco }} + + } + @case ('shelf') { + @if (currentTarget.entity.publicShelf || !canManageShelf()) { + + @if (currentTarget.entity.publicShelf) { + {{ 'book.shelfMenuService.shelf.publicShelfPrefix' | transloco }} + } + {{ (canManageShelf() + ? 'book.shelfMenuService.shelf.optionsLabel' + : 'book.shelfMenuService.shelf.readOnly') | transloco }} + + } + + {{ 'book.shelfMenuService.shelf.editShelf' | transloco }} + + + + {{ 'book.shelfMenuService.shelf.deleteShelf' | transloco }} + + } + @case ('magicShelf') { + + {{ 'book.shelfMenuService.magicShelf.editMagicShelf' | transloco }} + + + {{ 'book.shelfMenuService.magicShelf.exportJson' | transloco }} + + + + {{ 'book.shelfMenuService.magicShelf.deleteMagicShelf' | transloco }} + + } + } + } + + + `, +}) +export class LibraryShelfMenuComponent { + readonly target = input.required(); + readonly ariaLabel = input.required(); + + readonly opened = output(); + readonly closed = output(); + 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); + }); +} diff --git a/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts b/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts index c742c83b3..06fe6e106 100644 --- a/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts +++ b/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts @@ -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 { - return { - id: 7, - name: 'Main Library', - watch: true, - paths: [], - ...overrides, - }; -} - -function buildShelf(overrides: Partial = {}): Shelf { - return { - id: 11, - name: 'Favorites', - userId: 3, - publicShelf: false, - ...overrides, - }; -} - -function buildMagicShelf(overrides: Partial = {}): 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(); - }); }); diff --git a/frontend/src/app/features/book/service/library-shelf-menu.service.ts b/frontend/src/app/features/book/service/library-shelf-menu.service.ts index 0be3d3090..30a72ecdb 100644 --- a/frontend/src/app/features/book/service/library-shelf-menu.service.ts +++ b/frontend/src/app/features/book/service/library-shelf-menu.service.ts @@ -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, + 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(['/']); + } } } diff --git a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.html b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.html index b8f8b197a..584cd055a 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.html +++ b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.html @@ -71,28 +71,29 @@ } - @if (shouldShowContextMenuButton()) { - - + @if (currentItem.menuTarget; as menuTarget) { + + + @if (entityMenu.available()) { + + } @else if (currentItem.bookCount) { +

{{ formatCount(currentItem.bookCount) }}

+ } } @else if (currentItem.bookCount) {

{{ formatCount(currentItem.bookCount) }}

} diff --git a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.spec.ts b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.spec.ts index ada7a083e..14e8cb3c9 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.spec.ts +++ b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.spec.ts @@ -1,104 +1,35 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { signal } from '@angular/core'; -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { AppSidebarItemRowComponent } from './app.sidebar-item-row.component'; -import { UserService } from '../../../features/settings/user-management/user.service'; -import { LayoutService } from '../layout.service'; +import {signal} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it} from 'vitest'; + +import {LayoutService} from '../layout.service'; +import {AppSidebarItemRowComponent} from './app.sidebar-item-row.component'; describe('AppSidebarItemRowComponent', () => { let fixture: ComponentFixture; let component: AppSidebarItemRowComponent; - - const layoutService = { - sidebarCollapsed: signal(false), - currentPath: signal('/'), - }; + const currentPath = signal('/'); beforeEach(() => { - TestBed.resetTestingModule(); TestBed.configureTestingModule({ imports: [AppSidebarItemRowComponent], - providers: [ - { - provide: UserService, - useValue: { - currentUser: signal({ - permissions: { - canManageLibrary: true, - admin: true, - }, - }), - }, - }, - { provide: LayoutService, useValue: layoutService }, - ], + providers: [{provide: LayoutService, useValue: {currentPath}}], }); - - TestBed.overrideComponent(AppSidebarItemRowComponent, { set: { template: '' } }); - + TestBed.overrideComponent(AppSidebarItemRowComponent, {set: {template: ''}}); fixture = TestBed.createComponent(AppSidebarItemRowComponent); component = fixture.componentInstance; fixture.componentRef.setInput('index', 0); fixture.componentRef.setInput('parentKey', 'home-0'); - layoutService.sidebarCollapsed.set(false); + fixture.componentRef.setInput('item', {id: 'dashboard', label: 'Dashboard', routerLink: ['/dashboard']}); }); - function setItem(item: Parameters['componentRef']['setInput']>[1]): void { - fixture.componentRef.setInput('item', item); - } - - it('passes context menu items through to the template', () => { - const editCommand = vi.fn(); - const nestedCommand = vi.fn(); - - const item = { - id: 'shelf-a', - label: 'Shelf A', - type: 'shelf', - contextMenuItems: [ - { label: 'Edit', command: editCommand }, - { label: 'More', items: [{ label: 'Delete', command: nestedCommand }] }, - ], - }; - setItem(item); - - fixture.detectChanges(); - - const items = component.item().contextMenuItems!; - expect(items[0].label).toBe('Edit'); - items[0].command?.({} as never); - expect(editCommand).toHaveBeenCalled(); - - expect(items[1].items?.[0].label).toBe('Delete'); - items[1].items?.[0].command?.({} as never); - expect(nestedCommand).toHaveBeenCalled(); - }); - - it('hides the context menu button for items without context menu actions', () => { - setItem({ id: 'unshelved', label: 'Unshelved', type: 'shelf' }); - fixture.detectChanges(); - expect(component.shouldShowContextMenuButton()).toBe(false); - }); - - it('exposes admin and canManipulateLibrary as computed signals from UserService', () => { - setItem({ id: 'test', label: 'Test' }); - fixture.detectChanges(); - expect(component.admin()).toBe(true); - expect(component.canManipulateLibrary()).toBe(true); - }); - - it('reports route as active when currentPath matches item routerLink', () => { - setItem({ id: 'dashboard', label: 'Dashboard', routerLink: ['/dashboard'] }); - layoutService.currentPath.set('/dashboard'); - fixture.detectChanges(); + it('reports route as active when the path matches', () => { + currentPath.set('/dashboard'); expect(component.isRouteActive()).toBe(true); }); - it('reports route as inactive when currentPath does not match', () => { - setItem({ id: 'dashboard', label: 'Dashboard', routerLink: ['/dashboard'] }); - layoutService.currentPath.set('/library/1/books'); - fixture.detectChanges(); + it('reports route as inactive when the path differs', () => { + currentPath.set('/library/1/books'); expect(component.isRouteActive()).toBe(false); }); - }); diff --git a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.ts b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.ts index 35d23c88d..6d5aff63f 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.ts +++ b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar-item-row.component.ts @@ -1,15 +1,15 @@ import { ChangeDetectionStrategy, Component, computed, inject, input, signal } from '@angular/core'; import { RouterLink } from '@angular/router'; -import { Menu } from '@openng/optimus-ui/menu'; import { Tooltip } from '@openng/optimus-ui/tooltip'; import { TranslocoPipe } from '@jsverse/transloco'; import { LucideEllipsisVertical } from '@lucide/angular'; import { IconSelection, toIconSelection } from '../../icons/icon-selection'; -import { UserService } from '../../../features/settings/user-management/user.service'; import { IconDisplayComponent } from '../../components/icon-display/icon-display.component'; import { LayoutService } from '../layout.service'; import { SidebarLeaf } from '../navigation/nav-item.model'; +import {LibraryShelfMenuComponent} from '../../../features/book/components/library-shelf-menu/library-shelf-menu.component'; +import {AppMenuTriggerDirective} from '../../ui/menu/app-menu-trigger.directive'; @Component({ // Attribute selector so the row renders into its host
  • inside a
      . @@ -19,7 +19,8 @@ import { SidebarLeaf } from '../navigation/nav-item.model'; styleUrls: ['./app.sidebar-item-row.component.scss'], imports: [ RouterLink, - Menu, + LibraryShelfMenuComponent, + AppMenuTriggerDirective, IconDisplayComponent, Tooltip, TranslocoPipe, @@ -35,7 +36,6 @@ export class AppSidebarItemRowComponent { readonly menuOpen = signal(false); readonly key = computed(() => `${this.parentKey()}-${this.index()}`); - private readonly userService = inject(UserService); readonly layoutService = inject(LayoutService); readonly isRouteActive = computed(() => { @@ -44,23 +44,11 @@ export class AppSidebarItemRowComponent { return this.layoutService.currentPath() === route; }); - readonly canManipulateLibrary = computed(() => - this.userService.currentUser()?.permissions.canManageLibrary ?? false - ); - - readonly admin = computed(() => - this.userService.currentUser()?.permissions.admin ?? false - ); - runAction(event: Event): void { event.preventDefault(); this.item().action?.(); } - openContextMenu(event: Event, menu: Menu): void { - menu.toggle(event); - } - markContextMenuOpen(): void { this.menuOpen.set(true); } @@ -75,16 +63,6 @@ export class AppSidebarItemRowComponent { return toIconSelection(item.icon, item.iconType); } - hasContextMenu(): boolean { - return (this.item().contextMenuItems?.length ?? 0) > 0; - } - - shouldShowContextMenuButton(): boolean { - const item = this.item(); - return this.hasContextMenu() - && (item.type !== 'library' || (this.admin() || this.canManipulateLibrary())); - } - formatCount(count: number | null | undefined): string { if (!count) return ''; if (count >= 1000) return Math.floor(count / 100) / 10 + 'K'; diff --git a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.html b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.html index 62186d5c9..16af46845 100644 --- a/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.html +++ b/frontend/src/app/shared/layout/layout-sidebar/app.sidebar.component.html @@ -55,22 +55,28 @@ [tooltipDisabled]="!layoutService.isDesktop()" tooltipPosition="bottom" [attr.aria-label]="t('add')" - aria-haspopup="menu" - [attr.aria-expanded]="addMenuOpen() ? 'true' : 'false'" - (click)="toggleAddMenu($event, addMenu)" + [appMenuTriggerFor]="addMenu" > - + [ariaLabel]="t('add')"> + @if (currentUser(); as user) { + @if (user.permissions.admin || user.permissions.canManageLibrary) { + + {{ t('createLibrary') }} + + } + + {{ 'book.shelfCreator.title' | transloco }} + + + {{ t('createMagicShelf') }} + + } + @if (canUploadBooks()) {