diff --git a/frontend/src/app/app.routes.spec.ts b/frontend/src/app/app.routes.spec.ts index 9443a8a30..608c66139 100644 --- a/frontend/src/app/app.routes.spec.ts +++ b/frontend/src/app/app.routes.spec.ts @@ -26,18 +26,25 @@ describe('app routes', () => { it('defines the authenticated shell routes behind the auth guard', () => { const shellRoute = routes.find(route => route.path === '' && Array.isArray(route.children)); const children = shellRoute?.children ?? []; + const browsePage = (path: string) => children.find(route => route.path === path) + ?.children?.find(route => route.path === ''); + const browseFilterPage = (path: string) => children.find(route => route.path === path) + ?.children?.find(route => route.path === 'filter'); expect(children).toHaveLength(21); + expect(children.find(route => route.path === 'browse/filter')).toBeUndefined(); expect(shellRoute?.canActivateChild).toEqual([AuthChildGuard]); expect(children.find(route => route.path === 'dashboard')?.canActivate).toBeUndefined(); expect(children.find(route => route.path === 'all-books')?.canActivate).toBeUndefined(); expect(children.find(route => route.path === 'magic-shelf/:magicShelfId/books')?.canActivate).toBeUndefined(); expect(children.find(route => route.path === 'notebook')?.canActivate).toBeUndefined(); - expect(typeof children.find(route => route.path === 'all-books')?.loadComponent).toBe('function'); - expect(typeof children.find(route => route.path === 'library/:libraryId/books')?.loadComponent).toBe('function'); - expect(typeof children.find(route => route.path === 'shelf/:shelfId/books')?.loadComponent).toBe('function'); - expect(typeof children.find(route => route.path === 'unshelved-books')?.loadComponent).toBe('function'); - expect(typeof children.find(route => route.path === 'magic-shelf/:magicShelfId/books')?.loadComponent).toBe('function'); + expect(typeof browsePage('all-books')?.loadComponent).toBe('function'); + expect(typeof browseFilterPage('all-books')?.loadComponent).toBe('function'); + expect(children.find(route => route.path === 'browse')).toBeUndefined(); + expect(typeof browsePage('library/:libraryId/books')?.loadComponent).toBe('function'); + expect(typeof browsePage('shelf/:shelfId/books')?.loadComponent).toBe('function'); + expect(typeof browsePage('unshelved-books')?.loadComponent).toBe('function'); + expect(typeof browsePage('magic-shelf/:magicShelfId/books')?.loadComponent).toBe('function'); expect(typeof children.find(route => route.path === 'design-system')?.loadComponent).toBe('function'); expect(typeof children.find(route => route.path === 'design-system/form/library')?.loadComponent).toBe('function'); expect(typeof children.find(route => route.path === 'design-system/form/device')?.loadComponent).toBe('function'); diff --git a/frontend/src/app/app.routes.ts b/frontend/src/app/app.routes.ts index 3377db276..029d2b9f7 100644 --- a/frontend/src/app/app.routes.ts +++ b/frontend/src/app/app.routes.ts @@ -14,9 +14,17 @@ import {BookdropGuard} from './core/security/guards/bookdrop.guard'; import {LibraryStatsGuard} from './core/security/guards/library-stats.guard'; import {UserStatsGuard} from './core/security/guards/user-stats.guard'; import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard'; +import {validBookBrowseScope, type BookBrowseRouteData} from './features/book/browse/book-browse-scope'; -const loadBookBrowserComponent = () => - import('./features/book/components/book-browser/book-browser.component').then(m => m.BookBrowserComponent); +const loadBookBrowsePage = () => + import('./features/book/browse/book-browse-page.component').then(m => m.BookBrowsePageComponent); +const loadBookBrowseFilterPage = () => + import('./features/book/browse/book-browse-filter-page.component').then(m => m.BookBrowseFilterPageComponent); + +const bookBrowseRoutes = (data: BookBrowseRouteData = {}) => [ + {path: '', loadComponent: loadBookBrowsePage, ...(data.browseScope ? {data} : {})}, + {path: 'filter', loadComponent: loadBookBrowseFilterPage, ...(data.browseScope ? {data} : {})}, +]; export const routes: Routes = [ { @@ -37,16 +45,16 @@ export const routes: Routes = [ canActivateChild: [AuthChildGuard], children: [ {path: 'dashboard', component: MainDashboardComponent}, - {path: 'all-books', loadComponent: loadBookBrowserComponent}, + {path: 'all-books', children: bookBrowseRoutes()}, {path: 'settings', loadComponent: () => import('./features/settings/settings.component').then(m => m.SettingsComponent)}, - {path: 'library/:libraryId/books', loadComponent: loadBookBrowserComponent}, - {path: 'shelf/:shelfId/books', loadComponent: loadBookBrowserComponent}, - {path: 'unshelved-books', loadComponent: loadBookBrowserComponent}, + {path: 'library/:libraryId/books', canActivateChild: [validBookBrowseScope], children: bookBrowseRoutes()}, + {path: 'shelf/:shelfId/books', canActivateChild: [validBookBrowseScope], children: bookBrowseRoutes()}, + {path: 'unshelved-books', children: bookBrowseRoutes({browseScope: 'unshelved'})}, {path: 'series', loadComponent: () => import('./features/series-browser/components/series-browser/series-browser.component').then(m => m.SeriesBrowserComponent)}, {path: 'series/:seriesName', loadComponent: () => import('./features/book/components/series-page/series-page.component').then(m => m.SeriesPageComponent)}, {path: 'authors', loadComponent: () => import('./features/author-browser/components/author-browser/author-browser.component').then(m => m.AuthorBrowserComponent)}, {path: 'author/:authorId', loadComponent: () => import('./features/author-browser/components/author-detail/author-detail.component').then(m => m.AuthorDetailComponent)}, - {path: 'magic-shelf/:magicShelfId/books', loadComponent: loadBookBrowserComponent}, + {path: 'magic-shelf/:magicShelfId/books', canActivateChild: [validBookBrowseScope], children: bookBrowseRoutes()}, {path: 'book/:bookId', loadComponent: () => import('./features/metadata/component/book-metadata-center/book-metadata-center.component').then(m => m.BookMetadataCenterComponent)}, {path: 'bookdrop', loadComponent: () => import('./features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component').then(m => m.BookdropFileReviewComponent), canActivate: [BookdropGuard]}, {path: 'metadata-manager', loadComponent: () => import('./features/metadata/component/metadata-manager/metadata-manager.component').then(m => m.MetadataManagerComponent), canActivate: [EditMetadataGuard]}, diff --git a/frontend/src/app/features/book/browse/book-browse-bulk-bar.component.html b/frontend/src/app/features/book/browse/book-browse-bulk-bar.component.html new file mode 100644 index 000000000..634844853 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-bulk-bar.component.html @@ -0,0 +1,143 @@ +@if (selection().active()) { + + + + + + + + @if (bulkPermissions().canEditMetadata) { + + + + } + @if (bulkMetadataAvailable()) { + + + + } + @if (actionPermissions().canDeleteBook) { + + + + + } + + + + + + @for (status of readStatusTargets; track status) { + {{ statusLabelKey(status) | transloco }} + } + + + {{ clearReadStatusLabelKey | transloco }} + + + + + {{ 'browse.bulk.editAll' | transloco }} + {{ 'browse.bulk.editOneByOne' | transloco }} + + + + @if (bulkPermissions().canAutoFetchMetadata) { + {{ 'book.menu.fetchMetadata' | transloco }} + } + @if (bulkPermissions().canCustomFetchMetadata) { + {{ 'book.menu.fetchMetadataWithOptions' | transloco }} + } + + @if (bulkPermissions().canLockUnlockMetadata) { + {{ 'metadata.editor.lockAllBtn' | transloco }} + {{ 'metadata.editor.unlockAllBtn' | transloco }} + {{ 'browse.bulk.lockUnlockMetadata' | transloco }} + } + + @if (bulkPermissions().canRegenerateCover) { + {{ 'book.menu.restoreCover' | transloco }} + {{ 'book.menu.generateCover' | transloco }} + } + + + + @if (overflowed().has('addToShelf')) { + {{ 'book.menu.addToShelf' | transloco }} + } + @if (overflowed().has('markAs')) { + {{ 'book.menu.markAs' | transloco }} + } + @if (overflowed().has('edit')) { + {{ 'common.edit' | transloco }} + } + @if (overflowed().has('metadata')) { + {{ 'book.menu.metadata' | transloco }} + } + + @if (actionPermissions().canResetGrimmoryProgress) { + {{ 'book.menu.resetGrimmoryProgress' | transloco }} + } + @if (actionPermissions().canResetKoreaderProgress) { + {{ 'book.menu.resetKoreaderProgress' | transloco }} + } + + @if (bulkPermissions().canOrganizeFiles) { + {{ 'browse.bulk.organizeFiles' | transloco }} + } + @if (bulkPermissions().canAttachFiles) { + + {{ 'book.fileAttacher.attachFilesBulk' | transloco }} + + } + + @if (overflowed().has('delete')) { + + {{ 'common.delete' | transloco }} + + } + +} diff --git a/frontend/src/app/features/book/browse/book-browse-bulk-bar.component.spec.ts b/frontend/src/app/features/book/browse/book-browse-bulk-bar.component.spec.ts new file mode 100644 index 000000000..3cf338f31 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-bulk-bar.component.spec.ts @@ -0,0 +1,152 @@ +import {signal, type WritableSignal} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {ConfirmationService, MessageService} from '@openng/optimus-ui/api'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; + +import {createQueryClientHarness, flushQueryAsync} from '../../../core/testing/query-testing'; +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {type BrowseSelection, type BrowseSelectionState} from '../../../shared/browse/selection'; +import {AppSettingsService} from '../../../shared/service/app-settings.service'; +import {UserService} from '../../settings/user-management/user.service'; +import {type BookSummary} from '../data/book-response.models'; +import {ShelfDefinitionQueryService} from '../data/shelf-definition-query.service'; +import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service'; +import {BookBrowseBulkBarComponent} from './book-browse-bulk-bar.component'; + +function selectionOf(ids: readonly number[]): BrowseSelection { + const selected = new Set(ids); + return { + state: signal({mode: 'explicit', ids: selected}), + count: signal(ids.length), + active: signal(true), + allMatchingSelected: signal(false), + isSelected: id => selected.has(id), + toggle: vi.fn(), + selectAll: vi.fn(), + clear: vi.fn(), + pruneDeleted: vi.fn(), + }; +} + +function book(id: number, libraryId = 1): BookSummary { + return {id, libraryId, libraryName: `Library ${libraryId}`}; +} + +function user(permissions: Record, id = 1) { + return {id, permissions}; +} + +describe('BookBrowseBulkBarComponent', () => { + let fixture: ComponentFixture; + let currentUser: WritableSignal | null>; + let appSettings: WritableSignal<{diskType: string}>; + let shelfDefinitions: {id: number; userId: number; name: string}[]; + + function mount(books: BookSummary[], selectedIds: number[]): BookBrowseBulkBarComponent { + fixture = TestBed.createComponent(BookBrowseBulkBarComponent); + fixture.componentRef.setInput('selection', selectionOf(selectedIds)); + fixture.componentRef.setInput('books', books); + fixture.componentRef.setInput('total', books.length); + fixture.componentRef.setInput('fetchIds', () => Promise.resolve([])); + fixture.detectChanges(); + return fixture.componentInstance; + } + + beforeEach(() => { + const harness = createQueryClientHarness(); + currentUser = signal(null); + appSettings = signal({diskType: 'LOCAL'}); + shelfDefinitions = []; + + TestBed.configureTestingModule({ + imports: [BookBrowseBulkBarComponent, getTranslocoModule()], + providers: [ + ...harness.providers, + {provide: UserService, useValue: {currentUser}}, + {provide: AppSettingsService, useValue: {appSettings}}, + { + provide: ShelfDefinitionQueryService, + useValue: { + definitions: () => ({ + queryKey: ['shelves', 'query', 'definitions'] as const, + queryFn: () => Promise.resolve(shelfDefinitions), + }), + }, + }, + {provide: BookDialogHelperService, useValue: {}}, + {provide: ConfirmationService, useValue: {confirm: vi.fn()}}, + {provide: MessageService, useValue: {add: vi.fn()}}, + ], + }).overrideComponent(BookBrowseBulkBarComponent, { + set: {template: '', imports: []}, + }); + }); + + it('allows only the metadata actions the user is permitted', () => { + currentUser.set(user({canBulkLockUnlockMetadata: true})); + const bar = mount([book(1)], [1]); + + expect(bar['bulkMetadataAvailable']()).toBe(true); + expect(bar['bulkPermissions']()).toMatchObject({ + canLockUnlockMetadata: true, + canAutoFetchMetadata: false, + canCustomFetchMetadata: false, + canRegenerateCover: false, + }); + + currentUser.set(user({ + canBulkAutoFetchMetadata: true, + canBulkCustomFetchMetadata: true, + canBulkRegenerateCover: true, + })); + + expect(bar['bulkPermissions']()).toMatchObject({ + canLockUnlockMetadata: false, + canAutoFetchMetadata: true, + canCustomFetchMetadata: true, + canRegenerateCover: true, + }); + + currentUser.set(user({})); + expect(bar['bulkMetadataAvailable']()).toBe(false); + }); + + it('requires permission and one library to attach files, and local disk to organize files', () => { + currentUser.set(user({canManageLibrary: true})); + const bar = mount([book(1, 1), book(2, 2)], [1, 2]); + expect(bar['bulkPermissions']().canAttachFiles).toBe(true); + expect(bar['bulkAttachEligible']()).toBe(false); + + fixture.componentRef.setInput('books', [book(1), book(2)]); + expect(bar['bulkAttachEligible']()).toBe(true); + + fixture.componentRef.setInput('books', [book(1)]); + expect(bar['bulkAttachEligible']()).toBe(false); + + currentUser.set(user({canMoveOrganizeFiles: true})); + expect(bar['bulkPermissions']().canAttachFiles).toBe(false); + appSettings.set({diskType: 'S3'}); + expect(bar['bulkPermissions']().canOrganizeFiles).toBe(false); + + appSettings.set({diskType: 'LOCAL'}); + expect(bar['bulkPermissions']().canOrganizeFiles).toBe(true); + + currentUser.set(user({})); + expect(bar['bulkPermissions']().canOrganizeFiles).toBe(false); + }); + + it('offers only the current user shelves for bulk assignment', async () => { + currentUser.set(user({}, 7)); + shelfDefinitions = [ + {id: 5, userId: 7, name: 'Mine'}, + {id: 6, userId: 9, name: 'Shared by someone else'}, + ]; + const bar = mount([book(1)], [1]); + await flushQueryAsync(); + + expect(bar['bulkShelves']().map(shelf => shelf.id)).toEqual([5]); + + currentUser.set(user({}, 9)); + expect(bar['bulkShelves']().map(shelf => shelf.id)).toEqual([6]); + }); +}); diff --git a/frontend/src/app/features/book/browse/book-browse-bulk-bar.component.ts b/frontend/src/app/features/book/browse/book-browse-bulk-bar.component.ts new file mode 100644 index 000000000..977aaf73b --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-bulk-bar.component.ts @@ -0,0 +1,165 @@ +import {Component, computed, inject, input, viewChild} from '@angular/core'; +import {TranslocoPipe} from '@jsverse/transloco'; +import {injectQuery} from '@tanstack/angular-query-experimental'; +import {LucideBookmark, LucideCheck, LucideDatabase, LucidePenLine} from '@lucide/angular'; + +import { + bookActionPermissions, +} from '../data/book-actions'; +import { + BOOK_READ_STATUS_LABEL_KEYS, + BOOK_READ_STATUS_TARGETS, + CLEAR_BOOK_READ_STATUS, + CLEAR_BOOK_READ_STATUS_LABEL_KEY, + type BookReadStatusTarget, +} from '../components/book-read-status-options'; +import { + BrowseBulkActionsBarComponent, + BrowseBulkActionsDividerComponent, + BrowseBulkActionsItemDirective, +} from '../../../shared/browse/bulk-actions/bulk-actions-bar.component'; +import {ShelfMembershipMenuComponent} from '../../../shared/components/shelf-menu/shelf-membership-menu.component'; +import {AppButtonComponent} from '../../../shared/ui/button/app-button.component'; +import {AppMenuComponent} from '../../../shared/ui/menu/app-menu.component'; +import {AppMenuItemComponent} from '../../../shared/ui/menu/app-menu-item.component'; +import {AppMenuSeparatorComponent} from '../../../shared/ui/menu/app-menu-separator.component'; +import {AppMenuTriggerDirective} from '../../../shared/ui/menu/app-menu-trigger.directive'; +import {AppSettingsService} from '../../../shared/service/app-settings.service'; +import { + injectPendingBookDeletions, + injectPendingBookShelfMembership, + overlayShelfIds, +} from '../data/book-command-pending-state'; +import {type BookSummary} from '../data/book-response.models'; +import {ShelfDefinitionQueryService} from '../data/shelf-definition-query.service'; +import {UserService} from '../../settings/user-management/user.service'; +import {type BrowseSelection} from '../../../shared/browse/selection'; +import {createBookBrowseBulkCommands} from './book-browse-bulk-commands'; + +const NO_OVERFLOW: ReadonlySet = new Set(); + +@Component({ + selector: 'app-book-browse-bulk-bar', + host: {class: 'contents'}, + imports: [ + TranslocoPipe, + AppButtonComponent, + AppMenuComponent, + AppMenuItemComponent, + AppMenuSeparatorComponent, + AppMenuTriggerDirective, + BrowseBulkActionsBarComponent, + BrowseBulkActionsDividerComponent, + BrowseBulkActionsItemDirective, + ShelfMembershipMenuComponent, + LucideBookmark, + LucideCheck, + LucideDatabase, + LucidePenLine, + ], + templateUrl: './book-browse-bulk-bar.component.html', +}) +export class BookBrowseBulkBarComponent { + readonly selection = input.required(); + readonly books = input.required(); + readonly total = input.required(); + readonly fetchIds = input.required<() => Promise>(); + + private readonly userService = inject(UserService); + private readonly appSettingsService = inject(AppSettingsService); + private readonly shelfDefinitionQuery = inject(ShelfDefinitionQueryService); + protected readonly commands = createBookBrowseBulkCommands({ + selection: this.selection, + books: this.books, + fetchIds: this.fetchIds, + }); + + private readonly shelfDefinitionsQuery = injectQuery(() => this.shelfDefinitionQuery.definitions()); + private readonly pendingShelfMembership = injectPendingBookShelfMembership(); + private readonly pendingDeletions = injectPendingBookDeletions(); + + private readonly bulkBar = viewChild(BrowseBulkActionsBarComponent); + protected readonly overflowed = computed(() => this.bulkBar()?.overflowed() ?? NO_OVERFLOW); + protected readonly isResolving = this.commands.isResolving; + protected readonly readStatusTargets = BOOK_READ_STATUS_TARGETS; + protected readonly clearReadStatus = CLEAR_BOOK_READ_STATUS; + protected readonly clearReadStatusLabelKey = CLEAR_BOOK_READ_STATUS_LABEL_KEY; + protected readonly autoSeparatorClass = + 'first:hidden [app-menu-separator+&]:hidden [&:not(:has(~:not(app-menu-separator)))]:hidden'; + + protected readonly actionPermissions = computed(() => + bookActionPermissions(this.userService.currentUser()?.permissions)); + protected readonly bulkPermissions = computed(() => { + const permissions = this.userService.currentUser()?.permissions; + const admin = !!permissions?.admin; + return { + canAutoFetchMetadata: admin || !!permissions?.canBulkAutoFetchMetadata, + canCustomFetchMetadata: admin || !!permissions?.canBulkCustomFetchMetadata, + canEditMetadata: admin || !!permissions?.canBulkEditMetadata, + canRegenerateCover: admin || !!permissions?.canBulkRegenerateCover, + canLockUnlockMetadata: admin || !!permissions?.canBulkLockUnlockMetadata, + canOrganizeFiles: this.actionPermissions().canOrganizeFiles + && this.appSettingsService.appSettings()?.diskType === 'LOCAL', + canAttachFiles: admin || !!permissions?.canManageLibrary, + }; + }); + + private readonly selectedLoadedBooks = computed(() => { + const selection = this.selection(); + return this.books().filter(book => selection.isSelected(book.id)); + }); + private readonly allSelectedLoaded = computed(() => + this.selectedLoadedBooks().length === this.selection().count()); + + protected readonly bulkShelves = computed(() => { + const selectedBooks = this.selectedLoadedBooks(); + const allLoaded = this.allSelectedLoaded(); + const currentUserId = this.userService.currentUser()?.id; + const pendingShelfMembership = this.pendingShelfMembership(); + const shelfIdsByBook = selectedBooks.map(book => + overlayShelfIds(book, pendingShelfMembership.get(book.id)), + ); + return (this.shelfDefinitionsQuery.data() ?? []) + .filter(shelf => shelf.userId === currentUserId) + .map(shelf => { + let onCount = 0; + for (const shelfIds of shelfIdsByBook) { + if (shelfIds.has(shelf.id)) { + onCount++; + } + } + const checked = allLoaded && selectedBooks.length > 0 && onCount === selectedBooks.length; + return { + id: shelf.id, + name: shelf.name, + checked, + mixed: !checked && (onCount > 0 || !allLoaded), + }; + }); + }); + protected readonly bulkShelfIds = computed(() => this.bulkShelves().map(shelf => shelf.id)); + + protected readonly bulkMetadataAvailable = computed(() => { + const permissions = this.bulkPermissions(); + return permissions.canAutoFetchMetadata + || permissions.canCustomFetchMetadata + || permissions.canRegenerateCover + || permissions.canLockUnlockMetadata; + }); + protected readonly bulkAttachEligible = computed(() => + this.allSelectedLoaded() + && new Set(this.selectedLoadedBooks().map(book => book.libraryId)).size === 1, + ); + protected readonly moreMenuOnlyItems = computed(() => { + const permissions = this.actionPermissions(); + return permissions.canResetGrimmoryProgress + || permissions.canResetKoreaderProgress + || this.bulkPermissions().canOrganizeFiles + || this.bulkPermissions().canAttachFiles; + }); + protected readonly bulkDeleting = computed(() => this.pendingDeletions().size > 0); + + protected statusLabelKey(status: BookReadStatusTarget): string { + return BOOK_READ_STATUS_LABEL_KEYS[status]; + } +} diff --git a/frontend/src/app/features/book/browse/book-browse-bulk-commands.spec.ts b/frontend/src/app/features/book/browse/book-browse-bulk-commands.spec.ts new file mode 100644 index 000000000..924a5a506 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-bulk-commands.spec.ts @@ -0,0 +1,111 @@ +import {HttpTestingController} from '@angular/common/http/testing'; +import {signal} from '@angular/core'; +import {TestBed} from '@angular/core/testing'; +import {ConfirmationService, MessageService} from '@openng/optimus-ui/api'; +import {Subject} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {createQueryClientHarness, flushQueryAsync} from '../../../core/testing/query-testing'; +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {API_CONFIG} from '../../../core/config/api-config'; +import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service'; +import {type BrowseSelection, type BrowseSelectionState} from '../../../shared/browse/selection'; +import {createBookBrowseBulkCommands} from './book-browse-bulk-commands'; + +function selection(ids: readonly number[]): BrowseSelection { + const selected = new Set(ids); + return { + state: signal({mode: 'explicit', ids: selected}), + count: signal(ids.length), + active: signal(ids.length > 0), + allMatchingSelected: signal(false), + isSelected: id => selected.has(id), + toggle: vi.fn(), + selectAll: vi.fn(), + clear: vi.fn(), + pruneDeleted: vi.fn(), + }; +} + +describe('createBookBrowseBulkCommands', () => { + let http: HttpTestingController; + let dialogHelper: Record< + 'openBulkMetadataEditDialog' | 'openMultibookMetadataEditorDialog' | + 'openLockUnlockMetadataDialog' | 'openFileMoverDialog' | 'openBulkBookFileAttacherDialog', + ReturnType + >; + + function commandsFor(selected: BrowseSelection) { + return TestBed.runInInjectionContext(() => + createBookBrowseBulkCommands({ + selection: signal(selected), + books: signal([]), + fetchIds: signal(vi.fn()), + })); + } + type Commands = ReturnType; + + beforeEach(() => { + const harness = createQueryClientHarness(); + dialogHelper = { + openBulkMetadataEditDialog: vi.fn().mockResolvedValue(null), + openMultibookMetadataEditorDialog: vi.fn().mockResolvedValue(null), + openLockUnlockMetadataDialog: vi.fn().mockResolvedValue(null), + openFileMoverDialog: vi.fn().mockResolvedValue(null), + openBulkBookFileAttacherDialog: vi.fn().mockResolvedValue(null), + }; + + TestBed.configureTestingModule({ + imports: [getTranslocoModule()], + providers: [ + ...harness.providers, + {provide: BookDialogHelperService, useValue: dialogHelper}, + {provide: ConfirmationService, useValue: {confirm: vi.fn()}}, + {provide: MessageService, useValue: {add: vi.fn()}}, + ], + }); + http = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + http.verify(); + vi.restoreAllMocks(); + }); + + it.each([ + {name: 'bulk metadata editor', clears: true, dialog: () => dialogHelper.openBulkMetadataEditDialog, + run: (commands: Commands) => commands.editAll()}, + {name: 'one-by-one metadata editor', clears: true, dialog: () => dialogHelper.openMultibookMetadataEditorDialog, + run: (commands: Commands) => commands.editOneByOne()}, + {name: 'Lock/Unlock metadata dialog', clears: true, dialog: () => dialogHelper.openLockUnlockMetadataDialog, + run: (commands: Commands) => commands.lockUnlockMetadata()}, + {name: 'file organizer', clears: false, dialog: () => dialogHelper.openFileMoverDialog, + run: (commands: Commands) => commands.organizeFiles()}, + ])('opens the $name with resolved IDs', async ({clears, dialog, run}) => { + const onClose = new Subject(); + dialog().mockResolvedValue({onClose}); + const selected = selection([11, 12]); + + run(commandsFor(selected)); + + await vi.waitFor(() => expect(dialog()).toHaveBeenCalledOnce()); + expect([...dialog().mock.calls[0][0]]).toEqual([11, 12]); + onClose.next(); + expect(selected.clear).toHaveBeenCalledTimes(clears ? 1 : 0); + }); + + it('removes every supplied shelf in one membership mutation', async () => { + commandsFor(selection([61, 62])).removeFromAllShelves([7, 8]); + await flushQueryAsync(1); + + const request = http.expectOne(`${API_CONFIG.BASE_URL}/api/v1/books/shelves`); + expect(request.request.body).toEqual({ + bookIds: [61, 62], + shelvesToAssign: [], + shelvesToUnassign: [7, 8], + }); + request.flush([]); + await flushQueryAsync(1); + }); + +}); diff --git a/frontend/src/app/features/book/browse/book-browse-bulk-commands.ts b/frontend/src/app/features/book/browse/book-browse-bulk-commands.ts new file mode 100644 index 000000000..b44a78bc1 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-bulk-commands.ts @@ -0,0 +1,219 @@ +import {inject, signal, type Signal} from '@angular/core'; +import {TranslocoService} from '@jsverse/transloco'; +import {ConfirmationService, MessageService} from '@openng/optimus-ui/api'; +import {type DynamicDialogRef} from '@openng/optimus-ui/dynamicdialog'; +import {injectMutation} from '@tanstack/angular-query-experimental'; +import {take} from 'rxjs/operators'; + +import { + BOOK_READ_STATUS_LABEL_KEYS, + CLEAR_BOOK_READ_STATUS_LABEL_KEY, +} from '../components/book-read-status-options'; +import {DeleteBooksPartialError, type BookProgressSource} from '../data/book-command.models'; +import {BookBackgroundSubmissionService} from '../data/book-background-submission.service'; +import {BookCommandService} from '../data/book-command.service'; +import {BookShelfCommandService} from '../data/book-shelf-command.service'; +import {type BookSummary, type KnownBookReadStatus} from '../data/book-response.models'; +import {MetadataRefreshSubmissionService} from '../../metadata/data/metadata-refresh-submission.service'; +import {type BookFileAttacherSourceBook} from '../components/book-file-attacher/book-file-attacher.component'; +import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service'; +import {legacyBookCachePatches, withLegacyBookCache} from '../service/book-command-legacy-adapter'; +import {resolveSelectedIds, type BrowseSelection} from '../../../shared/browse/selection'; + +type FetchMatchingIds = () => Promise; + +export interface BookBrowseBulkCommandsOptions { + readonly selection: Signal; + readonly books: Signal; + readonly fetchIds: Signal; +} + +export function createBookBrowseBulkCommands({selection, books, fetchIds}: BookBrowseBulkCommandsOptions) { + const transloco = inject(TranslocoService); + const dialogHelper = inject(BookDialogHelperService); + const metadataRefresh = inject(MetadataRefreshSubmissionService); + const backgroundSubmission = inject(BookBackgroundSubmissionService); + const confirmationService = inject(ConfirmationService); + const messageService = inject(MessageService); + const bookCommands = inject(BookCommandService); + const shelfCommands = inject(BookShelfCommandService); + + const shelfMembershipMutation = injectMutation(() => withLegacyBookCache( + shelfCommands.updateMembership(), legacyBookCachePatches.shelfMembership)); + const readStatusMutation = injectMutation(() => withLegacyBookCache( + bookCommands.setReadStatus(), legacyBookCachePatches.readStatus)); + const refreshMetadataMutation = injectMutation(() => metadataRefresh.refreshMetadata()); + const deleteBooksMutation = injectMutation(() => withLegacyBookCache( + bookCommands.deleteBooks(), legacyBookCachePatches.deleteBooks)); + const resetProgressMutation = injectMutation(() => withLegacyBookCache( + bookCommands.resetProgress(), legacyBookCachePatches.resetProgress)); + const metadataLocksMutation = injectMutation(() => withLegacyBookCache( + bookCommands.setAllMetadataLocks(), legacyBookCachePatches.metadataAllLocks)); + const changeCoversMutation = injectMutation(() => backgroundSubmission.changeCovers()); + + const isResolving = signal(false); + + async function withSelectedBookIds(run: (bookIds: readonly number[]) => void): Promise { + if (isResolving()) { + return; + } + isResolving.set(true); + let bookIds: readonly number[]; + try { + bookIds = await resolveSelectedIds(selection().state(), fetchIds()); + } catch { + messageService.add({ + severity: 'error', + summary: transloco.translate('browse.bulk.selectionLoadError'), + }); + return; + } finally { + isResolving.set(false); + } + if (bookIds.length === 0) { + selection().clear(); + messageService.add({ + severity: 'info', + summary: transloco.translate('browse.bulk.selectionEmpty'), + }); + return; + } + run(bookIds); + } + + function openThenClear(open: (bookIds: Set) => Promise): void { + void withSelectedBookIds(bookIds => void open(new Set(bookIds)) + .then(ref => ref?.onClose.pipe(take(1)).subscribe(() => selection().clear()))); + } + + function selectedCount(): string { + return selection().count().toLocaleString(); + } + + return { + isResolving: isResolving.asReadonly(), + + toggleShelf(shelfId: number, checked: boolean): void { + void withSelectedBookIds(bookIds => + shelfMembershipMutation.mutate({ + bookIds: [...bookIds], + assignShelfIds: checked ? [shelfId] : [], + unassignShelfIds: checked ? [] : [shelfId], + })); + }, + + removeFromAllShelves(shelfIds: readonly number[]): void { + if (shelfIds.length === 0) { + return; + } + void withSelectedBookIds(bookIds => + shelfMembershipMutation.mutate({ + bookIds: [...bookIds], + assignShelfIds: [], + unassignShelfIds: [...shelfIds], + })); + }, + + editAll(): void { + openThenClear(bookIds => dialogHelper.openBulkMetadataEditDialog(bookIds)); + }, + + editOneByOne(): void { + openThenClear(bookIds => dialogHelper.openMultibookMetadataEditorDialog(bookIds)); + }, + + lockUnlockMetadata(): void { + openThenClear(bookIds => dialogHelper.openLockUnlockMetadataDialog(bookIds)); + }, + + organizeFiles(): void { + void withSelectedBookIds(bookIds => void dialogHelper.openFileMoverDialog(new Set(bookIds))); + }, + + createShelf(): void { + void dialogHelper.openShelfCreatorDialog(); + }, + + attachFiles(): void { + const sourceBooks: BookFileAttacherSourceBook[] = + books().filter(book => selection().isSelected(book.id)); + void dialogHelper.openBulkBookFileAttacherDialog(sourceBooks) + .then(ref => ref?.onClose.pipe(take(1)).subscribe((result: {success?: boolean} | undefined) => { + if (result?.success) { + selection().clear(); + } + })); + }, + + resetProgress(source: BookProgressSource): void { + void withSelectedBookIds(bookIds => resetProgressMutation.mutate({bookIds: [...bookIds], source})); + }, + + setMetadataLocks(locked: boolean): void { + void withSelectedBookIds(bookIds => metadataLocksMutation.mutate({bookIds: [...bookIds], locked})); + }, + + changeCovers(kind: 'regenerate' | 'generate'): void { + const regenerate = kind === 'regenerate'; + confirmationService.confirm({ + message: transloco.translate( + regenerate ? 'book.browser.confirm.regenCoverMessage' : 'book.browser.confirm.customCoverMessage', + {count: selectedCount()}, + ), + header: transloco.translate( + regenerate ? 'book.browser.confirm.regenCoverHeader' : 'book.browser.confirm.customCoverHeader', + ), + acceptLabel: transloco.translate('common.confirm'), + rejectLabel: transloco.translate('common.cancel'), + accept: () => { + void withSelectedBookIds(bookIds => changeCoversMutation.mutate({kind, bookIds: [...bookIds]})); + }, + }); + }, + + fetchMetadata(): void { + void withSelectedBookIds(bookIds => refreshMetadataMutation.mutate({bookIds: [...bookIds]})); + }, + + fetchMetadataWithOptions(): void { + void withSelectedBookIds(bookIds => void dialogHelper.openMetadataRefreshDialog(new Set(bookIds))); + }, + + delete(): void { + confirmationService.confirm({ + message: transloco.translate('book.browser.confirm.deleteMessage', {count: selectedCount()}), + header: transloco.translate('book.browser.confirm.deleteHeader'), + acceptLabel: transloco.translate('common.delete'), + rejectLabel: transloco.translate('common.cancel'), + acceptButtonStyleClass: 'p-button-danger', + rejectButtonStyleClass: 'p-button-outlined', + accept: () => { + void withSelectedBookIds(bookIds => + deleteBooksMutation.mutate({bookIds: [...bookIds]}, { + onSuccess: result => selection().pruneDeleted(result.removedBookIds), + onError: error => { + if (error instanceof DeleteBooksPartialError) { + selection().pruneDeleted(error.completed.removedBookIds); + } + }, + })); + }, + }); + }, + + markAs(status: KnownBookReadStatus): void { + const statusLabel = transloco.translate( + status === 'UNSET' ? CLEAR_BOOK_READ_STATUS_LABEL_KEY : BOOK_READ_STATUS_LABEL_KEYS[status], + ); + confirmationService.confirm({ + header: transloco.translate('browse.bulk.updateReadStatus'), + message: transloco.translate('browse.bulk.markAsMessage', {count: selectedCount(), status: statusLabel}), + acceptLabel: transloco.translate('common.confirm'), + rejectLabel: transloco.translate('common.cancel'), + accept: () => { + void withSelectedBookIds(bookIds => readStatusMutation.mutate({bookIds: [...bookIds], status})); + }, + }); + }, + }; +} diff --git a/frontend/src/app/features/book/browse/book-browse-detail-line.service.spec.ts b/frontend/src/app/features/book/browse/book-browse-detail-line.service.spec.ts new file mode 100644 index 000000000..31daf0972 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-detail-line.service.spec.ts @@ -0,0 +1,45 @@ +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {firstValueFrom} from 'rxjs'; +import {beforeEach, describe, expect, it} from 'vitest'; + +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {type BookSummary} from '../data/book-response.models'; +import {BookBrowseDetailLineService} from './book-browse-detail-line.service'; + +function book(overrides: Partial = {}): BookSummary { + return { + id: 1, + libraryId: 1, + libraryName: 'Library', + primaryFile: {id: 10, bookId: 1, book: true, folderBased: false, bookType: 'EPUB'}, + ...overrides, + }; +} + +describe('BookBrowseDetailLineService', () => { + let service: BookBrowseDetailLineService; + + beforeEach(async () => { + TestBed.configureTestingModule({imports: [getTranslocoModule()]}); + service = TestBed.inject(BookBrowseDetailLineService); + await firstValueFrom(TestBed.inject(TranslocoService).load('en')); + }); + + it('renders the reading progress the card bar shows', () => { + const reading = book({ + epubProgress: {cfi: null, href: null, contentSourceProgressPercent: null, percentage: 33.6, ttsPositionCfi: null}, + koboProgress: {percentage: 90}, + }); + expect(service.lineFor('readingProgress', reading)).toBe('34%'); + expect(service.lineFor('readingProgress', book({koboProgress: {percentage: 90}}))).toBe('90%'); + }); + + it('translates read status and renders every absent value as the muted dash', () => { + expect(service.lineFor('readStatus', book({readStatus: 'RE_READING'}))).toBe('Re-reading'); + const bare = book(); + for (const key of ['addedOn', 'publisher', 'pageCount', 'goodreadsRating', 'readingProgress', 'readStatus'] as const) { + expect(service.lineFor(key, bare)).toBe('—'); + } + }); +}); diff --git a/frontend/src/app/features/book/browse/book-browse-detail-line.service.ts b/frontend/src/app/features/book/browse/book-browse-detail-line.service.ts new file mode 100644 index 000000000..17eae2b77 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-detail-line.service.ts @@ -0,0 +1,72 @@ +import {Injectable, inject} from '@angular/core'; +import {toSignal} from '@angular/core/rxjs-interop'; +import {TranslocoService} from '@jsverse/transloco'; + +import {bookProgressPercentage} from '../data/book-actions'; +import {type BookSummary} from '../data/book-response.models'; +import {formatBookValue} from './book-browse-columns'; +import {type BookColumnKind, type BookColumnValue, type BookDetailLineSortKey} from './book-browse-fields'; + +@Injectable({providedIn: 'root'}) +export class BookBrowseDetailLineService { + private readonly transloco = inject(TranslocoService); + private readonly activeLang = toSignal(this.transloco.langChanges$, { + initialValue: this.transloco.getActiveLang(), + }); + + lineFor(key: BookDetailLineSortKey, book: BookSummary): string { + this.activeLang(); + return this.valueFor(key, book) ?? '—'; + } + + private valueFor(key: BookDetailLineSortKey, book: BookSummary): string | null { + const metadata = book.metadata; + switch (key) { + case 'addedOn': + return this.format('date', book.addedOn); + case 'lastReadTime': + return this.format('date', book.lastReadTime); + case 'dateFinished': + return this.format('date', book.dateFinished); + case 'publishedDate': + return this.format('date', metadata?.publishedDate); + case 'publisher': + return this.format('text', metadata?.publisher); + case 'seriesName': + return this.format('text', metadata?.seriesName); + case 'narrator': + return this.format('text', metadata?.narrator); + case 'language': + return this.format('text', metadata?.language); + case 'pageCount': + return this.format('number', metadata?.pageCount); + case 'personalRating': + return this.format('rating', book.personalRating); + case 'amazonRating': + case 'goodreadsRating': + case 'hardcoverRating': + case 'ranobedbRating': + case 'lubimyczytacRating': + case 'audibleRating': + return this.format('rating', metadata?.[key]); + case 'amazonReviewCount': + case 'goodreadsReviewCount': + case 'hardcoverReviewCount': + case 'audibleReviewCount': + return this.format('number', metadata?.[key]); + case 'readingProgress': + return progressLine(book); + case 'readStatus': + return this.format('readStatus', book.readStatus); + } + } + + private format(kind: BookColumnKind, value: BookColumnValue): string | null { + return formatBookValue(kind, value, key => this.transloco.translate(key)); + } +} + +function progressLine(book: BookSummary): string | null { + const percentage = bookProgressPercentage(book); + return percentage == null ? null : `${Math.round(percentage)}%`; +} diff --git a/frontend/src/app/features/book/browse/book-browse-filter-page.component.ts b/frontend/src/app/features/book/browse/book-browse-filter-page.component.ts new file mode 100644 index 000000000..9832bc8fa --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-filter-page.component.ts @@ -0,0 +1,151 @@ +import {Component, computed, inject, signal} from '@angular/core'; +import {toSignal} from '@angular/core/rxjs-interop'; +import {ActivatedRoute} from '@angular/router'; +import {TranslocoPipe, TranslocoService} from '@jsverse/transloco'; +import {injectQuery} from '@tanstack/angular-query-experimental'; + +import {BrowseFilterRailComponent} from '../../../shared/browse/filter-rail/filter-rail.component'; +import { + countBrowseFacetValues, + toggleBrowseFacetValue, + withBrowseFacetRange, + type BrowseFilterRangeCommit, + type BrowseFilterToggle, +} from '../../../shared/browse/facets'; + +import {AppButtonComponent} from '../../../shared/ui/button/app-button.component'; +import {BrowseSearchInputComponent} from '../../../shared/browse/search-input/search-input.component'; +import {debouncedSignal} from '../../../shared/util/debounced-signal'; +import {SEARCH_DEBOUNCE_MS} from '../../../shared/util/search-terms'; +import {AppPageHeaderComponent} from '../../../shared/layout/page-header/app.page-header.component'; +import {type PageHeader} from '../../../shared/layout/page-header/page-header.service'; +import { + EMPTY_FACET_SELECTION, + type BookQueryFacetKey, + type FacetValueMap, +} from '../data/book-query-params'; +import {type BookPage} from '../data/book-query.models'; +import {BookQueryService} from '../data/book-query.service'; +import {bookBrowseScope} from './book-browse-scope'; +import {createBookBrowseQueries} from './book-browse-queries'; +import {createBookBrowseUrlState} from './book-browse-url-state'; + +@Component({ + selector: 'app-book-browse-filter-page', + imports: [TranslocoPipe, AppButtonComponent, AppPageHeaderComponent, BrowseFilterRailComponent, BrowseSearchInputComponent], + template: ` +
+ +
+ +
+
+ +
+ +
+ +
+ + +
+
+ `, +}) +export class BookBrowseFilterPageComponent { + private readonly route = inject(ActivatedRoute); + private readonly bookQuery = inject(BookQueryService); + private readonly transloco = inject(TranslocoService); + private readonly urlState = createBookBrowseUrlState(); + + protected readonly staged = signal(this.urlState.facets()); + protected readonly stagedQuery = signal(this.urlState.query()); + private readonly debouncedQuery = debouncedSignal( + computed(() => this.stagedQuery().trim()), SEARCH_DEBOUNCE_MS, + ); + protected readonly hasActiveFilters = computed(() => + countBrowseFacetValues(this.staged()) > 0 || this.stagedQuery().trim().length > 0); + + private readonly scope = computed(() => + bookBrowseScope(this.route.snapshot.paramMap, this.route.snapshot.data), + ); + private readonly queries = createBookBrowseQueries({ + selection: this.staged, + query: this.debouncedQuery, + scope: this.scope, + }); + protected readonly railGroups = this.queries.railGroups; + protected readonly searchHint = this.queries.searchHint; + + private readonly previewQuery = injectQuery(() => ({ + ...this.bookQuery.page({...this.queries.collectionParams(), size: 1, sort: []}), + placeholderData: (previous: BookPage | undefined) => previous, + })); + protected readonly previewTotal = computed(() => this.previewQuery.data()?.page.totalElements ?? null); + protected readonly previewLoading = computed(() => + this.previewQuery.isPending() || this.previewQuery.isPlaceholderData()); + + private readonly activeLang = toSignal(this.transloco.langChanges$, { + initialValue: this.transloco.getActiveLang(), + }); + protected readonly pageHeader = computed(() => { + this.activeLang(); + return { + title: this.transloco.translate('browse.filter'), + breadcrumbs: [ + { + label: this.queries.title(), + commands: ['/', ...this.route.parent!.snapshot.url.map(segment => segment.path)], + queryParamsHandling: 'preserve', + }, + {label: this.transloco.translate('browse.filter')}, + ], + }; + }); + + protected onToggle(toggle: BrowseFilterToggle): void { + this.staged.update(current => + toggleBrowseFacetValue( + current, + toggle.key, + toggle.value, + toggle.selected, + ), + ); + } + + protected onCommitRange(commit: BrowseFilterRangeCommit): void { + this.staged.update(current => + withBrowseFacetRange(current, commit.key, commit.min, commit.max, this.queries.definitions())); + } + + protected onClear(): void { + this.staged.set(EMPTY_FACET_SELECTION); + this.stagedQuery.set(''); + } + + protected onCommit(): void { + this.urlState.applyFilters(this.staged(), this.stagedQuery().trim()); + } +} diff --git a/frontend/src/app/features/book/browse/book-browse-multi-sort-dialog.component.ts b/frontend/src/app/features/book/browse/book-browse-multi-sort-dialog.component.ts new file mode 100644 index 000000000..76497b96d --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-multi-sort-dialog.component.ts @@ -0,0 +1,59 @@ +import {Component, inject, signal} from '@angular/core'; +import {DynamicDialogConfig, DynamicDialogRef} from '@openng/optimus-ui/dynamicdialog'; +import {TranslocoPipe} from '@jsverse/transloco'; + +import {AppButtonComponent} from '../../../shared/ui/button/app-button.component'; +import {AppCheckboxComponent} from '../../../shared/ui/checkbox/app-checkbox.component'; +import {type BookSortTerm} from '../data/book-query-params'; +import {BookBrowseMultiSortEditorComponent} from './book-browse-multi-sort-editor.component'; +import {type BookSortOption} from './book-browse-sort'; + +export interface BookBrowseMultiSortDialogData { + readonly terms: readonly BookSortTerm[]; + readonly options: readonly BookSortOption[]; + readonly saveDefaultFor?: string; +} + +export interface BookBrowseMultiSortDialogResult { + readonly terms: readonly BookSortTerm[]; + readonly saveAsDefault: boolean; +} + +@Component({ + selector: 'app-book-browse-multi-sort-dialog', + imports: [TranslocoPipe, AppButtonComponent, AppCheckboxComponent, BookBrowseMultiSortEditorComponent], + template: ` +
+

{{ 'browse.sort.multiSort' | transloco }}

+ + @if (data.saveDefaultFor; as scope) { + + } +
+ + +
+
+ `, +}) +export class BookBrowseMultiSortDialogComponent { + private readonly ref = inject(DynamicDialogRef); + protected readonly data = inject>(DynamicDialogConfig).data!; + protected readonly draft = signal([...this.data.terms]); + protected readonly saveAsDefault = signal(false); + + protected apply(): void { + const result: BookBrowseMultiSortDialogResult = { + terms: [...this.draft()], + saveAsDefault: this.saveAsDefault(), + }; + this.ref.close(result); + } + + protected cancel(): void { + this.ref.close(); + } +} diff --git a/frontend/src/app/features/book/browse/book-browse-multi-sort-editor.component.ts b/frontend/src/app/features/book/browse/book-browse-multi-sort-editor.component.ts new file mode 100644 index 000000000..ce41b9a3a --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-multi-sort-editor.component.ts @@ -0,0 +1,164 @@ +import {Component, computed, inject, input, model, signal} from '@angular/core'; +import {CdkDrag, CdkDragHandle, CdkDropList, moveItemInArray, type CdkDragDrop} from '@angular/cdk/drag-drop'; +import {toSignal} from '@angular/core/rxjs-interop'; +import {TranslocoPipe, TranslocoService} from '@jsverse/transloco'; +import {LucideChevronDown, LucideChevronUp, LucideDynamicIcon, LucideGripVertical, LucideX} from '@lucide/angular'; + +import {AppButtonComponent} from '../../../shared/ui/button/app-button.component'; +import {AppSelectComponent} from '../../../shared/ui/select/app-select.component'; +import {type SelectOption} from '../../../shared/ui/select/app-select.options'; +import {type BookSortTerm} from '../data/book-query-params'; +import {bookSortDirectionIcon, bookSortField, type BookSortOption} from './book-browse-sort'; + +@Component({ + selector: 'app-book-browse-multi-sort-editor', + imports: [ + TranslocoPipe, + AppButtonComponent, + AppSelectComponent, + CdkDrag, + CdkDragHandle, + CdkDropList, + LucideChevronDown, + LucideChevronUp, + LucideDynamicIcon, + LucideGripVertical, + LucideX, + ], + template: ` +
+ @for (row of rows(); track row.key) { +
+ + + + {{ $index + 1 }} + {{ row.label }} + + + + + + + + + + + + +
+ } +
+ + `, +}) +export class BookBrowseMultiSortEditorComponent { + private readonly transloco = inject(TranslocoService); + private readonly activeLang = toSignal(this.transloco.langChanges$, { + initialValue: this.transloco.getActiveLang(), + }); + + readonly terms = model.required(); + readonly options = input.required(); + + protected readonly addSelection = signal(null); + + protected readonly rows = computed(() => { + this.activeLang(); + const optionsById = new Map(this.options().map(option => [option.id, option])); + return this.terms().map(term => { + const option = optionsById.get(term.key); + return { + key: term.key, + label: this.transloco.translate((option ?? bookSortField(term.key)).labelKey), + icon: bookSortDirectionIcon(term.key, term.direction), + canFlip: option?.directions.length === 2, + }; + }); + }); + + protected readonly addOptions = computed[]>(() => { + this.activeLang(); + const used = new Set(this.terms().map(term => term.key)); + return this.options() + .filter(option => !used.has(option.id)) + .map(option => ({value: option.id, label: this.transloco.translate(option.labelKey)})); + }); + + protected drop(event: CdkDragDrop): void { + if (event.previousIndex === event.currentIndex) { + return; + } + const next = [...this.terms()]; + moveItemInArray(next, event.previousIndex, event.currentIndex); + this.terms.set(next); + } + + protected move(index: number, delta: -1 | 1): void { + const next = [...this.terms()]; + const target = index + delta; + [next[index], next[target]] = [next[target], next[index]]; + this.terms.set(next); + } + + protected flip(index: number): void { + const next = this.terms().map((term, i): BookSortTerm => { + if (i !== index) { + return term; + } + return {key: term.key, direction: term.direction === 'asc' ? 'desc' : 'asc'}; + }); + this.terms.set(next); + } + + protected removeAt(index: number): void { + const terms = this.terms(); + this.terms.set(terms.filter((_, i) => i !== index)); + } + + protected add(key: string | null): void { + if (!key) { + return; + } + const option = this.options().find(candidate => candidate.id === key); + if (!option) { + return; + } + this.terms.set([...this.terms(), {key: option.id, direction: option.defaultDirection}]); + this.addSelection.set(null); + } +} diff --git a/frontend/src/app/features/book/browse/book-browse-page.component.html b/frontend/src/app/features/book/browse/book-browse-page.component.html new file mode 100644 index 000000000..f4da882cd --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-page.component.html @@ -0,0 +1,174 @@ +
+ + @if (mobileSelectMode()) { + + } @else { + + } + + + + + + +
+
+ @if (chipsBand().count > 0) { +
+ +
+ } @else { +
+ } + @if (preferences.viewMode() === 'table') { + + + + + + } @else { + + + + + + + + + + + + } +
+ + @if (railVisible()) { + + } +
+
+ + + @if (chipsBand().count > 0) { +
+

{{ 'browse.book.filteredEmpty' | transloco }}

+ +
+ } @else { +

{{ 'browse.book.empty' | transloco }}

+ } +
diff --git a/frontend/src/app/features/book/browse/book-browse-page.component.spec.ts b/frontend/src/app/features/book/browse/book-browse-page.component.spec.ts new file mode 100644 index 000000000..f6f0f4fbc --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-page.component.spec.ts @@ -0,0 +1,380 @@ +import {HttpTestingController} from '@angular/common/http/testing'; +import {Component, signal, type WritableSignal} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {By} from '@angular/platform-browser'; +import {Router, provideRouter} from '@angular/router'; +import {RouterTestingHarness} from '@angular/router/testing'; +import {QueryClient} from '@tanstack/angular-query-experimental'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {createQueryClientHarness, flushQueryAsync} from '../../../core/testing/query-testing'; +import {BrowseGridComponent} from '../../../shared/browse/grid/grid.component'; +import {BrowseGridViewportComponent} from '../../../shared/browse/grid/grid-viewport.component'; +import {AppSettingsService} from '../../../shared/service/app-settings.service'; +import {SEARCH_DEBOUNCE_MS} from '../../../shared/util/search-terms'; +import {UrlHelperService} from '../../../shared/service/url-helper.service'; +import {type BrowseLink} from '../../../core/data/browse.models'; +import {type BookSummary} from '../data/book-response.models'; +import {ConfirmationService, MessageService} from '@openng/optimus-ui/api'; +import {DialogService} from '@openng/optimus-ui/dynamicdialog'; + +import {BookFileService} from '../service/book-file.service'; +import {LibraryService} from '../service/library.service'; +import {LibraryShelfMenuService} from '../service/library-shelf-menu.service'; +import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service'; +import {ShelfDefinitionQueryService} from '../data/shelf-definition-query.service'; +import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service'; +import {UserService} from '../../settings/user-management/user.service'; +import {EmailService} from '../../settings/email-v2/email.service'; +import {type BookSortTerm} from '../data/book-query-params'; +import {BookBrowsePageComponent} from './book-browse-page.component'; +import {BookBrowseFilterPageComponent} from './book-browse-filter-page.component'; + +const PAGE_URL = `${API_CONFIG.BASE_URL}/api/v1/books/page`; +const FACETS_URL = `${API_CONFIG.BASE_URL}/api/v1/books/facets`; + +@Component({selector: 'app-test-route', template: ''}) +class TestRouteComponent {} + +function bookPage(ids: number[], totalElements = ids.length, links: BrowseLink[] = []) { + return { + content: ids.map(id => ({id, libraryId: 1, libraryName: 'Library'})), + page: {number: 0, size: 60, totalElements, totalPages: Math.ceil(totalElements / 60)}, + links, + }; +} + +interface PageHarness { + detailLineFor(book: BookSummary): string | null; + selection: { + count(): number; + toggle(book: BookSummary, index: number, shiftKey: boolean): void; + }; + preferences: {setSortTerms(terms: readonly BookSortTerm[]): void}; + searchDraft: {set(value: string): void}; + onSortDirectionChange(term: BookSortTerm): void; + onClearQuery(): void; +} + +const GLOBAL_PREFERENCE = { + sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false, overlayBookType: true, +}; + +function userFixture(permissions: Record, id?: number, global: Record = {}) { + return { + ...(id === undefined ? {} : {id}), + permissions, + userSettings: {entityViewPreferences: {global: {...GLOBAL_PREFERENCE, ...global}, overrides: []}}, + }; +} + +describe('BookBrowsePageComponent', () => { + let fixture: ComponentFixture; + + let http: HttpTestingController; + let queryClient: QueryClient; + let currentUser: WritableSignal | null>; + let updateUserSetting: ReturnType; + + function grid(): BrowseGridComponent { + return fixture.debugElement.query(By.directive(BrowseGridComponent)) + .componentInstance as BrowseGridComponent; + } + + function viewport(): BrowseGridViewportComponent { + return fixture.debugElement.query(By.directive(BrowseGridViewportComponent)) + .componentInstance as BrowseGridViewportComponent; + } + + function page(): PageHarness { + return fixture.componentInstance as unknown as PageHarness; + } + + function flushFacetRegistry(): void { + for (const request of http.match(candidate => candidate.url === FACETS_URL)) { + request.flush({ + links: [{rel: 'self', href: '/api/v1/books/facets', type: 'application/json'}], + facets: [{ + metadata: {rel: 'sort', key: 'sort', title: 'Sort'}, + links: [ + {rel: 'sort', href: '', type: '', title: 'title ascending', value: 'title'}, + {rel: 'sort', href: '', type: '', title: 'title descending', value: '-title'}, + {rel: 'sort', href: '', type: '', title: 'page count', value: 'pageCount'}, + ], + }], + }); + } + } + + function expectInitialPageRequest() { + flushFacetRegistry(); + return http.expectOne(request => + request.url === PAGE_URL && + request.params.get('sort') === 'title' && + request.params.get('size') === '60' && + !request.params.has('page') && + !request.params.has('cursor'), + ); + } + + async function routeTo(url: string): Promise { + const routerHarness = await RouterTestingHarness.create(); + await routerHarness.navigateByUrl(url); + routerHarness.detectChanges(); + return routerHarness; + } + + beforeEach(() => { + const harness = createQueryClientHarness(); + queryClient = harness.queryClient; + queryClient.setDefaultOptions({queries: {retry: false}}); + currentUser = signal(null); + updateUserSetting = vi.fn(); + + TestBed.configureTestingModule({ + imports: [BookBrowsePageComponent, getTranslocoModule()], + providers: [ + ...harness.providers, + provideRouter([ + {path: '', component: TestRouteComponent}, + {path: 'book/:bookId', component: TestRouteComponent}, + {path: 'library/:libraryId/books', children: [ + {path: '', component: BookBrowsePageComponent}, + {path: 'filter', component: BookBrowseFilterPageComponent}, + ]}, + {path: 'magic-shelf/:magicShelfId/books', children: [{path: '', component: BookBrowsePageComponent}]}, + {path: 'unshelved-books', children: [ + {path: '', component: BookBrowsePageComponent, data: {browseScope: 'unshelved'}}, + ]}, + ]), + { + provide: UrlHelperService, + useValue: { + getThumbnailUrl: (id: number) => `/thumb/${id}`, + getAudiobookThumbnailUrl: (id: number) => `/audio-thumb/${id}`, + }, + }, + { + provide: ShelfDefinitionQueryService, + useValue: { + definitions: () => ({ + queryKey: ['shelves', 'query', 'definitions'] as const, + queryFn: () => Promise.resolve([]), + }), + }, + }, + {provide: MagicShelfService, useValue: {shelves: () => [{id: 9, name: 'Witchy Reads'}]}}, + {provide: LibraryService, useValue: {libraries: () => [{id: 3, name: 'Cookbooks'}]}}, + {provide: LibraryShelfMenuService, useValue: {}}, + {provide: UserService, useValue: {currentUser, updateUserSetting}}, + {provide: AppSettingsService, useValue: {appSettings: signal({diskType: 'LOCAL'})}}, + {provide: BookDialogHelperService, useValue: {}}, + {provide: BookFileService, useValue: {}}, + {provide: EmailService, useValue: {}}, + {provide: ConfirmationService, useValue: {confirm: () => undefined}}, + {provide: MessageService, useValue: {add: () => undefined}}, + {provide: DialogService, useValue: {open: () => null}}, + ], + }); + + http = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + http.verify(); + vi.restoreAllMocks(); + TestBed.resetTestingModule(); + history.replaceState({}, '', '/'); + }); + + it('pins the route scope onto page and facet requests, over any URL facet for the same key', async () => { + const routerHarness = await routeTo('/library/3/books?facet=genre:Fantasy&facet=library:99'); + const facetRequests = http.match(candidate => candidate.url === FACETS_URL); + expect(facetRequests.map(facets => facets.request.params.getAll('facet'))).toEqual( + expect.arrayContaining([['library:3'], ['genre:Fantasy', 'library:3']]), + ); + expect(facetRequests).toHaveLength(2); + facetRequests.forEach(facets => facets.flush({facets: []})); + const library = http.expectOne(candidate => candidate.url === PAGE_URL); + expect(library.request.params.getAll('facet')).toEqual(['genre:Fantasy', 'library:3']); + library.flush(bookPage([1], 1)); + await flushQueryAsync(); + + await routerHarness.navigateByUrl('/magic-shelf/9/books'); + routerHarness.detectChanges(); + flushFacetRegistry(); + const magic = http.expectOne(candidate => candidate.url === PAGE_URL); + expect(magic.request.params.getAll('facet')).toEqual(['shelf:magic:9']); + magic.flush(bookPage([1], 1)); + await flushQueryAsync(); + + await routerHarness.navigateByUrl('/unshelved-books'); + routerHarness.detectChanges(); + flushFacetRegistry(); + const unshelved = http.expectOne(candidate => candidate.url === PAGE_URL); + expect(unshelved.request.params.getAll('facet')).toEqual(['shelf_status:unshelved']); + unshelved.flush(bookPage([1], 1)); + await flushQueryAsync(); + }); + + it('serves a remount from the shared cache and ignores view-only URL changes', async () => { + fixture = TestBed.createComponent(BookBrowsePageComponent); + fixture.detectChanges(); + expectInitialPageRequest().flush(bookPage([1, 2, 3], 100_000)); + await flushQueryAsync(); + + fixture.destroy(); + fixture = TestBed.createComponent(BookBrowsePageComponent); + fixture.detectChanges(); + await flushQueryAsync(); + + http.expectNone(candidate => candidate.url === PAGE_URL); + expect(grid().items().map(item => item.id)).toEqual([1, 2, 3]); + + await TestBed.inject(Router).navigate([], {queryParams: {view: 'grid'}}); + await fixture.whenStable(); + await flushQueryAsync(1); + + http.expectNone(candidate => candidate.url === PAGE_URL); + }); + + it('follows the opaque next link and retries a continuation failure', async () => { + fixture = TestBed.createComponent(BookBrowsePageComponent); + fixture.detectChanges(); + expectInitialPageRequest().flush(bookPage([1], 600, [{ + rel: ['next'], + href: '/api/v1/books/page?cursor=opaque%2Bcursor&sort=title&size=60', + type: 'application/json', + }])); + await flushQueryAsync(); + + viewport().renderedRange.set({start: 0, end: 0}); + await flushQueryAsync(1); + + const nextUrl = `${API_CONFIG.BASE_URL}/api/v1/books/page?cursor=opaque%2Bcursor&sort=title&size=60`; + http.expectOne(nextUrl).flush('Could not load', {status: 400, statusText: 'Bad Request'}); + await flushQueryAsync(); + + expect(grid().status()).toBe('success'); + expect(grid().nextPageError()).toBe(true); + expect(grid().items().map(item => item.id)).toEqual([1]); + + grid().retryNextPage.emit(); + http.expectOne(nextUrl).flush(bookPage([2], 600)); + await flushQueryAsync(); + + expect(grid().nextPageError()).toBe(false); + expect(grid().items().map(item => item.id)).toEqual([1, 2]); + }); + + it('passes sort, search and facets to the endpoint exactly while the URL keeps the raw query', async () => { + fixture = TestBed.createComponent(BookBrowsePageComponent); + await TestBed.inject(Router).navigate([], { + queryParams: {sort: '-title,pageCount', query: 'dune!', facet: ['genre:Fantasy', 'language:en']}, + }); + fixture.detectChanges(); + flushFacetRegistry(); + + const request = http.expectOne(candidate => candidate.url === PAGE_URL); + expect(request.request.params.get('sort')).toBe('-title,pageCount'); + expect(request.request.params.get('query')).toBe('dune'); + expect(request.request.params.getAll('facet')).toEqual(['genre:Fantasy', 'language:en']); + expect(request.request.params.has('page')).toBe(false); + request.flush(bookPage([1], 1)); + await flushQueryAsync(); + + expect(TestBed.inject(Router).routerState.snapshot.root.queryParamMap.get('query')).toBe('dune!'); + }); + + it('applies the saved default sort when the URL has none, mapping old author keys, then drops sorts the server does not offer', async () => { + fixture = TestBed.createComponent(BookBrowsePageComponent); + currentUser.set(userFixture({}, undefined, { + sortKey: 'author', + sortCriteria: [{field: 'author', direction: 'ASC'}, {field: 'title', direction: 'DESC'}], + })); + fixture.detectChanges(); + flushFacetRegistry(); + + http.expectOne(request => + request.url === PAGE_URL && + request.params.get('sort') === 'authorName,-title' && + !request.params.has('cursor'), + ).flush(bookPage([1], 1)); + await flushQueryAsync(); + http.expectOne(request => + request.url === PAGE_URL && request.params.get('sort') === '-title', + ).flush(bookPage([1], 1)); + await flushQueryAsync(); + }); + + it('ignores reselecting the active sort and flips only the primary term on a direction toggle', async () => { + fixture = TestBed.createComponent(BookBrowsePageComponent); + await TestBed.inject(Router).navigate([], {queryParams: {sort: 'pageCount'}}); + fixture.detectChanges(); + flushFacetRegistry(); + http.expectOne(request => + request.url === PAGE_URL && request.params.get('sort') === 'pageCount', + ).flush(bookPage([1], 1)); + await flushQueryAsync(); + + page().preferences.setSortTerms([{key: 'pageCount', direction: 'asc'}]); + await fixture.whenStable(); + await flushQueryAsync(1); + http.expectNone(candidate => candidate.url === PAGE_URL); + + await TestBed.inject(Router).navigate([], {queryParams: {sort: '-title,pageCount'}}); + await fixture.whenStable(); + http.expectOne(request => + request.url === PAGE_URL && request.params.get('sort') === '-title,pageCount', + ).flush(bookPage([1], 1)); + await flushQueryAsync(); + + page().onSortDirectionChange({key: 'title', direction: 'asc'}); + await fixture.whenStable(); + await flushQueryAsync(1); + http.expectOne(request => + request.url === PAGE_URL && request.params.get('sort') === 'title,pageCount', + ).flush(bookPage([1], 1)); + await flushQueryAsync(); + }); + + it('debounces typed text into one replaceUrl navigation and clears immediately', () => { + fixture = TestBed.createComponent(BookBrowsePageComponent); + vi.useFakeTimers(); + try { + fixture.detectChanges(); + expectInitialPageRequest().flush(bookPage([1], 1)); + const navigate = vi.spyOn(TestBed.inject(Router), 'navigate').mockResolvedValue(true); + + page().searchDraft.set('the war'); + page().searchDraft.set('the warden '); + TestBed.flushEffects(); + vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS - 1); + expect(navigate).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(1); + TestBed.flushEffects(); + expect(navigate).toHaveBeenCalledExactlyOnceWith([], expect.objectContaining({ + queryParams: {query: 'the warden'}, + replaceUrl: true, + })); + + navigate.mockClear(); + page().searchDraft.set('the wardens'); + TestBed.flushEffects(); + page().onClearQuery(); + expect(navigate).toHaveBeenCalledExactlyOnceWith([], expect.objectContaining({ + queryParams: {query: null}, + queryParamsHandling: 'merge', + })); + + vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS); + TestBed.flushEffects(); + expect(navigate).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/frontend/src/app/features/book/browse/book-browse-page.component.ts b/frontend/src/app/features/book/browse/book-browse-page.component.ts new file mode 100644 index 000000000..6b04b2177 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-page.component.ts @@ -0,0 +1,478 @@ +import {NgTemplateOutlet} from '@angular/common'; +import {Component, computed, effect, inject, linkedSignal, signal, untracked, viewChild} from '@angular/core'; +import {toSignal} from '@angular/core/rxjs-interop'; +import {ActivatedRoute} from '@angular/router'; +import {TranslocoPipe} from '@jsverse/transloco'; +import {injectInfiniteQuery, QueryClient} from '@tanstack/angular-query-experimental'; +import {take} from 'rxjs/operators'; + +import {BrowseGridComponent} from '../../../shared/browse/grid/grid.component'; +import { + BrowseEmptyDef, + BrowseGridItemDef, + BrowseGridSkeletonDef, +} from '../../../shared/browse/grid/grid.directives'; +import {bookCardHeightForWidth} from '../components/cards/book-card.layout'; +import {BookCardComponent, bookCardCoverSrc} from '../components/cards/book-card.component'; +import {UrlHelperService} from '../../../shared/service/url-helper.service'; +import {BookMenuComponent} from '../components/book-menu/book-menu.component'; +import {BookCardSkeletonComponent} from '../components/cards/book-card-skeleton.component'; +import {ArtworkRevealGroupDirective} from '../../../shared/components/cover/artwork-reveal-group.directive'; +import {AppPageHeaderComponent} from '../../../shared/layout/page-header/app.page-header.component'; +import {type PageHeader} from '../../../shared/layout/page-header/page-header.service'; +import {LayoutService} from '../../../shared/layout/layout.service'; +import {LocalStorageService} from '../../../shared/service/local-storage.service'; +import {PageTitleService} from '../../../shared/service/page-title.service'; +import {createGridDensity, type GridDensityDirection} from '../../../shared/util/grid-density.util'; +import {CoverScalePreferenceService} from '../components/book-browser/cover-scale-preference.service'; +import {LibraryService} from '../service/library.service'; +import {BookNavigationService} from '../service/book-navigation.service'; +import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service'; +import { + type BookPageParams, + type BookQuerySortKey, + type BookSortTerm, + type BookQueryFacetKey, +} from '../data/book-query-params'; +import {bookCollectionKeys} from '../data/book-query-keys'; +import {bookBrowseScope, bookBrowseScopePreferenceContext} from './book-browse-scope'; +import {createBookBrowseQueries} from './book-browse-queries'; +import {createBookBrowsePreferences} from './book-browse-preferences'; +import {createBookBrowseUrlState} from './book-browse-url-state'; +import {type BookBrowseMultiSortDialogResult} from './book-browse-multi-sort-dialog.component'; +import {type BookDetailLineSortKey} from './book-browse-fields'; +import {bookSortHasDetailLine, bookSortOptions} from './book-browse-sort'; +import {BookBrowseDetailLineService} from './book-browse-detail-line.service'; +import {cn} from '../../../shared/ui/cn'; +import {AppButtonComponent} from '../../../shared/ui/button/app-button.component'; +import {BrowseSearchInputComponent} from '../../../shared/browse/search-input/search-input.component'; +import {BrowseFilterRailComponent} from '../../../shared/browse/filter-rail/filter-rail.component'; +import { + countBrowseFacetValues, + toggleBrowseFacetValue, + withBrowseFacetRange, + type BrowseFilterChip, + type BrowseFilterRangeCommit, + type BrowseFilterToggle, +} from '../../../shared/browse/facets'; +import {BookBrowseToolbarComponent} from './book-browse-toolbar.component'; +import {BookBrowseBulkBarComponent} from './book-browse-bulk-bar.component'; +import {BrowseSelectModeControlsComponent} from '../../../shared/browse/bulk-actions/select-mode-controls.component'; +import {BookQueryService} from '../data/book-query.service'; +import {type BookSummary} from '../data/book-response.models'; +import { + injectPendingBookDeletions, + injectPendingBookProgressResets, + injectPendingBookReadStatuses, + overlayPendingBookState, + type PendingBookOverlay, +} from '../data/book-command-pending-state'; +import {createBrowseSelection} from '../../../shared/browse/selection'; +import {createBrowseResults} from '../../../shared/browse/results'; +import {heldSignal} from '../../../shared/util/held-signal'; +import {createBrowseSearchDraft} from '../../../shared/browse/search-draft'; +import {installBrowseSelectionShortcuts} from '../../../shared/browse/selection-shortcuts'; +import {BrowseFilterChipsComponent} from '../../../shared/browse/filter-chips/filter-chips.component'; +import {BookBrowseTableComponent} from './book-browse-table.component'; + +const SELECTION_CLICK_AWAY_EXEMPT = + 'app-book-card, app-browse-bulk-actions-bar, app-menu, app-page-header, aside, ' + + 'app-book-browse-table, ' + + '.cdk-overlay-container, .p-dialog-mask, [role="dialog"], ' + + 'button, a, input, textarea, select, label'; + +const PAGE_SIZE = 60; + +interface BrowseChipsBand { + count: number; + query: string; + chips: readonly BrowseFilterChip[]; +} + +const RAIL_OPEN_STORAGE_KEY = 'browseFilterRailOpen'; + +const GRID_GAP = 16; +const CARD_BASE_WIDTH = 135; +const DESKTOP_MIN_SCALE = 0.5; +const DESKTOP_MAX_SCALE = 1.5; +const MOBILE_COLUMNS_STORAGE_KEY = 'mobileColumnsPreference'; +const DEFAULT_MOBILE_COLUMNS = 3; +const MIN_MOBILE_COLUMNS = 2; +const MAX_MOBILE_COLUMNS = 4; + +@Component({ + selector: 'app-book-browse-page', + imports: [ + NgTemplateOutlet, + TranslocoPipe, + AppPageHeaderComponent, + BrowseGridComponent, + BrowseGridItemDef, + BrowseGridSkeletonDef, + BrowseEmptyDef, + BookCardComponent, + BookMenuComponent, + BookCardSkeletonComponent, + ArtworkRevealGroupDirective, + BookBrowseToolbarComponent, + BookBrowseTableComponent, + BookBrowseBulkBarComponent, + BrowseSelectModeControlsComponent, + BrowseFilterRailComponent, + BrowseFilterChipsComponent, + BrowseSearchInputComponent, + AppButtonComponent, + ], + templateUrl: './book-browse-page.component.html', +}) +export class BookBrowsePageComponent { + private readonly bookQuery = inject(BookQueryService); + private readonly queryClient = inject(QueryClient); + private readonly pageTitle = inject(PageTitleService); + private readonly route = inject(ActivatedRoute); + private readonly layout = inject(LayoutService); + private readonly localStorage = inject(LocalStorageService); + private readonly coverScale = inject(CoverScalePreferenceService); + private readonly detailLines = inject(BookBrowseDetailLineService); + private readonly libraryService = inject(LibraryService); + protected readonly bookNavigation = inject(BookNavigationService); + private readonly urlHelper = inject(UrlHelperService); + private readonly dialogLauncher = inject(DialogLauncherService); + private readonly pendingReadStatuses = injectPendingBookReadStatuses(); + private readonly pendingProgressResets = injectPendingBookProgressResets(); + protected readonly pendingDeletions = injectPendingBookDeletions(); + + private readonly gridRef = viewChild(BrowseGridComponent); + private readonly tableRef = viewChild(BookBrowseTableComponent); + protected readonly bookMenu = viewChild(BookMenuComponent); + private readonly headerRef = viewChild(AppPageHeaderComponent); + protected readonly isMobile = computed(() => !this.layout.isDesktop()); + protected readonly mobileSelectMode = linkedSignal({ + source: this.isMobile, + computation: (isMobile, previous) => isMobile && (previous?.value ?? false), + }); + + private readonly gridDensity = createGridDensity(this.localStorage, { + useFixedColumns: this.isMobile, + screenWidth: () => window.innerWidth, + storageKey: MOBILE_COLUMNS_STORAGE_KEY, + defaultColumns: DEFAULT_MOBILE_COLUMNS, + minColumns: MIN_MOBILE_COLUMNS, + maxColumns: MAX_MOBILE_COLUMNS, + scale: this.coverScale.scaleFactor, + minScale: DESKTOP_MIN_SCALE, + maxScale: DESKTOP_MAX_SCALE, + gap: GRID_GAP, + baseWidth: () => CARD_BASE_WIDTH, + setScale: scale => this.coverScale.setScale(scale), + }); + protected readonly gridGap = this.gridDensity.gap; + protected readonly gridRowGap = GRID_GAP; + protected readonly gridColumns = this.gridDensity.columns; + protected readonly densitySmallerDisabled = this.gridDensity.smallerDisabled; + protected readonly densityLargerDisabled = this.gridDensity.largerDisabled; + protected readonly minCardWidth = computed(() => + this.isMobile() ? 1 : Math.round(CARD_BASE_WIDTH * this.coverScale.scaleFactor()), + ); + private readonly railOpen = signal(this.localStorage.get(RAIL_OPEN_STORAGE_KEY) !== false); + protected readonly railVisible = computed(() => !this.isMobile() && this.railOpen()); + protected readonly menuOpenBookId = computed(() => this.bookMenu()?.openBookId() ?? null); + + protected readonly urlState = createBookBrowseUrlState(); + private readonly routeParamMap = toSignal(this.route.paramMap, { + initialValue: this.route.snapshot.paramMap, + }); + private readonly scope = computed(() => + bookBrowseScope(this.routeParamMap(), this.route.snapshot.data), + ); + private readonly preferenceContext = computed(() => bookBrowseScopePreferenceContext(this.scope())); + + protected readonly queries = createBookBrowseQueries({ + selection: this.urlState.facets, + query: this.urlState.query, + scope: this.scope, + enabled: this.railVisible, + }); + protected readonly railReady = computed(() => !this.queries.pending()); + protected readonly sortOptions = computed(() => bookSortOptions(this.queries.sortTokens())); + private readonly availableSortKeys = computed>( + () => new Set(this.sortOptions().map(option => option.id)), + ); + + protected readonly preferences = createBookBrowsePreferences({ + context: this.preferenceContext, + availableSortKeys: this.availableSortKeys, + urlState: this.urlState, + }); + protected readonly sortTerms = this.preferences.sortTerms; + + protected readonly searchDraft = createBrowseSearchDraft({ + committed: this.urlState.query, + commit: term => this.urlState.setQuery(term), + }); + + private readonly params = computed(() => ({ + ...this.queries.collectionParams(), + size: PAGE_SIZE, + sort: this.sortTerms(), + })); + private readonly collectionKeys = computed(() => bookCollectionKeys(this.params())); + private readonly filtersKey = computed(() => this.collectionKeys().filtersKey); + private readonly shuffleGeneration = signal(0); + private readonly listKey = computed(() => + `${this.collectionKeys().listKey}:${this.shuffleGeneration()}`); + private readonly booksQuery = injectInfiniteQuery(() => this.bookQuery.infinitePage(this.params())); + + protected readonly presentation = createBrowseResults({ + query: this.booksQuery, + listKey: this.listKey, + artworkUrls: (books, lastVisibleIndex) => { + return books.slice(0, lastVisibleIndex + 1).flatMap(book => { + const url = bookCardCoverSrc(book, book.primaryFile, this.urlHelper); + return url ? [url] : []; + }); + }, + scrollToTop: () => { + this.tableRef()?.scrollToTop(); + this.gridRef()?.scrollToTop(); + }, + }); + protected readonly chipsBand = heldSignal( + () => ({ + count: countBrowseFacetValues(this.urlState.facets()) + (this.urlState.query() ? 1 : 0), + query: this.urlState.query(), + chips: this.queries.chips(), + }), + this.presentation.showingPreviousResults, + ); + + private readonly pendingBookOverlay = computed(() => ({ + readStatuses: this.pendingReadStatuses(), + progressResets: this.pendingProgressResets(), + })); + + protected readonly books = computed(() => { + const books = this.presentation.items(); + const overlay = this.pendingBookOverlay(); + if (overlay.readStatuses.size === 0 + && overlay.progressResets.size === 0) { + return books; + } + return books.map(book => overlayPendingBookState(book, overlay)); + }); + protected readonly hasNextPage = this.presentation.shownHasNextPage; + + protected readonly selection = createBrowseSelection({ + filtersKey: this.filtersKey, + listKey: this.listKey, + items: this.books, + totalElements: this.presentation.total, + }); + protected readonly selectionEnabled = computed(() => !this.isMobile() || this.mobileSelectMode()); + protected readonly fetchMatchingBookIds = (): Promise => + this.queryClient.query(this.bookQuery.ids(this.params())); + + private readonly detailLineKey = heldSignal( + () => { + const primary = this.sortTerms().at(0); + return primary && !this.preferences.isDefaultSort(this.sortTerms()) && bookSortHasDetailLine(primary.key) + ? primary.key + : null; + }, + this.presentation.showingPreviousResults, + ); + protected readonly squareCovers = computed(() => this.squareCoversFor(this.books())); + protected readonly metaLines = computed<2 | 3>(() => this.detailLineKey() === null ? 2 : 3); + protected readonly estimateItemHeight = (width: number): number => + bookCardHeightForWidth(width, {square: this.squareCovers(), metaLines: this.metaLines()}); + protected readonly bookItemKey = (book: BookSummary): number => book.id; + + protected readonly pageHeader = computed(() => { + const total = this.presentation.total(); + return { + title: this.queries.title(), + count: total == null ? undefined : total.toLocaleString(), + }; + }); + + protected readonly mobileTableLayout = computed( + () => this.isMobile() && this.preferences.viewMode() === 'table', + ); + protected readonly layoutClasses = computed(() => { + const page = 'app-page pb-0!'; + const row = 'flex items-start gap-7'; + const column = 'min-w-0 flex-1'; + + if (this.mobileTableLayout()) { + return { + page: cn(page, 'h-[calc(100dvh-var(--mobile-topbar-height))] overflow-hidden'), + row: cn(row, 'min-h-0 flex-1'), + column: cn(column, 'flex min-h-0 flex-col h-full'), + }; + } + + if (this.isMobile()) { + return {page, row, column: cn(column, 'pb-8')}; + } + + return { + page, + row, + column: cn( + column, + 'flex min-h-0 flex-col h-[calc(100dvh-var(--page-stuck-offset,0px))]', + this.preferences.viewMode() === 'table' && 'pb-4', + ), + }; + }); + protected readonly railClass = computed(() => + cn( + 'flex max-h-[calc(100dvh-var(--page-stuck-offset,0px))] w-[236px] shrink-0 flex-col', + this.preferences.viewMode() === 'grid' && 'box-content border-l border-border/70 pl-6', + ), + ); + protected readonly gridBoxClass = computed(() => cn('md:pb-8', !this.railVisible() && 'md:-mr-8 md:pr-8')); + protected readonly chipsBandClass = computed(() => + cn( + 'sticky top-[var(--page-stuck-offset,0px)] z-10 -mx-4 bg-page px-4', + this.isMobile() ? 'pb-1.5' : 'pb-3', + this.headerRef()?.isStuck() && + 'shadow-[0_1px_0_0_color-mix(in_srgb,var(--color-border)_70%,transparent)]', + ), + ); + protected readonly hairlineStripClass = computed(() => + cn( + 'sticky top-[var(--page-stuck-offset,0px)] z-10 -mx-4 h-0 border-b', + this.headerRef()?.isStuck() ? 'border-border/70' : 'border-transparent', + ), + ); + + constructor() { + effect(() => { + const range = this.gridRef()?.renderedRange() ?? this.tableRef()?.renderedRange(); + if (range) { + untracked(() => this.presentation.onRenderedRange(range)); + } + }); + + effect(() => { + const title = this.pageHeader().title; + if (title) { + this.pageTitle.setPageTitle(title); + } + }); + + installBrowseSelectionShortcuts({ + enabled: () => this.selectionEnabled(), + active: () => this.selection.active(), + suspended: () => this.menuOpenBookId() !== null, + clear: () => this.selection.clear(), + selectAll: () => this.selection.selectAll(), + onEscapeWhileInactive: () => { + if (this.mobileSelectMode()) { + this.mobileSelectMode.set(false); + } + }, + clickAwayExempt: SELECTION_CLICK_AWAY_EXEMPT, + }); + } + + protected detailLineFor(book: BookSummary): string | null { + const key = this.detailLineKey(); + return key === null ? null : this.detailLines.lineFor(key, book); + } + + private squareCoversFor(books: readonly BookSummary[]): boolean { + const scope = this.scope(); + if (scope?.kind === 'library') { + const formats = this.libraryService.libraries() + .find(library => library.id === scope.entityId)?.allowedFormats; + if (formats?.length === 1 && formats[0] === 'AUDIOBOOK') { + return true; + } + } + return books.length > 0 + && books.every(book => book.primaryFile?.bookType === 'AUDIOBOOK'); + } + + protected onDensityChange(direction: GridDensityDirection): void { + const grid = this.gridRef()?.densityGrid(); + if (grid) { + this.gridDensity.adjust(direction, grid); + } + } + + protected onMobileSelectToggle(): void { + if (this.mobileSelectMode()) { + this.selection.clear(); + this.mobileSelectMode.set(false); + return; + } + this.mobileSelectMode.set(true); + } + + protected onBookDetailRequested(book: BookSummary): void { + this.bookNavigation.openBook(book.id, this.books().map(presented => presented.id)); + } + + protected onFiltersToggle(): void { + if (this.isMobile()) { + this.urlState.openFilterPage(); + return; + } + const next = !this.railOpen(); + this.railOpen.set(next); + this.localStorage.set(RAIL_OPEN_STORAGE_KEY, next); + } + + protected onToggleFacet(toggle: BrowseFilterToggle): void { + this.urlState.setFacets(toggleBrowseFacetValue( + this.urlState.facets(), + toggle.key, + toggle.value, + toggle.selected, + )); + } + + protected onCommitFacetRange(commit: BrowseFilterRangeCommit): void { + this.urlState.setFacetRange( + withBrowseFacetRange(this.urlState.facets(), commit.key, commit.min, commit.max, this.queries.definitions()), + ); + } + + protected onClearQuery(): void { + this.searchDraft.set(''); + this.urlState.clearQuery(); + } + + protected onClearAllFilters(): void { + this.searchDraft.set(''); + this.urlState.clearFilters(); + } + + protected onSortDirectionChange(term: BookSortTerm): void { + this.preferences.setSortTerms([term, ...this.sortTerms().slice(1)]); + } + + protected onRandomSortRequested(): void { + this.shuffleGeneration.update(generation => generation + 1); + void this.bookQuery.restartInfinitePage(this.params()); + } + + protected async onMultiSortRequested(): Promise { + const ref = await this.dialogLauncher.openMultiSortDialog({ + terms: this.sortTerms(), + options: this.sortOptions(), + saveDefaultFor: this.queries.title(), + }); + ref?.onClose.pipe(take(1)).subscribe((result?: BookBrowseMultiSortDialogResult) => { + if (!result) { + return; + } + this.preferences.setSortTerms(result.terms); + if (result.saveAsDefault) { + this.preferences.saveSortDefault(result.terms); + } + }); + } +} diff --git a/frontend/src/app/features/book/browse/book-browse-preferences.ts b/frontend/src/app/features/book/browse/book-browse-preferences.ts new file mode 100644 index 000000000..de916dccf --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-preferences.ts @@ -0,0 +1,152 @@ +import {computed, inject, linkedSignal, type Signal} from '@angular/core'; +import {TranslocoService} from '@jsverse/transloco'; +import {MessageService} from '@openng/optimus-ui/api'; + +import { + type EntityViewPreference, + type TableColumnPreference, + UserService, +} from '../../settings/user-management/user.service'; +import { + entityViewMode, + entityViewSortCriteria, + entityViewSortPatch, + findEntityViewPreferenceOverride, + upsertEntityViewPreference, + type EntityViewPreferenceContext, +} from '../../settings/user-management/entity-view-preferences'; +import {browseSortCriteria} from '../../../shared/browse/sort'; +import { + DEFAULT_BOOK_SORT_TERMS, + sortTermsToken, + type BookQuerySortKey, + type BookSortTerm, +} from '../data/book-query-params'; +import { + bookColumnOptions, + bookVisibleColumnOptions, + normalizeBookColumnPreferences, + type BookBrowseColumnVisibilityChange, +} from './book-browse-columns'; +import {bookSortTermsFromCriteria} from './book-browse-sort'; +import {type BookBrowseUrlState, type BookBrowseViewMode} from './book-browse-url-state'; + +export interface BookBrowsePreferencesOptions { + readonly context: Signal; + readonly availableSortKeys: Signal>; + readonly urlState: BookBrowseUrlState; +} + +export function createBookBrowsePreferences({context, availableSortKeys, urlState}: BookBrowsePreferencesOptions) { + const userService = inject(UserService); + const messages = inject(MessageService); + const transloco = inject(TranslocoService); + const entityViewPreferences = computed(() => userService.currentUser()?.userSettings.entityViewPreferences); + + const viewMode = computed(() => + urlState.view() ?? (entityViewMode(entityViewPreferences(), context()) === 'TABLE' ? 'table' : 'grid')); + const formatPill = computed(() => entityViewPreferences()?.global?.overlayBookType ?? true); + + const defaultSortTerms = computed(() => { + const preferences = entityViewPreferences(); + const available = availableSortKeys(); + const scope = context(); + const candidates = [ + scope ? findEntityViewPreferenceOverride(preferences, scope) : undefined, + preferences?.global, + ]; + for (const candidate of candidates) { + if (!candidate) { + continue; + } + const terms = bookSortTermsFromCriteria(entityViewSortCriteria(candidate)) + .filter(term => available.size === 0 || available.has(term.key)); + if (terms.length > 0) { + return terms; + } + } + return DEFAULT_BOOK_SORT_TERMS; + }); + const sortTerms = computed(() => { + const terms = urlState.sortTerms(); + return terms.length > 0 ? terms : defaultSortTerms(); + }); + const isDefaultSort = (terms: readonly BookSortTerm[]): boolean => + sortTermsToken(terms) === sortTermsToken(defaultSortTerms()); + + const columnPreferences = linkedSignal(() => + normalizeBookColumnPreferences( + userService.currentUser()?.userSettings.tableColumnPreference, + ), + ); + const columnOptions = computed(() => bookColumnOptions(columnPreferences())); + const visibleColumns = computed(() => bookVisibleColumnOptions(columnPreferences())); + + function onSaveError(): void { + messages.add({ + severity: 'error', + summary: transloco.translate('common.error'), + detail: transloco.translate('settingsView.saveFailedDetail'), + }); + } + + function persistColumnPreferences(): void { + const user = userService.currentUser(); + if (user) { + userService.updateUserSetting(user.id, 'tableColumnPreference', columnPreferences(), onSaveError); + } + } + + function updateViewPreference(patch: Partial): void { + const user = userService.currentUser(); + if (!user) { + return; + } + const preferences = upsertEntityViewPreference( + user.userSettings.entityViewPreferences, + context(), + patch, + ); + userService.updateUserSetting(user.id, 'entityViewPreferences', preferences, onSaveError); + } + + return { + viewMode, + formatPill, + sortTerms, + defaultSortTerms, + isDefaultSort, + columnOptions, + visibleColumns, + + setSortTerms(terms: readonly BookSortTerm[]): void { + const next = terms.length > 0 ? terms : DEFAULT_BOOK_SORT_TERMS; + const collapsesMultiSort = sortTerms().length > 1 && next.length === 1; + urlState.setSortToken(isDefaultSort(next) ? null : sortTermsToken(next), !collapsesMultiSort); + }, + + setColumnVisibility(change: BookBrowseColumnVisibilityChange): void { + const column = columnOptions().find(option => option.field === change.field); + if (!column?.hideable) { + return; + } + columnPreferences.update(preferences => preferences.map(preference => + preference.field === change.field + ? {...preference, visible: change.visible} + : preference, + )); + persistColumnPreferences(); + }, + + resetColumns(): void { + columnPreferences.set(normalizeBookColumnPreferences(undefined)); + persistColumnPreferences(); + }, + + saveSortDefault(terms: readonly BookSortTerm[]): void { + updateViewPreference(entityViewSortPatch( + browseSortCriteria(terms.length > 0 ? terms : DEFAULT_BOOK_SORT_TERMS), + )); + }, + }; +} diff --git a/frontend/src/app/features/book/browse/book-browse-queries.ts b/frontend/src/app/features/book/browse/book-browse-queries.ts new file mode 100644 index 000000000..4e581475f --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-queries.ts @@ -0,0 +1,119 @@ +import {computed, inject, type Signal} from '@angular/core'; +import {toSignal} from '@angular/core/rxjs-interop'; +import {TranslocoService} from '@jsverse/transloco'; +import {injectQuery} from '@tanstack/angular-query-experimental'; + +import {normalizeRemoteSearchTerm} from '../../../shared/util/search-terms'; +import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service'; +import { + EMPTY_FACET_SELECTION, + type BookCollectionFilterParams, + type BookQueryFacetKey, + type FacetValueMap, +} from '../data/book-query-params'; +import {type BrowseFacetResult} from '../../../core/data/browse.models'; +import {BookQueryService} from '../data/book-query.service'; +import {ShelfDefinitionQueryService} from '../data/shelf-definition-query.service'; +import {LibraryService} from '../service/library.service'; +import {UserService} from '../../settings/user-management/user.service'; +import {type LibraryShelfMenuTarget} from '../../../shared/layout/navigation/library-shelf-menu-target.model'; +import {libraryShelfMenuAvailable} from '../components/library-shelf-menu/library-shelf-menu-items.component'; +import { + browseFilterGroups, + browseFilterChips, + browseFrozenFacetOrders, + type BrowseFacetDefinitions, + type BrowseFilterChip, + type BrowseFilterGroup, + type BrowseFrozenFacetOrders, +} from '../../../shared/browse/facets'; +import {bookFacetDefinitions, bookFacetLabelDeps} from './book-browse-facet-definitions'; +import { + bookBrowseScopeMenuTarget, + bookBrowseScopeTitle, + scopedFacetSelection, + type BookBrowseScope, +} from './book-browse-scope'; + +export interface BookBrowseQueriesOptions { + readonly selection: Signal; + readonly query: Signal; + readonly scope: Signal; + readonly enabled?: Signal; +} + +export function createBookBrowseQueries({selection, query, scope, enabled}: BookBrowseQueriesOptions) { + const bookQuery = inject(BookQueryService); + const transloco = inject(TranslocoService); + const libraryService = inject(LibraryService); + const magicShelfService = inject(MagicShelfService); + const shelfDefinitionQuery = inject(ShelfDefinitionQueryService); + const userService = inject(UserService); + const activeLang = toSignal(transloco.langChanges$, {initialValue: transloco.getActiveLang()}); + + const collectionParams = computed(() => ({ + facets: scopedFacetSelection(selection(), scope()), + facetLogic: 'or', + query: normalizeRemoteSearchTerm(query()) || undefined, + })); + const scopeFacetsQuery = injectQuery(() => bookQuery.facets({ + facets: scopedFacetSelection(EMPTY_FACET_SELECTION, scope()), + facetLogic: 'or', + })); + const facetsQuery = injectQuery(() => ({ + ...bookQuery.facets(collectionParams()), + enabled: enabled?.() ?? true, + placeholderData: (previous: BrowseFacetResult | undefined) => previous, + })); + const shelfDefinitionsQuery = injectQuery(() => shelfDefinitionQuery.definitions()); + const shelfDefinitions = computed(() => shelfDefinitionsQuery.data() ?? []); + + const definitions = computed>(() => { + activeLang(); + return bookFacetDefinitions(bookFacetLabelDeps( + shelfDefinitions(), + libraryService.libraries(), + key => transloco.translate(key), + )); + }); + const frozen = computed(() => { + const data = scopeFacetsQuery.data(); + return data ? browseFrozenFacetOrders(data.facets, definitions()) : undefined; + }); + const railGroups = computed[]>(() => + browseFilterGroups(facetsQuery.data()?.facets ?? [], frozen(), definitions(), selection())); + const chips = computed[]>(() => + browseFilterChips(scopeFacetsQuery.data()?.facets ?? [], frozen(), definitions(), selection())); + const title = computed(() => { + activeLang(); + return bookBrowseScopeTitle(scope(), libraryService.libraries(), shelfDefinitions(), magicShelfService.shelves(), { + allBooks: transloco.translate('book.browser.labels.allBooks'), + unshelved: transloco.translate('book.browser.labels.unshelvedBooks'), + }); + }); + const searchHint = computed(() => { + activeLang(); + return transloco.translate(`browse.rail.searchScope.${scope()?.kind ?? 'allBooks'}`); + }); + const actionTarget = computed(() => { + const target = bookBrowseScopeMenuTarget( + scope(), + libraryService.libraries(), + shelfDefinitions(), + magicShelfService.shelves(), + ); + return target && libraryShelfMenuAvailable(target, userService.currentUser()) ? target : null; + }); + + return { + collectionParams, + definitions, + sortTokens: computed(() => scopeFacetsQuery.data()?.sortTokens ?? []), + pending: computed(() => facetsQuery.isPending()), + chips, + railGroups, + title, + searchHint, + actionTarget, + }; +} diff --git a/frontend/src/app/features/book/browse/book-browse-scope.spec.ts b/frontend/src/app/features/book/browse/book-browse-scope.spec.ts new file mode 100644 index 000000000..a055497b1 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-scope.spec.ts @@ -0,0 +1,42 @@ +import {convertToParamMap} from '@angular/router'; +import {describe, expect, it} from 'vitest'; + +import {EMPTY_FACET_SELECTION} from '../data/book-query-params'; +import {bookBrowseScope, scopedFacetSelection} from './book-browse-scope'; + +describe('bookBrowseScope', () => { + it('maps each scoped route onto its stable facet', () => { + expect(bookBrowseScope(convertToParamMap({libraryId: '3'}), {})) + .toEqual({kind: 'library', entityId: 3, facetKey: 'library', facetValue: '3'}); + expect(bookBrowseScope(convertToParamMap({shelfId: '7'}), {})) + .toEqual({kind: 'shelf', entityId: 7, facetKey: 'shelf', facetValue: '7'}); + expect(bookBrowseScope(convertToParamMap({magicShelfId: '9'}), {})) + .toEqual({kind: 'magicShelf', entityId: 9, facetKey: 'shelf', facetValue: 'magic:9'}); + expect(bookBrowseScope(convertToParamMap({}), {browseScope: 'unshelved'})) + .toEqual({kind: 'unshelved', facetKey: 'shelf_status', facetValue: 'unshelved'}); + }); + + it('treats unscoped and malformed routes as all books', () => { + expect(bookBrowseScope(convertToParamMap({}), {})).toBeNull(); + expect(bookBrowseScope(convertToParamMap({libraryId: 'abc'}), {})).toBeNull(); + expect(bookBrowseScope(convertToParamMap({libraryId: '-2'}), {})).toBeNull(); + }); +}); + +describe('scopedFacetSelection', () => { + it('passes selections through unchanged without a scope', () => { + const selection = {genre: ['Fantasy']}; + expect(scopedFacetSelection(selection, null)).toBe(selection); + }); + + it('gives the scope sole ownership of its facet key, even on an empty selection', () => { + const library = bookBrowseScope(convertToParamMap({libraryId: '3'}), {}); + expect(scopedFacetSelection({genre: ['Fantasy'], library: ['99']}, library)).toEqual({ + genre: ['Fantasy'], + library: ['3'], + }); + + const unshelved = bookBrowseScope(convertToParamMap({}), {browseScope: 'unshelved'}); + expect(scopedFacetSelection(EMPTY_FACET_SELECTION, unshelved)).toEqual({shelf_status: ['unshelved']}); + }); +}); diff --git a/frontend/src/app/features/book/browse/book-browse-scope.ts b/frontend/src/app/features/book/browse/book-browse-scope.ts new file mode 100644 index 000000000..9887ddff3 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-scope.ts @@ -0,0 +1,137 @@ +import {inject} from '@angular/core'; +import {Router, type CanActivateChildFn, type ParamMap} from '@angular/router'; + +import {pinBrowseFacetValue} from '../../../shared/browse/facets'; +import {type LibraryShelfMenuTarget} from '../../../shared/layout/navigation/library-shelf-menu-target.model'; +import {type EntityViewPreferenceContext} from '../../settings/user-management/entity-view-preferences'; +import {type FacetValueMap} from '../data/book-query-params'; + +export type BookBrowseScope = + | {kind: 'library'; entityId: number; facetKey: 'library'; facetValue: string} + | {kind: 'shelf'; entityId: number; facetKey: 'shelf'; facetValue: string} + | {kind: 'magicShelf'; entityId: number; facetKey: 'shelf'; facetValue: string} + | {kind: 'unshelved'; facetKey: 'shelf_status'; facetValue: 'unshelved'}; + +export interface BookBrowseRouteData { + browseScope?: 'unshelved'; +} + +export const validBookBrowseScope: CanActivateChildFn = route => { + const invalid = ['libraryId', 'shelfId', 'magicShelfId'].some(key => + route.paramMap.has(key) && positiveId(route.paramMap.get(key)) === null); + return invalid ? inject(Router).createUrlTree(['/dashboard']) : true; +}; + +export function bookBrowseScope( + paramMap: ParamMap, + routeData: BookBrowseRouteData, +): BookBrowseScope | null { + const libraryId = positiveId(paramMap.get('libraryId')); + if (libraryId !== null) { + return {kind: 'library', entityId: libraryId, facetKey: 'library', facetValue: `${libraryId}`}; + } + + const shelfId = positiveId(paramMap.get('shelfId')); + if (shelfId !== null) { + return {kind: 'shelf', entityId: shelfId, facetKey: 'shelf', facetValue: `${shelfId}`}; + } + + const magicShelfId = positiveId(paramMap.get('magicShelfId')); + if (magicShelfId !== null) { + return { + kind: 'magicShelf', + entityId: magicShelfId, + facetKey: 'shelf', + facetValue: `magic:${magicShelfId}`, + }; + } + + if (routeData.browseScope === 'unshelved') { + return {kind: 'unshelved', facetKey: 'shelf_status', facetValue: 'unshelved'}; + } + + return null; +} + +export function scopedFacetSelection( + selection: FacetValueMap, + scope: BookBrowseScope | null, +): FacetValueMap { + return scope ? pinBrowseFacetValue(selection, scope.facetKey, scope.facetValue) : selection; +} + +export function bookBrowseScopeTitle( + scope: BookBrowseScope | null, + libraries: readonly {id?: number | null; name: string}[], + shelves: readonly {id?: number | null; name: string}[], + magicShelves: readonly {id?: number | null; name: string}[], + labels: {readonly allBooks: string; readonly unshelved: string}, +): string { + switch (scope?.kind) { + case 'library': + return libraries.find(library => library.id === scope.entityId)?.name ?? ''; + case 'shelf': + return shelves.find(shelf => shelf.id === scope.entityId)?.name ?? ''; + case 'magicShelf': + return magicShelves.find(shelf => shelf.id === scope.entityId)?.name ?? ''; + case 'unshelved': + return labels.unshelved; + case undefined: + return labels.allBooks; + } +} + +export function bookBrowseScopePreferenceContext( + scope: BookBrowseScope | null, +): EntityViewPreferenceContext | null { + switch (scope?.kind) { + case 'library': + return {entityType: 'LIBRARY', entityId: scope.entityId}; + case 'shelf': + return {entityType: 'SHELF', entityId: scope.entityId}; + case 'magicShelf': + return {entityType: 'MAGIC_SHELF', entityId: scope.entityId}; + case 'unshelved': + case undefined: + return null; + } +} + +export function bookBrowseScopeMenuTarget( + scope: BookBrowseScope | null, + libraries: readonly {id?: number | null; name: string}[], + shelves: readonly {id: number; name: string; userId: number; publicShelf?: boolean}[], + magicShelves: readonly {id?: number | null; name: string; filterJson: string; isPublic?: boolean}[], +): LibraryShelfMenuTarget | null { + switch (scope?.kind) { + case 'library': { + const library = libraries.find(candidate => candidate.id === scope.entityId); + return library?.id == null + ? null + : {type: 'library', entity: {id: library.id, name: library.name}}; + } + case 'shelf': { + const shelf = shelves.find(candidate => candidate.id === scope.entityId); + return shelf + ? {type: 'shelf', entity: {id: shelf.id, name: shelf.name, userId: shelf.userId, publicShelf: shelf.publicShelf}} + : null; + } + case 'magicShelf': { + const shelf = magicShelves.find(candidate => candidate.id === scope.entityId); + return shelf?.id == null + ? null + : { + type: 'magicShelf', + entity: {id: shelf.id, name: shelf.name, filterJson: shelf.filterJson, isPublic: shelf.isPublic}, + }; + } + case 'unshelved': + case undefined: + return null; + } +} + +function positiveId(raw: string | null): number | null { + const id = Number(raw); + return raw !== null && Number.isSafeInteger(id) && id > 0 ? id : null; +} diff --git a/frontend/src/app/features/book/browse/book-browse-toolbar.component.html b/frontend/src/app/features/book/browse/book-browse-toolbar.component.html new file mode 100644 index 000000000..e8c73f216 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-toolbar.component.html @@ -0,0 +1,185 @@ +