From a2f41b29d84f3ce2b965990f00982001a628c101 Mon Sep 17 00:00:00 2001 From: Alex <25013571+alexhb1@users.noreply.github.com> Date: Sat, 26 Sep 2026 12:55:45 +0100 Subject: [PATCH] feat(ui): paginated book browser page (#2573) --- frontend/src/app/app.routes.spec.ts | 17 +- frontend/src/app/app.routes.ts | 22 +- .../book-browse-bulk-bar.component.html | 143 ++++++ .../book-browse-bulk-bar.component.spec.ts | 152 ++++++ .../browse/book-browse-bulk-bar.component.ts | 165 ++++++ .../browse/book-browse-bulk-commands.spec.ts | 111 ++++ .../book/browse/book-browse-bulk-commands.ts | 219 ++++++++ .../book-browse-detail-line.service.spec.ts | 45 ++ .../browse/book-browse-detail-line.service.ts | 72 +++ .../book-browse-filter-page.component.ts | 151 ++++++ ...book-browse-multi-sort-dialog.component.ts | 59 +++ ...book-browse-multi-sort-editor.component.ts | 164 ++++++ .../browse/book-browse-page.component.html | 174 +++++++ .../browse/book-browse-page.component.spec.ts | 380 ++++++++++++++ .../book/browse/book-browse-page.component.ts | 478 ++++++++++++++++++ .../book/browse/book-browse-preferences.ts | 152 ++++++ .../book/browse/book-browse-queries.ts | 119 +++++ .../book/browse/book-browse-scope.spec.ts | 42 ++ .../features/book/browse/book-browse-scope.ts | 137 +++++ .../browse/book-browse-toolbar.component.html | 185 +++++++ .../book-browse-toolbar.component.spec.ts | 97 ++++ .../browse/book-browse-toolbar.component.ts | 192 +++++++ .../book/browse/book-browse-url-state.ts | 91 ++++ .../book-dialog-helper.service.ts | 5 +- .../book-file-attacher.component.ts | 11 +- .../library-shelf-menu-items.component.ts | 146 ++++++ .../library-shelf-menu.component.spec.ts | 7 +- .../library-shelf-menu.component.ts | 136 +---- .../series-page/series-page.component.ts | 8 +- .../book/data/book-query-keys.spec.ts | 37 +- .../app/features/book/data/book-query-keys.ts | 11 + .../features/book/data/book-query-params.ts | 7 +- .../features/book/model/book-value-labels.ts | 56 +- .../book/service/book-menu.service.ts | 4 +- .../service/book-navigation.service.spec.ts | 9 +- .../book/service/book-navigation.service.ts | 17 + .../library-shelf-menu.service.spec.ts | 9 + .../service/library-shelf-menu.service.ts | 2 +- .../metadata-viewer.component.ts | 48 +- .../metadata-manager.component.spec.ts | 6 +- .../metadata-manager.component.ts | 8 +- .../entity-view-preferences.spec.ts | 22 + .../entity-view-preferences.ts | 66 +++ .../settings/user-management/user.service.ts | 21 +- .../library-shelf-menu-target.model.ts | 7 + .../layout/navigation/nav-item.model.ts | 2 +- .../services/dialog-launcher.service.ts | 12 + frontend/src/app/shared/util/held-signal.ts | 8 + frontend/src/assets/styles/overlays.scss | 4 + frontend/src/i18n/cs.json | 44 ++ frontend/src/i18n/da.json | 44 ++ frontend/src/i18n/de.json | 73 ++- frontend/src/i18n/en.json | 63 ++- frontend/src/i18n/es.json | 71 ++- frontend/src/i18n/fr.json | 68 ++- frontend/src/i18n/hr.json | 71 ++- frontend/src/i18n/hu.json | 54 +- frontend/src/i18n/id.json | 62 +++ frontend/src/i18n/it.json | 69 ++- frontend/src/i18n/ja.json | 70 ++- frontend/src/i18n/ko.json | 44 ++ frontend/src/i18n/nl.json | 57 ++- frontend/src/i18n/pl.json | 70 ++- frontend/src/i18n/pt.json | 70 ++- frontend/src/i18n/ru.json | 70 ++- frontend/src/i18n/sk.json | 50 +- frontend/src/i18n/sl.json | 73 ++- frontend/src/i18n/sv.json | 73 ++- frontend/src/i18n/uk.json | 73 ++- frontend/src/i18n/zh.json | 70 ++- 70 files changed, 5139 insertions(+), 236 deletions(-) create mode 100644 frontend/src/app/features/book/browse/book-browse-bulk-bar.component.html create mode 100644 frontend/src/app/features/book/browse/book-browse-bulk-bar.component.spec.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-bulk-bar.component.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-bulk-commands.spec.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-bulk-commands.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-detail-line.service.spec.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-detail-line.service.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-filter-page.component.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-multi-sort-dialog.component.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-multi-sort-editor.component.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-page.component.html create mode 100644 frontend/src/app/features/book/browse/book-browse-page.component.spec.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-page.component.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-preferences.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-queries.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-scope.spec.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-scope.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-toolbar.component.html create mode 100644 frontend/src/app/features/book/browse/book-browse-toolbar.component.spec.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-toolbar.component.ts create mode 100644 frontend/src/app/features/book/browse/book-browse-url-state.ts create mode 100644 frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu-items.component.ts create mode 100644 frontend/src/app/features/settings/user-management/entity-view-preferences.spec.ts create mode 100644 frontend/src/app/features/settings/user-management/entity-view-preferences.ts create mode 100644 frontend/src/app/shared/layout/navigation/library-shelf-menu-target.model.ts create mode 100644 frontend/src/app/shared/util/held-signal.ts 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) { + + + {{ 'book.sorting.saveAsDefault' | transloco: {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 @@ + + + + + @if (activeSortHasSecondaryAction()) { + + + + } + + + @for (option of commonOptions(); track option.id) { + + {{ option.labelKey | transloco }} + + } + @if (moreOptions().length > 0) { + @if (moreSortsExpanded()) { + + + @for (option of moreOptions(); track option.id) { + + {{ option.labelKey | transloco }} + + } + + + } + + + {{ (moreSortsExpanded() ? 'browse.showFewer' : 'browse.showAll') | transloco }} + + + } + @if (sortOptions().length > 0) { + + + {{ 'browse.sort.multiSort' | transloco }} + + } + + + + + + + + + + + + + + {{ 'browse.toolbar.viewMode' | transloco }} + @if (viewMode() === 'grid') { + + {{ 'browse.toolbar.density' | transloco }} + + + + + } + + + {{ 'book.viewMode.grid' | transloco }} + {{ 'book.viewMode.table' | transloco }} + + + @if (viewMode() !== 'grid') { + + {{ 'browse.toolbar.columns' | transloco }} + } + + + {{ 'browse.toolbar.showFilters' | transloco }} + + + @if (actionTarget(); as target) { + + {{ target.entity.name }} + + } + + + + + @for (section of columnSections(); track section.id) { + + {{ 'browse.toolbar.columnGroups.' + section.id | transloco }} + @for (column of section.columns; track column.field) { + + {{ column.labelKey | transloco }} + + } + + } + + + + {{ 'browse.toolbar.resetColumns' | transloco }} + + diff --git a/frontend/src/app/features/book/browse/book-browse-toolbar.component.spec.ts b/frontend/src/app/features/book/browse/book-browse-toolbar.component.spec.ts new file mode 100644 index 000000000..9c93d1bcc --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-toolbar.component.spec.ts @@ -0,0 +1,97 @@ +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {beforeEach, describe, expect, it} from 'vitest'; + +import {getTranslocoModule} from '../../../core/testing/transloco-testing'; +import {bookSortOptions} from './book-browse-sort'; +import {BookBrowseToolbarComponent} from './book-browse-toolbar.component'; +import {LibraryShelfMenuService} from '../service/library-shelf-menu.service'; + +describe('BookBrowseToolbarComponent', () => { + let fixture: ComponentFixture; + const host = (): HTMLElement => fixture.nativeElement as HTMLElement; + + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [BookBrowseToolbarComponent, getTranslocoModule()], + providers: [ + {provide: LibraryShelfMenuService, useValue: {}}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(BookBrowseToolbarComponent); + fixture.componentRef.setInput( + 'sortOptions', + bookSortOptions(['title', '-title', 'pageCount', '-pageCount']), + ); + fixture.componentRef.setInput('sortTerms', [{key: 'title', direction: 'asc'}]); + fixture.componentRef.setInput('viewMode', 'grid'); + fixture.componentRef.setInput('columnOptions', []); + fixture.componentRef.setInput('densitySmallerDisabled', false); + fixture.componentRef.setInput('densityLargerDisabled', false); + fixture.componentRef.setInput('filtersOpen', false); + fixture.componentRef.setInput('actionTarget', null); + await fixture.whenStable(); + }); + + it('routes the direction toggle through sortDirectionChange, not sortChange', async () => { + const sortChanges: unknown[] = []; + const directionChanges: unknown[] = []; + fixture.componentInstance.sortChange.subscribe(change => sortChanges.push(change)); + fixture.componentInstance.sortDirectionChange.subscribe(change => directionChanges.push(change)); + await fixture.whenStable(); + + buttonByLabel('Sort Descending').click(); + + expect(sortChanges).toEqual([]); + expect(directionChanges).toEqual([{key: 'title', direction: 'desc'}]); + }); + + it('marks no simple option active during multi-sort and treats picks as fresh sorts', async () => { + fixture.componentRef.setInput('sortTerms', [ + {key: 'title', direction: 'asc'}, + {key: 'pageCount', direction: 'desc'}, + ]); + const changes: unknown[] = []; + fixture.componentInstance.sortChange.subscribe(change => changes.push(change)); + await fixture.whenStable(); + + buttonByText('Title +1').click(); + await fixture.whenStable(); + + const titleItem = menuItemByText('Title'); + expect(titleItem.querySelector('svg')).toBeNull(); + expect(titleItem.textContent).toContain('1'); + + titleItem.click(); + expect(changes).toEqual([{key: 'title', direction: 'asc'}]); + }); + + function optionalButtonByLabel(label: string): HTMLButtonElement | null { + return host().querySelector(`button[aria-label="${label}"]`) as HTMLButtonElement | null; + } + + function buttonByLabel(label: string): HTMLButtonElement { + const button = optionalButtonByLabel(label); + if (!button) throw new Error(`Could not find button labelled "${label}"`); + return button; + } + + function buttonByText(text: string): HTMLButtonElement { + const button = buttonByTextOrNull(text); + if (!button) throw new Error(`Could not find button with text "${text}"`); + return button; + } + + function buttonByTextOrNull(text: string): HTMLButtonElement | null { + const buttons = Array.from(host().querySelectorAll('button')); + return buttons.find(candidate => candidate.textContent.trim() === text) ?? null; + } + + function menuItemByText(text: string): HTMLElement { + const items = Array.from(document.querySelectorAll('.cdk-overlay-container app-menu-item')) as HTMLElement[]; + const item = items.find(candidate => candidate.textContent.includes(text)); + if (!item) throw new Error(`Could not find menu item "${text}"`); + return item; + } +}); diff --git a/frontend/src/app/features/book/browse/book-browse-toolbar.component.ts b/frontend/src/app/features/book/browse/book-browse-toolbar.component.ts new file mode 100644 index 000000000..f23593a23 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-toolbar.component.ts @@ -0,0 +1,192 @@ +import { + Component, + computed, + input, + output, + signal, +} from '@angular/core'; +import {TranslocoPipe} from '@jsverse/transloco'; +import { + LucideChevronDown, + LucideChevronUp, + LucideDynamicIcon, + LucideEllipsis, + LucideFunnel, + LucideLayoutGrid, + LucideListOrdered, + LucideMinus, + LucidePlus, + LucideTableProperties, + type LucideIconData, +} from '@lucide/angular'; + +import {type GridDensityDirection} from '../../../shared/util/grid-density.util'; +import {DEFAULT_BOOK_SORT_TERMS, type BookSortTerm, type SortDirection} from '../data/book-query-params'; +import {AppButtonComponent} from '../../../shared/ui/button/app-button.component'; +import {connectedGroupClass, connectedItemClass} from '../../../shared/ui/connected-group'; +import {AppRadioGroupComponent} from '../../../shared/ui/radio-group/app-radio-group.component'; +import {AppMenuComponent} from '../../../shared/ui/menu/app-menu.component'; +import {AppMenuCheckboxComponent} from '../../../shared/ui/menu/app-menu-checkbox.component'; +import {AppMenuItemComponent} from '../../../shared/ui/menu/app-menu-item.component'; +import {AppMenuRadioComponent} from '../../../shared/ui/menu/app-menu-radio.component'; +import {AppMenuRadioGroupComponent} from '../../../shared/ui/menu/app-menu-radio-group.component'; +import {AppMenuSectionComponent} from '../../../shared/ui/menu/app-menu-section.component'; +import {AppMenuSeparatorComponent} from '../../../shared/ui/menu/app-menu-separator.component'; +import {AppMenuTriggerDirective} from '../../../shared/ui/menu/app-menu-trigger.directive'; +import { + bookColumnSections, + type BookBrowseColumnVisibilityChange, + type BookColumnOption, + type BookColumnSection, +} from './book-browse-columns'; +import {bookSortDirectionIcon, bookSortField, type BookSortOption} from './book-browse-sort'; +import {type BookBrowseViewMode} from './book-browse-url-state'; +import {type LibraryShelfMenuTarget} from '../../../shared/layout/navigation/library-shelf-menu-target.model'; +import {LibraryShelfMenuItemsComponent} from '../components/library-shelf-menu/library-shelf-menu-items.component'; + +@Component({ + selector: 'app-book-browse-toolbar', + imports: [ + TranslocoPipe, + AppButtonComponent, + AppRadioGroupComponent, + AppMenuComponent, + AppMenuCheckboxComponent, + AppMenuItemComponent, + AppMenuRadioComponent, + AppMenuRadioGroupComponent, + AppMenuSectionComponent, + AppMenuSeparatorComponent, + AppMenuTriggerDirective, + LibraryShelfMenuItemsComponent, + LucideDynamicIcon, + LucideEllipsis, + LucideFunnel, + ], + host: {class: 'contents'}, + templateUrl: './book-browse-toolbar.component.html', +}) +export class BookBrowseToolbarComponent { + readonly sortOptions = input.required(); + readonly sortTerms = input.required(); + readonly viewMode = input.required(); + readonly columnOptions = input.required(); + readonly densitySmallerDisabled = input.required(); + readonly densityLargerDisabled = input.required(); + readonly filtersOpen = input.required(); + readonly actionTarget = input.required(); + + readonly sortChange = output(); + readonly sortDirectionChange = output(); + readonly randomSortRequested = output(); + readonly multiSortRequested = output(); + readonly viewModeChange = output(); + readonly columnVisibilityChange = output(); + readonly columnsReset = output(); + readonly densityChange = output(); + readonly filtersToggle = output(); + readonly mobileSelectToggle = output(); + + protected readonly stepperItemClass = + 'w-10! flex-none justify-center px-0! text-text-muted pointer-coarse:w-12! [&_[data-menu-label]]:hidden'; + protected readonly smallerIcon: LucideIconData = LucideMinus.icon; + protected readonly largerIcon: LucideIconData = LucidePlus.icon; + protected readonly sortGroupClass = connectedGroupClass; + protected readonly sortFieldButtonClass = computed(() => connectedItemClass({ + first: true, + last: !this.activeSortHasSecondaryAction(), + })); + protected readonly sortDirectionButtonClass = connectedItemClass({first: false, last: true}); + + protected readonly commonOptions = computed(() => + this.sortOptions().filter(option => option.group === 'common')); + protected readonly moreOptions = computed(() => + this.sortOptions().filter(option => option.group === 'more')); + protected readonly multiSortActive = computed(() => this.sortTerms().length > 1); + protected readonly multiSortShortcut = computed(() => + this.multiSortActive() ? `+${this.sortTerms().length - 1}` : ''); + protected readonly moreSortsExpanded = signal(false); + protected readonly moreSortsToggleIcon = computed(() => + this.moreSortsExpanded() ? LucideChevronUp.icon : LucideChevronDown.icon); + + protected onSortMenuOpened(): void { + this.moreSortsExpanded.set(this.moreOptions().some(option => option.id === this.activeId())); + } + + protected readonly gridIcon: LucideIconData = LucideLayoutGrid.icon; + protected readonly tableIcon: LucideIconData = LucideTableProperties.icon; + protected readonly multiSortIcon: LucideIconData = LucideListOrdered.icon; + + private readonly primaryTerm = computed(() => this.sortTerms()[0] ?? DEFAULT_BOOK_SORT_TERMS[0]); + protected readonly activeId = computed(() => this.primaryTerm().key); + private readonly activeDirection = computed(() => this.primaryTerm().direction); + private readonly activeOption = computed(() => + this.sortOptions().find(option => option.id === this.activeId())); + protected readonly activeField = computed(() => this.activeOption() ?? bookSortField(this.activeId())); + private readonly activeSortIsRandom = computed(() => this.activeField().kind === 'random'); + protected readonly activeSortCanToggle = computed(() => + this.sortOptions().length === 0 || (this.activeOption()?.directions.length ?? 0) > 1); + protected readonly activeSortHasSecondaryAction = computed(() => + this.activeSortIsRandom() || this.activeSortCanToggle()); + protected readonly secondarySortActionLabelKey = computed(() => { + if (this.activeSortIsRandom()) { + return 'browse.toolbar.shuffleAgain'; + } + return this.activeDirection() === 'asc' + ? 'browse.toolbar.sortDescending' + : 'browse.toolbar.sortAscending'; + }); + protected readonly activeSortIcon = computed(() => + bookSortDirectionIcon(this.activeId(), this.activeDirection())); + protected readonly columnSections = computed(() => { + return bookColumnSections(this.columnOptions()); + }); + + protected selectView(viewMode: BookBrowseViewMode): void { + if (viewMode !== this.viewMode()) { + this.viewModeChange.emit(viewMode); + } + } + + protected onViewModeValue(viewMode: string | null): void { + if (viewMode === 'grid' || viewMode === 'table') this.selectView(viewMode); + } + + protected sortRankFor(option: BookSortOption): string { + if (!this.multiSortActive()) { + return ''; + } + const index = this.sortTerms().findIndex(term => term.key === option.id); + return index === -1 ? '' : `${index + 1}`; + } + + protected directionIconFor(option: BookSortOption): LucideIconData | undefined { + if (this.multiSortActive() || option.id !== this.activeId()) { + return undefined; + } + return this.activeSortIcon(); + } + + protected onSelect(option: BookSortOption): void { + const reselected = !this.multiSortActive() && option.id === this.activeId(); + const direction = reselected + ? this.otherDirection(option) ?? option.defaultDirection + : option.defaultDirection; + this.sortChange.emit({key: option.id, direction}); + } + + protected activateSecondarySortAction(): void { + if (this.activeSortIsRandom()) { + this.randomSortRequested.emit(); + return; + } + const nextDirection = this.otherDirection(this.activeOption()); + if (nextDirection) { + this.sortDirectionChange.emit({key: this.activeId(), direction: nextDirection}); + } + } + + private otherDirection(option: BookSortOption | undefined): SortDirection | undefined { + return option?.directions.find(direction => direction !== this.activeDirection()); + } +} diff --git a/frontend/src/app/features/book/browse/book-browse-url-state.ts b/frontend/src/app/features/book/browse/book-browse-url-state.ts new file mode 100644 index 000000000..371c897a1 --- /dev/null +++ b/frontend/src/app/features/book/browse/book-browse-url-state.ts @@ -0,0 +1,91 @@ +import {computed, inject} from '@angular/core'; +import {toSignal} from '@angular/core/rxjs-interop'; +import {ActivatedRoute, Router, type Params} from '@angular/router'; + +import { + bookFacetQueryParams, + parseFacetParams, + parseSortTermsToken, + type BookSortTerm, + type FacetValueMap, +} from '../data/book-query-params'; + +export type BookBrowseViewMode = 'grid' | 'table'; + +export type BookBrowseUrlState = ReturnType; + +export function createBookBrowseUrlState() { + const route = inject(ActivatedRoute); + const router = inject(Router); + const queryParamMap = toSignal(route.queryParamMap, { + initialValue: route.snapshot.queryParamMap, + }); + + const facets = computed(() => parseFacetParams(queryParamMap().getAll('facet'))); + const query = computed(() => (queryParamMap().get('query') ?? '').trim()); + const sortTerms = computed(() => + parseSortTermsToken(queryParamMap().get('sort'))); + const view = computed(() => { + const requested = queryParamMap().get('view'); + return requested === 'grid' || requested === 'table' ? requested : null; + }); + + const merge = (queryParams: Params, replaceUrl: boolean): void => { + void router.navigate([], { + relativeTo: route, + queryParams, + queryParamsHandling: 'merge', + replaceUrl, + }); + }; + + return { + facets, + query, + sortTerms, + view, + + setFacets(next: FacetValueMap): void { + merge(bookFacetQueryParams(next), false); + }, + + setFacetRange(next: FacetValueMap): void { + merge(bookFacetQueryParams(next), true); + }, + + setQuery(term: string): void { + merge({query: term || null}, true); + }, + + clearQuery(): void { + merge({query: null}, false); + }, + + clearFilters(): void { + merge({facet: null, query: null}, false); + }, + + setView(next: BookBrowseViewMode): void { + merge({view: next}, true); + }, + + setSortToken(token: string | null, replaceUrl: boolean): void { + merge({sort: token}, replaceUrl); + }, + + openFilterPage(): void { + void router.navigate(['filter'], {relativeTo: route, queryParamsHandling: 'preserve'}); + }, + + applyFilters(nextFacets: FacetValueMap, nextQuery: string): void { + void router.navigate(['..'], { + relativeTo: route, + queryParams: { + ...bookFacetQueryParams(nextFacets), + query: nextQuery || null, + }, + queryParamsHandling: 'merge', + }); + }, + }; +} diff --git a/frontend/src/app/features/book/components/book-browser/book-dialog-helper.service.ts b/frontend/src/app/features/book/components/book-browser/book-dialog-helper.service.ts index 42afbb7af..92ef67cd7 100644 --- a/frontend/src/app/features/book/components/book-browser/book-dialog-helper.service.ts +++ b/frontend/src/app/features/book/components/book-browser/book-dialog-helper.service.ts @@ -4,6 +4,7 @@ import {DialogLauncherService, DialogSize, DialogStyle} from '../../../../shared import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum'; import {Book} from '../../model/book.model'; import {type BookSenderSource} from '../book-sender/book-sender.component'; +import {type BookFileAttacherSourceBook} from '../book-file-attacher/book-file-attacher.component'; interface MetadataRefreshDialogContext { metadataRefreshType: MetadataRefreshType; @@ -193,7 +194,9 @@ export class BookDialogHelperService { }); } - async openBulkBookFileAttacherDialog(sourceBooks: Book[]): Promise { + async openBulkBookFileAttacherDialog( + sourceBooks: readonly BookFileAttacherSourceBook[], + ): Promise { return this.dialogLauncherService.launchLazyDialog(async () => { const {BookFileAttacherComponent} = await import('../book-file-attacher/book-file-attacher.component'); return this.openDialog(BookFileAttacherComponent, { diff --git a/frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.ts b/frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.ts index 358ac3dec..9e566bb01 100644 --- a/frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.ts +++ b/frontend/src/app/features/book/components/book-file-attacher/book-file-attacher.component.ts @@ -12,6 +12,13 @@ import { MessageService } from '@openng/optimus-ui/api'; import { TranslocoDirective, TranslocoPipe, TranslocoService } from '@jsverse/transloco'; import { AppSettingsService } from '../../../../shared/service/app-settings.service'; +export interface BookFileAttacherSourceBook { + id: number; + libraryId: number; + metadata?: {title?: string; authors?: string[]}; + primaryFile?: {extension?: string; bookType?: string; fileName?: string}; +} + @Component({ selector: 'app-book-file-attacher', standalone: true, @@ -29,7 +36,7 @@ import { AppSettingsService } from '../../../../shared/service/app-settings.serv export class BookFileAttacherComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChild('autocompleteWrapper') autocompleteWrapper!: ElementRef; - sourceBooks: Book[] = []; + sourceBooks: readonly BookFileAttacherSourceBook[] = []; targetBook: Book | null = null; moveFiles = false; isAttaching = false; @@ -128,7 +135,7 @@ export class BookFileAttacherComponent implements OnInit, AfterViewInit, OnDestr return authors ? `${title} - ${authors}` : title; } - getSourceFileInfo(book: Book): string { + getSourceFileInfo(book: BookFileAttacherSourceBook): string { const file = book.primaryFile; if (!file) return this.t.translate('book.fileAttacher.unknownFile'); const format = file.extension?.toUpperCase() || file.bookType || this.t.translate('book.fileAttacher.unknownFormat'); diff --git a/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu-items.component.ts b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu-items.component.ts new file mode 100644 index 000000000..6ccf11bae --- /dev/null +++ b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu-items.component.ts @@ -0,0 +1,146 @@ +import {ChangeDetectionStrategy, Component, computed, inject, input} from '@angular/core'; +import {TranslocoPipe} from '@jsverse/transloco'; + +import {AppMenuComponent} from '../../../../shared/ui/menu/app-menu.component'; +import {AppMenuItemComponent} from '../../../../shared/ui/menu/app-menu-item.component'; +import {AppMenuSectionComponent} from '../../../../shared/ui/menu/app-menu-section.component'; +import {AppMenuSeparatorComponent} from '../../../../shared/ui/menu/app-menu-separator.component'; +import {type LibraryShelfMenuTarget} from '../../../../shared/layout/navigation/library-shelf-menu-target.model'; +import {UserService} from '../../../settings/user-management/user.service'; +import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service'; + +export interface LibraryShelfMenuUser { + readonly id: number; + readonly permissions: { + readonly admin: boolean; + readonly canManageLibrary: boolean; + }; +} + +export function libraryShelfMenuAvailable( + target: LibraryShelfMenuTarget, + user: LibraryShelfMenuUser | null, +): boolean { + if (!user) { + return false; + } + return target.type !== 'library' + || user.permissions.admin + || user.permissions.canManageLibrary; +} + +@Component({ + selector: 'app-library-shelf-menu-items', + changeDetection: ChangeDetectionStrategy.OnPush, + host: {class: 'contents'}, + imports: [ + TranslocoPipe, + AppMenuComponent, + AppMenuItemComponent, + AppMenuSectionComponent, + AppMenuSeparatorComponent, + ], + template: ` + @let current = target(); + @switch (current.type) { + @case ('library') { + + {{ 'book.shelfMenuService.library.addPhysicalBook' | transloco }} + + + {{ 'book.shelfMenuService.library.bulkIsbnImport' | transloco }} + + + {{ 'book.shelfMenuService.library.rescanLibrary' | transloco }} + + + + {{ 'book.shelfMenuService.library.manageLibrary' | transloco }} + + + + + {{ 'book.shelfMenuService.library.editLibrary' | transloco }} + + + {{ 'book.shelfMenuService.library.customFetchMetadata' | transloco }} + + + {{ 'book.shelfMenuService.library.autoFetchMetadata' | transloco }} + + + {{ 'book.shelfMenuService.library.findDuplicates' | transloco }} + + + + {{ 'book.shelfMenuService.library.deleteLibrary' | transloco }} + + + } + @case ('shelf') { + @if (current.entity.publicShelf || !canManageShelf()) { + + @if (current.entity.publicShelf) { + {{ 'book.shelfMenuService.shelf.publicShelfPrefix' | transloco }} + } + {{ (canManageShelf() + ? 'book.shelfMenuService.shelf.optionsLabel' + : 'book.shelfMenuService.shelf.readOnly') | transloco }} + + } + + {{ 'book.shelfMenuService.shelf.editShelf' | transloco }} + + + + {{ 'book.shelfMenuService.shelf.deleteShelf' | transloco }} + + } + @case ('magicShelf') { + + {{ 'book.shelfMenuService.magicShelf.editMagicShelf' | transloco }} + + + {{ 'book.shelfMenuService.magicShelf.exportJson' | transloco }} + + + + {{ 'book.shelfMenuService.magicShelf.deleteMagicShelf' | transloco }} + + } + } + `, +}) +export class LibraryShelfMenuItemsComponent { + readonly target = input.required(); + + private readonly currentUser = inject(UserService).currentUser; + protected readonly actions = inject(LibraryShelfMenuService); + + protected readonly canManageShelf = computed(() => { + const target = this.target(); + return target.type === 'shelf' && target.entity.userId === this.currentUser()?.id; + }); + + protected readonly canManageMagicShelf = computed(() => { + const target = this.target(); + return target.type === 'magicShelf' + && (!target.entity.isPublic || !!this.currentUser()?.permissions.admin); + }); +} diff --git a/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.spec.ts b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.spec.ts index 4eca99808..1b60a9377 100644 --- a/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.spec.ts +++ b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.spec.ts @@ -34,8 +34,9 @@ describe('LibraryShelfMenuComponent', () => { name: 'library manager', user: {id: 3, permissions: {admin: false, canManageLibrary: true}}, target: {type: 'library', entity: {id: 7, name: 'Library', watch: true, paths: []}}, - labels: ['Add Physical Book', 'Import ISBNs from File', 'Edit Library', 'Re-scan Library', - 'Custom Fetch Metadata', 'Auto Fetch Metadata', 'Find Duplicates', 'Delete Library'], + labels: ['Add Physical Book', 'Import ISBNs from File', 'Re-scan Library', 'Manage Library', + 'Edit Library', 'Custom Fetch Metadata', 'Auto Fetch Metadata', 'Find Duplicates', + 'Delete Library'], disabled: 0, available: true, }, @@ -74,7 +75,7 @@ describe('LibraryShelfMenuComponent', () => { const menu = document.querySelector('app-menu[aria-label="Actions"]') as HTMLElement; const renderedLabels = Array.from(menu.querySelectorAll('app-menu-item')) - .map(item => item.textContent?.trim()); + .map(item => item.textContent!.trim()); expect(fixture.componentInstance.available()).toBe(available); expect(renderedLabels).toEqual(labels); expect(menu.querySelectorAll('app-menu-item[aria-disabled="true"]')).toHaveLength(disabled); diff --git a/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.ts b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.ts index f5468562b..5585f29d1 100644 --- a/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.ts +++ b/frontend/src/app/features/book/components/library-shelf-menu/library-shelf-menu.component.ts @@ -1,130 +1,27 @@ import {ChangeDetectionStrategy, Component, computed, inject, input, output, viewChild} from '@angular/core'; -import {LucideTrash2} from '@lucide/angular'; -import {TranslocoPipe} from '@jsverse/transloco'; import {AppMenuComponent} from '../../../../shared/ui/menu/app-menu.component'; import {AppMenuContentDirective} from '../../../../shared/ui/menu/app-menu-content.directive'; -import {AppMenuItemComponent} from '../../../../shared/ui/menu/app-menu-item.component'; -import {AppMenuSectionComponent} from '../../../../shared/ui/menu/app-menu-section.component'; -import {AppMenuSeparatorComponent} from '../../../../shared/ui/menu/app-menu-separator.component'; -import {MagicShelf} from '../../../magic-shelf/service/magic-shelf.service'; import {UserService} from '../../../settings/user-management/user.service'; -import {Library} from '../../model/library.model'; -import {Shelf} from '../../model/shelf.model'; -import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service'; +import {type LibraryShelfMenuTarget} from '../../../../shared/layout/navigation/library-shelf-menu-target.model'; +import {libraryShelfMenuAvailable, LibraryShelfMenuItemsComponent} from './library-shelf-menu-items.component'; -type Persisted = Omit & {id: number}; - -export type LibraryShelfMenuTarget = - | {type: 'library'; entity: Persisted} - | {type: 'shelf'; entity: Persisted} - | {type: 'magicShelf'; entity: Persisted}; +export type {LibraryShelfMenuTarget} from '../../../../shared/layout/navigation/library-shelf-menu-target.model'; @Component({ selector: 'app-library-shelf-menu', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, host: {class: 'contents'}, - imports: [ - TranslocoPipe, - AppMenuComponent, - AppMenuContentDirective, - AppMenuItemComponent, - AppMenuSectionComponent, - AppMenuSeparatorComponent, - ], + imports: [AppMenuComponent, AppMenuContentDirective, LibraryShelfMenuItemsComponent], template: ` - @let currentTarget = target(); @if (available()) { - @switch (currentTarget.type) { - @case ('library') { - - {{ 'book.shelfMenuService.library.addPhysicalBook' | transloco }} - - - {{ 'book.shelfMenuService.library.bulkIsbnImport' | transloco }} - - - - {{ 'book.shelfMenuService.library.editLibrary' | transloco }} - - - {{ 'book.shelfMenuService.library.rescanLibrary' | transloco }} - - - - {{ 'book.shelfMenuService.library.customFetchMetadata' | transloco }} - - - {{ 'book.shelfMenuService.library.autoFetchMetadata' | transloco }} - - - {{ 'book.shelfMenuService.library.findDuplicates' | transloco }} - - - - {{ 'book.shelfMenuService.library.deleteLibrary' | transloco }} - - } - @case ('shelf') { - @if (currentTarget.entity.publicShelf || !canManageShelf()) { - - @if (currentTarget.entity.publicShelf) { - {{ 'book.shelfMenuService.shelf.publicShelfPrefix' | transloco }} - } - {{ (canManageShelf() - ? 'book.shelfMenuService.shelf.optionsLabel' - : 'book.shelfMenuService.shelf.readOnly') | transloco }} - - } - - {{ 'book.shelfMenuService.shelf.editShelf' | transloco }} - - - - {{ 'book.shelfMenuService.shelf.deleteShelf' | transloco }} - - } - @case ('magicShelf') { - - {{ 'book.shelfMenuService.magicShelf.editMagicShelf' | transloco }} - - - {{ 'book.shelfMenuService.magicShelf.exportJson' | transloco }} - - - - {{ 'book.shelfMenuService.magicShelf.deleteMagicShelf' | transloco }} - - } - } + } @@ -139,25 +36,8 @@ export class LibraryShelfMenuComponent { readonly menu = viewChild.required(AppMenuComponent); private readonly currentUser = inject(UserService).currentUser; - protected readonly actions = inject(LibraryShelfMenuService); - protected readonly trashIcon = LucideTrash2.icon; - readonly available = computed(() => { - const user = this.currentUser(); - if (!user) return false; - return this.target().type !== 'library' - || user.permissions.admin - || user.permissions.canManageLibrary; - }); - - protected readonly canManageShelf = computed(() => { - const target = this.target(); - return target.type === 'shelf' && target.entity.userId === this.currentUser()?.id; - }); - - protected readonly canManageMagicShelf = computed(() => { - const target = this.target(); - return target.type === 'magicShelf' - && (!target.entity.isPublic || !!this.currentUser()?.permissions.admin); - }); + readonly available = computed( + () => libraryShelfMenuAvailable(this.target(), this.currentUser()), + ); } diff --git a/frontend/src/app/features/book/components/series-page/series-page.component.ts b/frontend/src/app/features/book/components/series-page/series-page.component.ts index 584c0e842..9da4232d8 100644 --- a/frontend/src/app/features/book/components/series-page/series-page.component.ts +++ b/frontend/src/app/features/book/components/series-page/series-page.component.ts @@ -454,7 +454,7 @@ export class SeriesPageComponent implements AfterViewChecked { } goToCategory(category: string): void { - this.handleMetadataClick("category", category); + this.handleMetadataClick("genre", category); } goToPublisher(publisher: string): void { @@ -467,11 +467,7 @@ export class SeriesPageComponent implements AfterViewChecked { ): void { this.router.navigate(["/all-books"], { queryParams: { - view: "grid", - sort: "title", - direction: "asc", - sidebar: true, - filter: `${filterKey}:${encodeURIComponent(filterValue)}`, + facet: `${filterKey}:${filterValue}`, }, }); } diff --git a/frontend/src/app/features/book/data/book-query-keys.spec.ts b/frontend/src/app/features/book/data/book-query-keys.spec.ts index bdb7689c2..655be6ccd 100644 --- a/frontend/src/app/features/book/data/book-query-keys.spec.ts +++ b/frontend/src/app/features/book/data/book-query-keys.spec.ts @@ -4,8 +4,9 @@ import { normalizeBookCollectionFilterParams, normalizeBookQueryParams, normalizeBookPageParams, + type BookPageParams, } from './book-query-params'; -import {bookQueryKeys} from './book-query-keys'; +import {bookCollectionKeys, bookQueryKeys} from './book-query-keys'; describe('book query keys', () => { const query = { @@ -54,3 +55,37 @@ describe('book query keys', () => { .toEqual([...recommendationPrefix]); }); }); + +const PARAMS: BookPageParams = { + query: 'dune', + facets: {genre: ['Science Fiction']}, + facetLogic: 'or', + sort: [{key: 'title', direction: 'asc'}], + size: 20, +}; + +describe('bookCollectionKeys', () => { + it('normalizes the params and keeps membership identity apart from ordering identity', () => { + const collection = bookCollectionKeys(PARAMS); + const equivalent = bookCollectionKeys({ + ...PARAMS, + query: ' dune ', + facets: {genre: ['Science Fiction', 'Science Fiction']}, + }); + expect(equivalent.filtersKey).toBe(collection.filtersKey); + expect(equivalent.listKey).toBe(collection.listKey); + + const largerPage: BookPageParams = {...PARAMS, size: 50}; + const resized = bookCollectionKeys(largerPage); + expect(resized.filtersKey).toBe(collection.filtersKey); + expect(resized.listKey).toBe(collection.listKey); + + const reordered = bookCollectionKeys({...PARAMS, sort: [{key: 'title', direction: 'desc'}]}); + expect(reordered.filtersKey).toBe(collection.filtersKey); + expect(reordered.listKey).not.toBe(collection.listKey); + + const refiltered = bookCollectionKeys({...PARAMS, query: 'foundation'}); + expect(refiltered.filtersKey).not.toBe(collection.filtersKey); + expect(refiltered.listKey).not.toBe(collection.listKey); + }); +}); diff --git a/frontend/src/app/features/book/data/book-query-keys.ts b/frontend/src/app/features/book/data/book-query-keys.ts index 2c0055dcf..8d915dc99 100644 --- a/frontend/src/app/features/book/data/book-query-keys.ts +++ b/frontend/src/app/features/book/data/book-query-keys.ts @@ -1,7 +1,11 @@ +import {hashKey} from '@tanstack/angular-query-experimental'; + import { BookCollectionFilterParams, BookPageParams, BookQueryParams, + normalizeBookCollectionFilterParams, + normalizeBookQueryParams, } from './book-query-params'; export const bookQueryKeys = { @@ -30,3 +34,10 @@ export const bookQueryKeys = { recommendation: (bookId: number, limit: number) => [...bookQueryKeys.recommendationQueries(bookId), {limit}] as const, }; + +export function bookCollectionKeys(params: BookQueryParams) { + return { + filtersKey: hashKey([normalizeBookCollectionFilterParams(params)]), + listKey: hashKey([normalizeBookQueryParams(params)]), + }; +} diff --git a/frontend/src/app/features/book/data/book-query-params.ts b/frontend/src/app/features/book/data/book-query-params.ts index b63af27e9..153689161 100644 --- a/frontend/src/app/features/book/data/book-query-params.ts +++ b/frontend/src/app/features/book/data/book-query-params.ts @@ -120,11 +120,14 @@ export function parseFacetParams(tokens: readonly string[]): FacetValueMap { if (!isBookQueryFacetKey(key)) { continue; } + const value = token.slice(separator + 1).trim(); const values = facets.get(key) ?? []; - values.push(token.slice(separator + 1)); + if (value && !values.includes(value)) { + values.push(value); + } facets.set(key, values); } - return normalizeFacetValueMap(Object.fromEntries(facets)); + return Object.fromEntries([...facets].filter(([, values]) => values.length > 0)); } export function bookFacetQueryParams(facets: FacetValueMap) { diff --git a/frontend/src/app/features/book/model/book-value-labels.ts b/frontend/src/app/features/book/model/book-value-labels.ts index d67e852fd..d79bf1a56 100644 --- a/frontend/src/app/features/book/model/book-value-labels.ts +++ b/frontend/src/app/features/book/model/book-value-labels.ts @@ -1,4 +1,52 @@ -import {type BrowseFacetBucket} from '../../../shared/browse/facet-ranges'; +import {type BrowseFacetBucket, formatRangeToken} from '../../../shared/browse/facet-ranges'; +import {ReadStatus} from './book.model'; + +interface RangeConfig { + id: number; + label: string; + min: number; + max: number; +} + +export const READ_STATUS_LABELS = { + [ReadStatus.UNREAD]: 'Unread', + [ReadStatus.READING]: 'Reading', + [ReadStatus.RE_READING]: 'Re-reading', + [ReadStatus.PARTIALLY_READ]: 'Partially Read', + [ReadStatus.PAUSED]: 'Paused', + [ReadStatus.READ]: 'Read', + [ReadStatus.WONT_READ]: 'Won\'t Read', + [ReadStatus.ABANDONED]: 'Abandoned', + [ReadStatus.UNSET]: 'Unset' +} satisfies Readonly>; + +export const PAGE_COUNT_RANGES: readonly RangeConfig[] = [ + {id: 0, label: '< 50 pages', min: 0, max: 50}, + {id: 1, label: '50–100 pages', min: 50, max: 100}, + {id: 2, label: '100–200 pages', min: 100, max: 200}, + {id: 3, label: '200–400 pages', min: 200, max: 400}, + {id: 4, label: '400–600 pages', min: 400, max: 600}, + {id: 5, label: '600–1000 pages', min: 600, max: 1000}, + {id: 6, label: '1000+ pages', min: 1000, max: Infinity} +]; + +export const AGE_RATING_OPTIONS: readonly RangeConfig[] = [ + {id: 0, min: 0, max: 6, label: 'All Ages'}, + {id: 6, min: 6, max: 10, label: '6+'}, + {id: 10, min: 10, max: 13, label: '10+'}, + {id: 13, min: 13, max: 16, label: '13+'}, + {id: 16, min: 16, max: 18, label: '16+'}, + {id: 18, min: 18, max: 21, label: '18+'}, + {id: 21, min: 21, max: Infinity, label: '21+'} +]; + +export const CONTENT_RATING_LABELS: Readonly> = { + 'EVERYONE': 'Everyone', + 'TEEN': 'Teen', + 'MATURE': 'Mature', + 'ADULT': 'Adult', + 'EXPLICIT': 'Explicit' +}; export interface MatchScoreBand extends BrowseFacetBucket { readonly labelKey: string; @@ -13,3 +61,9 @@ export const MATCH_SCORE_BANDS: readonly MatchScoreBand[] = [ {min: 30, max: 50, labelKey: 'weak'}, {min: 0, max: 30, labelKey: 'poor'}, ]; + +export function bookMatchScoreRangeToken(score: number): string | null { + const band = MATCH_SCORE_BANDS.find(candidate => + (candidate.min == null || score >= candidate.min) && (candidate.max == null || score <= candidate.max)); + return band ? formatRangeToken(band) : null; +} diff --git a/frontend/src/app/features/book/service/book-menu.service.ts b/frontend/src/app/features/book/service/book-menu.service.ts index be6492161..15e94d781 100644 --- a/frontend/src/app/features/book/service/book-menu.service.ts +++ b/frontend/src/app/features/book/service/book-menu.service.ts @@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core'; import {ConfirmationService, MenuItem, MessageService} from '@openng/optimus-ui/api'; import {BookService} from './book.service'; import {BookMetadataManageService} from './book-metadata-manage.service'; -import {AGE_RATING_OPTIONS, CONTENT_RATING_LABELS, readStatusLabels} from '../components/book-browser/book-filter/book-filter.config'; +import {AGE_RATING_OPTIONS, CONTENT_RATING_LABELS, READ_STATUS_LABELS} from '../model/book-value-labels'; import {ReadStatus} from '../model/book.model'; import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type'; import {finalize} from 'rxjs'; @@ -90,7 +90,7 @@ export class BookMenuService { items.push({ label: this.t.translate('book.menuService.menu.updateReadStatus'), icon: 'pi pi-book', - items: Object.entries(readStatusLabels).map(([status, label]) => ({ + items: Object.entries(READ_STATUS_LABELS).map(([status, label]) => ({ label, command: () => { this.confirmationService.confirm({ diff --git a/frontend/src/app/features/book/service/book-navigation.service.spec.ts b/frontend/src/app/features/book/service/book-navigation.service.spec.ts index f49b59564..fba4638b6 100644 --- a/frontend/src/app/features/book/service/book-navigation.service.spec.ts +++ b/frontend/src/app/features/book/service/book-navigation.service.spec.ts @@ -2,13 +2,19 @@ import {TestBed} from '@angular/core/testing'; import {Router} from '@angular/router'; import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {UserService} from '../../settings/user-management/user.service'; +import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service'; import {BookNavigationService} from './book-navigation.service'; const navigate = vi.fn(() => Promise.resolve(true)); function createService(): BookNavigationService { TestBed.configureTestingModule({ - providers: [{provide: Router, useValue: {navigate}}], + providers: [ + {provide: Router, useValue: {navigate}}, + {provide: UserService, useValue: {currentUser: () => null}}, + {provide: BookDialogHelperService, useValue: {openBookDetailsDialog: () => Promise.resolve()}}, + ], }); return TestBed.inject(BookNavigationService); } @@ -83,5 +89,4 @@ describe('BookNavigationService', () => { expect(navigate).toHaveBeenCalledWith([route]); }); - }); diff --git a/frontend/src/app/features/book/service/book-navigation.service.ts b/frontend/src/app/features/book/service/book-navigation.service.ts index edef4cdea..f1b957691 100644 --- a/frontend/src/app/features/book/service/book-navigation.service.ts +++ b/frontend/src/app/features/book/service/book-navigation.service.ts @@ -1,7 +1,9 @@ import {computed, inject, Injectable, signal} from '@angular/core'; import {Router} from '@angular/router'; +import {UserService} from '../../settings/user-management/user.service'; import {type BookFileResponse, type BookFileType, type BookSummary} from '../data/book-response.models'; +import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service'; export interface BookNavigationState { bookIds: number[]; @@ -13,6 +15,8 @@ export interface BookNavigationState { }) export class BookNavigationService { private readonly router = inject(Router); + private readonly userService = inject(UserService); + private readonly dialogHelper = inject(BookDialogHelperService); private readonly _navigationState = signal(null); readonly navigationState = this._navigationState.asReadonly(); @@ -73,6 +77,19 @@ export class BookNavigationService { void this.router.navigate(path); } + openBook(bookId: number, contextIds: number[]): void { + if (contextIds.length > 0) { + this.setNavigationContext(contextIds, bookId); + } + + const mode = this.userService.currentUser()?.userSettings.metadataCenterViewMode ?? 'route'; + if (mode === 'route') { + void this.router.navigate(['/book', bookId]); + return; + } + void this.dialogHelper.openBookDetailsDialog(bookId); + } + setNavigationContext(bookIds: number[], currentBookId: number): void { const currentIndex = bookIds.indexOf(currentBookId); if (currentIndex !== -1) { diff --git a/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts b/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts index 06fe6e106..860b6808a 100644 --- a/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts +++ b/frontend/src/app/features/book/service/library-shelf-menu.service.spec.ts @@ -114,6 +114,15 @@ describe('LibraryShelfMenuService', () => { expect(router.navigate).toHaveBeenNthCalledWith(2, ['/']); }); + it('returns home after deleting a shelf whose filter child route is open', () => { + router.url = '/shelf/11/books/filter?facet=genre:Fantasy'; + + service.deleteShelf({id: 11, name: 'Favorites'}); + confirmationService.confirm.mock.calls[0][0].accept(); + + expect(router.navigate).toHaveBeenCalledWith(['/']); + }); + it('copies magic-shelf JSON', async () => { const writeText = vi.fn(() => Promise.resolve()); vi.stubGlobal('navigator', {clipboard: {writeText}}); diff --git a/frontend/src/app/features/book/service/library-shelf-menu.service.ts b/frontend/src/app/features/book/service/library-shelf-menu.service.ts index 30a72ecdb..73dc9fa6a 100644 --- a/frontend/src/app/features/book/service/library-shelf-menu.service.ts +++ b/frontend/src/app/features/book/service/library-shelf-menu.service.ts @@ -223,7 +223,7 @@ export class LibraryShelfMenuService { private navigateHomeIfViewing(deletedTargetUrl: string): void { const currentPath = this.router.url.replace(/[?#].*$/, ''); - if (currentPath === deletedTargetUrl) { + if (currentPath === deletedTargetUrl || currentPath.startsWith(`${deletedTargetUrl}/`)) { void this.router.navigate(['/']); } } diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts index 73b3a74b0..077eff92b 100644 --- a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts @@ -29,7 +29,13 @@ import {BookDialogHelperService} from '../../../../book/components/book-browser/ import {LibraryService} from '../../../../book/service/library.service'; import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component'; import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; -import {AGE_RATING_OPTIONS, CONTENT_RATING_LABELS, matchScoreRanges, pageCountRanges} from '../../../../book/components/book-browser/book-filter/book-filter.config'; +import {formatRangeToken} from '../../../../../shared/browse/facet-ranges'; +import { + AGE_RATING_OPTIONS, + bookMatchScoreRangeToken, + CONTENT_RATING_LABELS, + PAGE_COUNT_RANGES, +} from '../../../../book/model/book-value-labels'; import {BookNavigationService} from '../../../../book/service/book-navigation.service'; import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service'; import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; @@ -837,7 +843,7 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked { } goToCategory(category: string): void { - this.handleMetadataClick('category', category); + this.handleMetadataClick('genre', category); } goToMood(mood: string): void { @@ -871,7 +877,7 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked { goToPublishedYear(publishedDate: string): void { const year = this.extractYear(publishedDate); if (year) { - this.handleMetadataClick('publishedDate', year); + this.handleMetadataClick('published_year', year); } } @@ -889,35 +895,35 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked { if (["MP3", "M4A", "M4B", "OPUS"].includes(filterValue)) { filterValue = 'AUDIOBOOK'; } - this.handleMetadataClick('bookType', filterValue); + this.handleMetadataClick('file_type', filterValue); } } goToReadStatus(status: ReadStatus): void { - this.handleMetadataClick('readStatus', status); + this.handleMetadataClick('read_status', status); } goToPageCountRange(pageCount: number): void { - const range = pageCountRanges.find(r => pageCount >= r.min && pageCount < r.max); - if (range) { - this.handleMetadataClick('pageCount', range.id.toString()); + const range = PAGE_COUNT_RANGES.find(r => pageCount >= r.min && pageCount < r.max); + const token = range && formatRangeToken({min: range.min, max: Number.isFinite(range.max) ? range.max : null}); + if (token) { + this.handleMetadataClick('page_count', token); } } goToMatchScoreRange(score: number): void { - const normalizedScore = score > 1 ? score / 100 : score; - const range = matchScoreRanges.find(r => normalizedScore >= r.min && normalizedScore < r.max); - if (range) { - this.handleMetadataClick('matchScore', range.id.toString()); + const token = bookMatchScoreRangeToken(score); + if (token) { + this.handleMetadataClick('match_score', token); } } goToAgeRating(ageRating: number): void { - this.handleMetadataClick('ageRating', ageRating.toString()); + this.handleMetadataClick('age_rating', ageRating.toString()); } goToContentRating(contentRating: string): void { - this.handleMetadataClick('contentRating', contentRating); + this.handleMetadataClick('content_rating', contentRating); } getAgeRatingLabel(ageRating: number | null | undefined): string { @@ -940,11 +946,7 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked { private navigateToFilteredBooks(filterKey: string, filterValue: string): void { this.router.navigate(['/all-books'], { queryParams: { - view: 'grid', - sort: 'title', - direction: 'asc', - sidebar: true, - filter: `${filterKey}:${encodeURIComponent(filterValue)}` + facet: `${filterKey}:${filterValue}`, } }); } @@ -1347,19 +1349,19 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked { } goToCharacter(character: string): void { - this.handleMetadataClick('comicCharacter', character); + this.handleMetadataClick('comic_character', character); } goToTeam(team: string): void { - this.handleMetadataClick('comicTeam', team); + this.handleMetadataClick('comic_team', team); } goToLocation(location: string): void { - this.handleMetadataClick('comicLocation', location); + this.handleMetadataClick('comic_location', location); } goToCreator(name: string, role: string): void { - this.handleMetadataClick('comicCreator', `${name}:${role}`); + this.handleMetadataClick('comic_creator', `${name}:${role}`); } // Audiobook metadata helpers diff --git a/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.spec.ts b/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.spec.ts index a5d0d5d88..fe072d01d 100644 --- a/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.spec.ts +++ b/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.spec.ts @@ -183,11 +183,7 @@ describe('MetadataManagerComponent', () => { component.onMetadataClick('authors', 'A&B'); expect(navigate).toHaveBeenCalledWith(['/all-books'], { queryParams: { - view: 'grid', - sort: 'title', - direction: 'asc', - sidebar: true, - filter: 'author:A%26B', + facet: 'author:A&B', } }); }); diff --git a/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.ts b/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.ts index 6dc0d59f7..1a3e82329 100644 --- a/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.ts +++ b/frontend/src/app/features/metadata/component/metadata-manager/metadata-manager.component.ts @@ -580,7 +580,7 @@ export class MetadataManagerComponent implements OnInit, OnDestroy { onMetadataClick(type: MetadataType, value: string): void { const filterKeyMap: Record = { authors: 'author', - categories: 'category', + categories: 'genre', moods: 'mood', tags: 'tag', series: 'series', @@ -594,11 +594,7 @@ export class MetadataManagerComponent implements OnInit, OnDestroy { navigateToFilteredBooks(filterKey: string, filterValue: string): void { this.router.navigate(['/all-books'], { queryParams: { - view: 'grid', - sort: 'title', - direction: 'asc', - sidebar: true, - filter: `${filterKey}:${encodeURIComponent(filterValue)}` + facet: `${filterKey}:${filterValue}`, } }); } diff --git a/frontend/src/app/features/settings/user-management/entity-view-preferences.spec.ts b/frontend/src/app/features/settings/user-management/entity-view-preferences.spec.ts new file mode 100644 index 000000000..1adb76326 --- /dev/null +++ b/frontend/src/app/features/settings/user-management/entity-view-preferences.spec.ts @@ -0,0 +1,22 @@ +import {describe, expect, it} from 'vitest'; + +import {findEntityViewPreferenceOverride, upsertEntityViewPreference} from './entity-view-preferences'; +import {type EntityViewPreferences} from './user.service'; + +const DEFAULTS: EntityViewPreferences = { + global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false, overlayBookType: true}, + overrides: null, +}; + +describe('entity view preferences with the backend default of null overrides', () => { + it('finds no override', () => { + expect(findEntityViewPreferenceOverride(DEFAULTS, {entityType: 'LIBRARY', entityId: 3})).toBeUndefined(); + }); + + it('adds the first override', () => { + const next = upsertEntityViewPreference(DEFAULTS, {entityType: 'LIBRARY', entityId: 3}, {view: 'TABLE'}); + + expect(next.overrides).toEqual([{entityType: 'LIBRARY', entityId: 3, preferences: {...DEFAULTS.global, view: 'TABLE'}}]); + expect(DEFAULTS.overrides).toBeNull(); + }); +}); diff --git a/frontend/src/app/features/settings/user-management/entity-view-preferences.ts b/frontend/src/app/features/settings/user-management/entity-view-preferences.ts new file mode 100644 index 000000000..4dfe41259 --- /dev/null +++ b/frontend/src/app/features/settings/user-management/entity-view-preferences.ts @@ -0,0 +1,66 @@ +import { + type EntityViewPreference, + type EntityViewPreferenceOverride, + type EntityViewPreferences, + type SortCriterion, +} from './user.service'; + +export type EntityViewPreferenceContext = Pick; + +const DEFAULT_GLOBAL_PREFERENCE: EntityViewPreference = { + sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false, overlayBookType: true, +}; + +export function entityViewSortCriteria(preference: EntityViewPreference | null | undefined): SortCriterion[] { + if (preference?.sortCriteria?.length) { + return preference.sortCriteria; + } + return preference?.sortKey && preference.sortDir + ? [{field: preference.sortKey, direction: preference.sortDir}] + : []; +} + +export function findEntityViewPreferenceOverride( + preferences: EntityViewPreferences | undefined, + context: EntityViewPreferenceContext, +): EntityViewPreference | undefined { + return preferences?.overrides?.find(override => + override.entityType === context.entityType && override.entityId === context.entityId, + )?.preferences; +} + +export function entityViewMode( + preferences: EntityViewPreferences | undefined, + context: EntityViewPreferenceContext | null, +): 'GRID' | 'TABLE' { + const override = context ? findEntityViewPreferenceOverride(preferences, context) : undefined; + return override?.view ?? preferences?.global?.view ?? 'GRID'; +} + +export function entityViewSortPatch(sortCriteria: readonly SortCriterion[]): Partial { + const primary = sortCriteria.at(0); + return {sortKey: primary?.field, sortDir: primary?.direction, sortCriteria: [...sortCriteria]}; +} + +export function upsertEntityViewPreference( + preferences: EntityViewPreferences | null | undefined, + context: EntityViewPreferenceContext | null, + patch: Partial, +): EntityViewPreferences { + const next = structuredClone({ + global: {...DEFAULT_GLOBAL_PREFERENCE, ...preferences?.global}, + overrides: preferences?.overrides ?? [], + }); + if (context === null) { + next.global = {...next.global, ...patch}; + return next; + } + const override = next.overrides.find(candidate => + candidate.entityType === context.entityType && candidate.entityId === context.entityId); + if (override) { + override.preferences = {...override.preferences, ...patch}; + } else { + next.overrides.push({...context, preferences: {...next.global, ...patch}}); + } + return next; +} diff --git a/frontend/src/app/features/settings/user-management/user.service.ts b/frontend/src/app/features/settings/user-management/user.service.ts index ecc3f1552..7483999d1 100644 --- a/frontend/src/app/features/settings/user-management/user.service.ts +++ b/frontend/src/app/features/settings/user-management/user.service.ts @@ -13,7 +13,7 @@ import {DEFAULT_UI_FONT, normalizeUiFont, type UiFontPreference} from '../../../ export interface EntityViewPreferences { global: EntityViewPreference; - overrides: EntityViewPreferenceOverride[]; + overrides: EntityViewPreferenceOverride[] | null; } export interface SortCriterion { @@ -512,7 +512,7 @@ export class UserService { ); } - updateUserSetting(userId: number, key: string, value: unknown): void { + updateUserSetting(userId: number, key: string, value: unknown, onError?: () => void): void { const payload = { key, value @@ -520,13 +520,16 @@ export class UserService { this.http.put(`${this.userUrl}/${userId}/settings`, payload, { headers: { 'Content-Type': 'application/json' }, responseType: 'text' as 'json' - }).subscribe(() => { - const currentUser = this.currentUser(); - if (currentUser) { - const updatedSettings = { ...currentUser.userSettings, [key]: value }; - const updatedUser = { ...currentUser, userSettings: updatedSettings }; - this.queryClient.setQueryData(CURRENT_USER_QUERY_KEY, updatedUser); - } + }).subscribe({ + next: () => { + const currentUser = this.currentUser(); + if (currentUser) { + const updatedSettings = { ...currentUser.userSettings, [key]: value }; + const updatedUser = { ...currentUser, userSettings: updatedSettings }; + this.queryClient.setQueryData(CURRENT_USER_QUERY_KEY, updatedUser); + } + }, + error: onError, }); } diff --git a/frontend/src/app/shared/layout/navigation/library-shelf-menu-target.model.ts b/frontend/src/app/shared/layout/navigation/library-shelf-menu-target.model.ts new file mode 100644 index 000000000..635d718cb --- /dev/null +++ b/frontend/src/app/shared/layout/navigation/library-shelf-menu-target.model.ts @@ -0,0 +1,7 @@ +export type LibraryShelfMenuTarget = + | {type: 'library'; entity: {id: number; name: string}} + | {type: 'shelf'; entity: {id: number; name: string; userId?: number; publicShelf?: boolean}} + | { + type: 'magicShelf'; + entity: {id: number; name: string; filterJson: string; isPublic?: boolean}; + }; diff --git a/frontend/src/app/shared/layout/navigation/nav-item.model.ts b/frontend/src/app/shared/layout/navigation/nav-item.model.ts index cffee8e96..32bd3ca4c 100644 --- a/frontend/src/app/shared/layout/navigation/nav-item.model.ts +++ b/frontend/src/app/shared/layout/navigation/nav-item.model.ts @@ -1,5 +1,5 @@ import { IconType } from '../../icons/icon-selection'; -import type {LibraryShelfMenuTarget} from '../../../features/book/components/library-shelf-menu/library-shelf-menu.component'; +import type {LibraryShelfMenuTarget} from './library-shelf-menu-target.model'; export type NavItemType = | 'library' | 'shelf' | 'magicShelf' diff --git a/frontend/src/app/shared/services/dialog-launcher.service.ts b/frontend/src/app/shared/services/dialog-launcher.service.ts index 03c1d3b62..dccf3da7f 100644 --- a/frontend/src/app/shared/services/dialog-launcher.service.ts +++ b/frontend/src/app/shared/services/dialog-launcher.service.ts @@ -4,6 +4,7 @@ import {TranslocoService} from '@jsverse/transloco'; import {MessageService} from '@openng/optimus-ui/api'; import {MetadataRefreshType} from '../../features/metadata/model/request/metadata-refresh-type.enum'; import {BookdropFinalizeResult} from '../../features/bookdrop/service/bookdrop.service'; +import type {BookBrowseMultiSortDialogData} from '../../features/book/browse/book-browse-multi-sort-dialog.component'; /** * Dialog size classes - use these to control dialog dimensions @@ -234,6 +235,17 @@ export class DialogLauncherService { }); } + async openMultiSortDialog(data: BookBrowseMultiSortDialogData): Promise { + return this.launchLazyDialog(async () => { + const {BookBrowseMultiSortDialogComponent} = await import('../../features/book/browse/book-browse-multi-sort-dialog.component'); + return this.openDialog(BookBrowseMultiSortDialogComponent, { + showHeader: false, + styleClass: `${DialogSize.SM} ${DialogStyle.MINIMAL}`, + data, + }); + }); + } + async openIconPickerDialog(): Promise { return this.launchLazyDialog(async () => { const {IconPickerComponent} = await import('../components/icon-picker/icon-picker-component'); diff --git a/frontend/src/app/shared/util/held-signal.ts b/frontend/src/app/shared/util/held-signal.ts new file mode 100644 index 000000000..e0345bff9 --- /dev/null +++ b/frontend/src/app/shared/util/held-signal.ts @@ -0,0 +1,8 @@ +import {linkedSignal, type Signal} from '@angular/core'; + +export function heldSignal(value: () => S, hold: () => boolean): Signal { + return linkedSignal<{stale: boolean; value: S}, S>({ + source: () => ({stale: hold(), value: value()}), + computation: (source, previous) => (source.stale && previous ? previous.value : source.value), + }); +} diff --git a/frontend/src/assets/styles/overlays.scss b/frontend/src/assets/styles/overlays.scss index 8b7030d00..efc2d12ee 100644 --- a/frontend/src/assets/styles/overlays.scss +++ b/frontend/src/assets/styles/overlays.scss @@ -7,6 +7,10 @@ * shared overlay classes that are not Optimus UI-specific live here. */ +.cdk-overlay-container { + z-index: 1300; +} + .command-palette-backdrop { background: rgb(0 0 0 / 56%); } diff --git a/frontend/src/i18n/cs.json b/frontend/src/i18n/cs.json index 2ac1900c2..d46090234 100644 --- a/frontend/src/i18n/cs.json +++ b/frontend/src/i18n/cs.json @@ -3663,6 +3663,50 @@ "mergeFailedDetail": "", "mergePartialDetail": "" } + }, + "fields": { + "title": "Title", + "author": "Author", + "genre": "Genre", + "series": "Series", + "seriesNumber": "Series number", + "publisher": "Publisher", + "tag": "Tag", + "mood": "Mood", + "language": "Language", + "narrator": "Narrator", + "fileType": "File format", + "readStatus": "Read status", + "personalRating": "Personal rating", + "amazonRating": "Amazon rating", + "amazonReviewCount": "Amazon reviews", + "goodreadsRating": "Goodreads rating", + "goodreadsReviewCount": "Goodreads reviews", + "hardcoverRating": "Hardcover rating", + "hardcoverReviewCount": "Hardcover reviews", + "ranobedbRating": "RanobeDB rating", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Pages", + "publishedDate": "Published date", + "publishedYear": "Published year", + "addedOn": "Date added", + "lastReadTime": "Last read", + "dateFinished": "Date finished", + "readingProgress": "Reading progress", + "fileName": "File name", + "fileSize": "File size", + "isbn": "ISBN", + "library": "Library", + "shelf": "Shelf", + "ageRating": "Age rating", + "contentRating": "Content rating", + "matchScore": "Metadata match score", + "shelfStatus": "Shelf status", + "comicCharacter": "Comic character", + "comicTeam": "Comic team", + "comicLocation": "Comic location", + "comicCreator": "Comic creator" } }, "readerAudiobook": { diff --git a/frontend/src/i18n/da.json b/frontend/src/i18n/da.json index ec923adf2..cefbea123 100644 --- a/frontend/src/i18n/da.json +++ b/frontend/src/i18n/da.json @@ -3663,6 +3663,50 @@ "mergeFailedDetail": "", "mergePartialDetail": "" } + }, + "fields": { + "title": "Title", + "author": "Author", + "genre": "Genre", + "series": "Series", + "seriesNumber": "Series number", + "publisher": "Publisher", + "tag": "Tag", + "mood": "Mood", + "language": "Language", + "narrator": "Narrator", + "fileType": "File format", + "readStatus": "Read status", + "personalRating": "Personal rating", + "amazonRating": "Amazon rating", + "amazonReviewCount": "Amazon reviews", + "goodreadsRating": "Goodreads rating", + "goodreadsReviewCount": "Goodreads reviews", + "hardcoverRating": "Hardcover rating", + "hardcoverReviewCount": "Hardcover reviews", + "ranobedbRating": "RanobeDB rating", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Pages", + "publishedDate": "Published date", + "publishedYear": "Published year", + "addedOn": "Date added", + "lastReadTime": "Last read", + "dateFinished": "Date finished", + "readingProgress": "Reading progress", + "fileName": "File name", + "fileSize": "File size", + "isbn": "ISBN", + "library": "Library", + "shelf": "Shelf", + "ageRating": "Age rating", + "contentRating": "Content rating", + "matchScore": "Metadata match score", + "shelfStatus": "Shelf status", + "comicCharacter": "Comic character", + "comicTeam": "Comic team", + "comicLocation": "Comic location", + "comicCreator": "Comic creator" } }, "readerAudiobook": { diff --git a/frontend/src/i18n/de.json b/frontend/src/i18n/de.json index ca80c1ced..624e3eba3 100644 --- a/frontend/src/i18n/de.json +++ b/frontend/src/i18n/de.json @@ -3070,7 +3070,8 @@ "customFetchMetadata": "Metadaten benutzerdefiniert abrufen", "autoFetchMetadata": "Metadaten automatisch abrufen", "findDuplicates": "Duplikate finden", - "deleteLibrary": "Bibliothek löschen" + "deleteLibrary": "Bibliothek löschen", + "manageLibrary": "Bibliothek verwalten" }, "shelf": { "publicShelfPrefix": "Öffentliches Regal - ", @@ -3709,6 +3710,57 @@ "mergeFailedDetail": "Diese Gruppe konnte nicht zusammengeführt werden.", "mergePartialDetail": "{{ success }} zusammengeführt, {{ failed }} fehlgeschlagen." } + }, + "fields": { + "random": "Zufällig", + "title": "Titel", + "author": "Autor", + "authorSurname": "Autor (Nachname)", + "genre": "Genre", + "series": "Serie", + "seriesNumber": "Seriennummer", + "publisher": "Verlag", + "tag": "Schlagwort", + "mood": "Stimmung", + "language": "Sprache", + "narrator": "Sprecher", + "fileType": "Buchtyp", + "readStatus": "Lesestatus", + "personalRating": "Persönliche Bewertung", + "amazonRating": "Amazon-Bewertung", + "amazonReviewCount": "Amazon Nr.", + "goodreadsRating": "Goodreads-Bewertung", + "goodreadsReviewCount": "Goodreads Nr.", + "hardcoverRating": "Hardcover-Bewertung", + "hardcoverReviewCount": "Hardcover Nr.", + "ranobedbRating": "Ranobedb-Bewertung", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Seiten", + "publishedDate": "Veröffentlichungsdatum", + "publishedYear": "Erscheinungsjahr", + "addedOn": "Hinzugefügt am", + "lastReadTime": "Zuletzt gelesen", + "dateFinished": "Beendet am", + "readingProgress": "Lesefortschritt", + "fileName": "Dateiname", + "fileSize": "Dateigröße", + "isbn": "ISBN", + "library": "Bibliothek", + "shelf": "Regal", + "ageRating": "Altersfreigabe", + "contentRating": "Inhaltsbewertung", + "matchScore": "Metadaten-Übereinstimmung", + "shelfStatus": "Regalstatus", + "comicCharacter": "Comic-Charakter", + "comicTeam": "Comic-Team", + "comicLocation": "Comic-Ort", + "comicCreator": "Comic-Zeichner", + "audibleReviewCount": "Audible-Rezensionen" + }, + "viewMode": { + "grid": "Raster", + "table": "Tabelle" } }, "readerAudiobook": { @@ -5378,6 +5430,23 @@ }, "browse": { "showAll": "Alle einblenden", - "moreActions": "Weitere Aktionen" + "moreActions": "Weitere Aktionen", + "toolbar": { + "columnGroups": { + "file": "Datei", + "ratings": "Bewertungen" + }, + "viewMode": "Ansicht", + "density": "Größe", + "resetColumns": "Auf Standard zurücksetzen" + }, + "bulk": { + "organizeFiles": "Dateien organisieren", + "updateReadStatus": "Lesestatus aktualisieren", + "lockUnlockMetadata": "Metadaten sperren/entsperren" + }, + "sort": { + "apply": "Anwenden" + } } } diff --git a/frontend/src/i18n/en.json b/frontend/src/i18n/en.json index aaa1860d6..ad99b42b7 100644 --- a/frontend/src/i18n/en.json +++ b/frontend/src/i18n/en.json @@ -2989,6 +2989,10 @@ } }, "selectBook": "Select {{ title }}", + "viewMode": { + "grid": "Grid", + "table": "Table" + }, "notes": { "confirm": { "deleteMessage": "Are you sure you want to delete the note \"{{ title }}\"?", @@ -3116,7 +3120,8 @@ "customFetchMetadata": "Custom Fetch Metadata", "autoFetchMetadata": "Auto Fetch Metadata", "findDuplicates": "Find Duplicates", - "deleteLibrary": "Delete Library" + "deleteLibrary": "Delete Library", + "manageLibrary": "Manage Library" }, "shelf": { "publicShelfPrefix": "Public Shelf - ", @@ -3561,7 +3566,7 @@ "sortOrder": "Sort Order", "removeTooltip": "Remove", "addSortFieldPlaceholder": "Add sort field...", - "saveAsDefault": "Save as Default", + "saveAsDefault": "Save as Default for {{scope}}", "ascendingTooltip": "Ascending - click to change", "descendingTooltip": "Descending - click to change", "options": { @@ -3620,7 +3625,7 @@ }, "searcher": { "placeholder": "Title, Author, Series, Genre, or ISBN...", - "clearSearch": "Clear Search", + "clearSearch": "Clear search", "bookCoverAlt": "Book Cover", "byPrefix": "by", "noResults": "No results found", @@ -5475,13 +5480,29 @@ "showAll": "Show All", "showFewer": "Show Fewer", "clearFilters": "Clear Filters", + "filter": "Filter", "moreActions": "More Actions", + "sort": { + "multiSort": "Multi-Sort", + "addField": "Add Field", + "apply": "Apply", + "moveUp": "Move Up", + "moveDown": "Move Down", + "flipDirection": "Flip Direction" + }, "chips": { "removeSearch": "Remove Search Filter {{query}}" }, "rail": { "searchValues": "Search…", - "search": "Search {{scope}}", + "searchFields": "Title, author, genre…", + "searchScope": { + "allBooks": "Search All Books", + "library": "Search Library", + "shelf": "Search Shelf", + "magicShelf": "Search Magic Shelf", + "unshelved": "Search Unshelved Books" + }, "noMatches": "No matches", "minUnit": "Min unit", "maxUnit": "Max unit", @@ -5496,6 +5517,40 @@ }, "table": { "moreValues": "Show {{count}} more {{column}}" + }, + "toolbar": { + "columnGroups": { + "reading": "Reading", + "publishing": "Publishing", + "file": "File", + "categorization": "Categorization", + "ratings": "Ratings" + }, + "sort": "Sort", + "sortAria": "Sort by {{field}}", + "sortAscending": "Sort Ascending", + "sortDescending": "Sort Descending", + "shuffleAgain": "Shuffle Again", + "viewMode": "View", + "density": "Size", + "smallerCards": "Smaller Cards", + "largerCards": "Larger Cards", + "showFilters": "Show Filters", + "columns": "Columns", + "resetColumns": "Reset to Default" + }, + "bulk": { + "markAsMessage": "Mark {{count}} books as {{status}}?", + "editAll": "Edit All", + "editOneByOne": "Edit One by One", + "selectionEmpty": "That selection no longer matches any books.", + "selectionLoadError": "Couldn't load the selection. Please try again.", + "organizeFiles": "Organize Files", + "updateReadStatus": "Update Read Status", + "lockUnlockMetadata": "Lock/Unlock Metadata" + }, + "filterPage": { + "show": "Show {{count}} Books" } } } diff --git a/frontend/src/i18n/es.json b/frontend/src/i18n/es.json index 2d996c712..ab8167d9a 100644 --- a/frontend/src/i18n/es.json +++ b/frontend/src/i18n/es.json @@ -2944,6 +2944,10 @@ } }, "selectBook": "Seleccionar {{ title }}", + "viewMode": { + "grid": "Cuadrícula", + "table": "Tabla" + }, "notes": { "confirm": { "deleteMessage": "¿Estás seguro de que deseas eliminar la nota \"{{ title }}\"?", @@ -3071,7 +3075,8 @@ "customFetchMetadata": "Obtención personalizada de metadatos", "autoFetchMetadata": "Obtener metadatos automáticamente", "findDuplicates": "Buscar duplicados", - "deleteLibrary": "Eliminar biblioteca" + "deleteLibrary": "Eliminar biblioteca", + "manageLibrary": "Gestionar biblioteca" }, "shelf": { "publicShelfPrefix": "Estante público - ", @@ -3710,6 +3715,53 @@ "mergeFailedDetail": "No se pudo fusionar este grupo.", "mergePartialDetail": "{{ success }} fusionados, {{ failed }} fallidos." } + }, + "fields": { + "random": "Aleatorio", + "title": "Título", + "author": "Autor", + "authorSurname": "Autor (Apellido)", + "genre": "Género", + "series": "Serie", + "seriesNumber": "Número de serie", + "publisher": "Editorial", + "tag": "Etiqueta", + "mood": "Estado de ánimo", + "language": "Idioma", + "narrator": "Narrador", + "fileType": "Formato de archivo", + "readStatus": "Estado de lectura", + "personalRating": "Calificación personal", + "amazonRating": "Calificación Amazon", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Calificación Goodreads", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Calificación Hardcover", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Calificación RanobeDB", + "lubimyczytacRating": "Calificación Lubimyczytac", + "audibleRating": "Calificación Audible", + "pageCount": "Páginas", + "publishedDate": "Fecha de publicación", + "publishedYear": "Año de publicación", + "addedOn": "Fecha de añadido", + "lastReadTime": "Última lectura", + "dateFinished": "Fecha de finalización", + "readingProgress": "Progreso de lectura", + "fileName": "Nombre de archivo", + "fileSize": "Tamaño de archivo", + "isbn": "ISBN", + "library": "Biblioteca", + "shelf": "Estante", + "ageRating": "Clasificación por edad", + "contentRating": "Clasificación de contenido", + "matchScore": "Puntuación de coincidencia de metadatos", + "shelfStatus": "Estado del estante", + "comicCharacter": "Personaje de cómic", + "comicTeam": "Equipo de cómic", + "comicLocation": "Ubicación de cómic", + "comicCreator": "Creador de cómic", + "audibleReviewCount": "Cantidad de Reseñas de Audible" } }, "readerAudiobook": { @@ -5380,8 +5432,25 @@ "browse": { "showAll": "Mostrar todos", "moreActions": "Más acciones", + "sort": { + "apply": "Aplicar" + }, "rail": { "noMatches": "Sin coincidencias" + }, + "toolbar": { + "columnGroups": { + "file": "Archivo", + "ratings": "Calificaciones" + }, + "viewMode": "Vista", + "density": "Tamaño", + "resetColumns": "Restablecer valores" + }, + "bulk": { + "organizeFiles": "Organizar archivos", + "updateReadStatus": "Actualizar estado de lectura", + "lockUnlockMetadata": "Bloquear/Desbloquear metadatos" } } } diff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.json index 85969c634..711433d06 100644 --- a/frontend/src/i18n/fr.json +++ b/frontend/src/i18n/fr.json @@ -3071,7 +3071,8 @@ "customFetchMetadata": "Récupération personnalisée des métadonnées", "autoFetchMetadata": "Récupération automatique des métadonnées", "findDuplicates": "Rechercher les doublons", - "deleteLibrary": "Supprimer la bibliothèque" + "deleteLibrary": "Supprimer la bibliothèque", + "manageLibrary": "Gérer la bibliothèque" }, "shelf": { "publicShelfPrefix": "Étagère publique - ", @@ -3710,6 +3711,57 @@ "mergeFailedDetail": "Impossible de fusionner ce groupe.", "mergePartialDetail": "{{ success }} fusionné(s), {{ failed }} échoué(s)." } + }, + "viewMode": { + "grid": "Grille", + "table": "Tableau" + }, + "fields": { + "random": "Aléatoire", + "title": "Titre", + "author": "Auteur", + "authorSurname": "Auteur (nom de famille)", + "genre": "Genre", + "series": "Série", + "seriesNumber": "Numéro de la série", + "publisher": "Éditeur", + "tag": "Tag", + "mood": "Humeur", + "language": "Langue", + "narrator": "Narrateur", + "fileType": "Type de livre", + "readStatus": "Statut de lecture", + "personalRating": "Note personnelle", + "amazonRating": "Note Amazon", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Note Goodreads", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Note Hardcover", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Note RanobeDB", + "lubimyczytacRating": "Note Lubimyczytac", + "audibleRating": "Note Audible", + "pageCount": "Pages", + "publishedDate": "Date de publication", + "publishedYear": "Année de publication", + "addedOn": "Date d'ajout", + "lastReadTime": "Dernière lecture", + "dateFinished": "Date de fin", + "readingProgress": "Progression de lecture", + "fileName": "Nom du fichier", + "fileSize": "Taille du fichier", + "isbn": "ISBN", + "library": "Bibliothèque", + "shelf": "Étagère", + "ageRating": "Classification d'âge", + "contentRating": "Classification de contenu", + "matchScore": "Score de correspondance des métadonnées", + "shelfStatus": "Statut d'étagère", + "comicCharacter": "Personnage de BD", + "comicTeam": "Équipe de BD", + "comicLocation": "Lieu de BD", + "comicCreator": "Créateur de BD", + "audibleReviewCount": "Nombre d'avis Audible" } }, "readerAudiobook": { @@ -5382,6 +5434,20 @@ "moreActions": "Plus d'actions", "rail": { "noMatches": "Aucun résultat" + }, + "bulk": { + "organizeFiles": "Organiser les fichiers", + "updateReadStatus": "Mettre à jour le statut de lecture", + "lockUnlockMetadata": "Verrouiller/Déverrouiller les métadonnées" + }, + "toolbar": { + "columnGroups": { + "file": "Fichier", + "ratings": "Notes" + }, + "viewMode": "Affichage", + "density": "Taille", + "resetColumns": "Réinitialiser par défaut" } } } diff --git a/frontend/src/i18n/hr.json b/frontend/src/i18n/hr.json index c93c3b59e..82a0ccf74 100644 --- a/frontend/src/i18n/hr.json +++ b/frontend/src/i18n/hr.json @@ -3071,7 +3071,8 @@ "customFetchMetadata": "Prilagođeni dohvat metapodataka", "autoFetchMetadata": "Automatski dohvat metapodataka", "findDuplicates": "Pronađi duplikate", - "deleteLibrary": "Obriši knjižnicu" + "deleteLibrary": "Obriši knjižnicu", + "manageLibrary": "Upravljanje zbirkom" }, "shelf": { "publicShelfPrefix": "Javna polica - ", @@ -3710,6 +3711,57 @@ "mergeFailedDetail": "Spajanje ove grupe nije uspjelo.", "mergePartialDetail": "{{ success }} spojeno, {{ failed }} neuspjelo." } + }, + "fields": { + "random": "Nasumično", + "title": "Naslov", + "author": "Autor", + "authorSurname": "Autor (prezime)", + "genre": "Žanr", + "series": "Serijal", + "seriesNumber": "Broj u serijalu", + "publisher": "Izdavač", + "tag": "Oznaka", + "mood": "Raspoloženje", + "language": "Jezik", + "narrator": "Narator", + "fileType": "Vrsta knjige", + "readStatus": "Status čitanja", + "personalRating": "Osobna ocjena", + "amazonRating": "Amazon ocjena", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Goodreads ocjena", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Hardcover ocjena", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "RanobeDB ocjena", + "lubimyczytacRating": "Lubimyczytac ocjena", + "audibleRating": "Audible ocjena", + "pageCount": "Stranice", + "publishedDate": "Datum izdavanja", + "publishedYear": "Godina izdavanja", + "addedOn": "Dodano", + "lastReadTime": "Zadnje čitano", + "dateFinished": "Datum završetka", + "readingProgress": "Napredak čitanja", + "fileName": "Naziv datoteke", + "fileSize": "Veličina datoteke", + "isbn": "ISBN", + "library": "Zbirka", + "shelf": "Polica", + "ageRating": "Dobna ocjena", + "contentRating": "Ocjena sadržaja", + "matchScore": "Rezultat usklađenosti metapodataka", + "shelfStatus": "Status police", + "comicCharacter": "Lik iz stripa", + "comicTeam": "Tim iz stripa", + "comicLocation": "Lokacija iz stripa", + "comicCreator": "Autor stripa", + "audibleReviewCount": "Audible broj recenzija" + }, + "viewMode": { + "grid": "Mreža", + "table": "Tablica" } }, "readerAudiobook": { @@ -5382,6 +5434,23 @@ "moreActions": "Više radnji", "rail": { "noMatches": "Nema podudaranja" + }, + "sort": { + "apply": "Primijeni" + }, + "bulk": { + "organizeFiles": "Organiziraj datoteke", + "updateReadStatus": "Ažuriraj status čitanja", + "lockUnlockMetadata": "Zaključaj/Otključaj metapodatke" + }, + "toolbar": { + "columnGroups": { + "file": "Datoteka", + "ratings": "Ocjene" + }, + "viewMode": "Prikaz", + "density": "Veličina", + "resetColumns": "Vrati na zadano" } } } diff --git a/frontend/src/i18n/hu.json b/frontend/src/i18n/hu.json index 980e613e1..07d5ab3dd 100644 --- a/frontend/src/i18n/hu.json +++ b/frontend/src/i18n/hu.json @@ -3692,6 +3692,50 @@ "largeFileHeader": "Figyelmeztetés: nagyméretű fájl", "sendAnyway": "Elküldés mindenképp" } + }, + "fields": { + "title": "Title", + "author": "Author", + "genre": "Genre", + "series": "Series", + "seriesNumber": "Series number", + "publisher": "Publisher", + "tag": "Tag", + "mood": "Mood", + "language": "Language", + "narrator": "Narrator", + "fileType": "File format", + "readStatus": "Read status", + "personalRating": "Personal rating", + "amazonRating": "Amazon rating", + "amazonReviewCount": "Amazon reviews", + "goodreadsRating": "Goodreads rating", + "goodreadsReviewCount": "Goodreads reviews", + "hardcoverRating": "Hardcover rating", + "hardcoverReviewCount": "Hardcover reviews", + "ranobedbRating": "RanobeDB rating", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Pages", + "publishedDate": "Published date", + "publishedYear": "Published year", + "addedOn": "Hozzáadás Dátuma", + "lastReadTime": "Last read", + "dateFinished": "Date finished", + "readingProgress": "Reading progress", + "fileName": "File name", + "fileSize": "File size", + "isbn": "ISBN", + "library": "Library", + "shelf": "Shelf", + "ageRating": "Age rating", + "contentRating": "Content rating", + "matchScore": "Metadata match score", + "shelfStatus": "Shelf status", + "comicCharacter": "Comic character", + "comicTeam": "Comic team", + "comicLocation": "Comic location", + "comicCreator": "Comic creator" } }, "readerAudiobook": { @@ -5360,6 +5404,14 @@ } }, "browse": { - "moreActions": "További lehetőségek" + "moreActions": "További lehetőségek", + "toolbar": { + "viewMode": "Nézet", + "resetColumns": "Visszaállítás Alapértelmezettre" + }, + "bulk": { + "organizeFiles": "Fájlok rendszerezése", + "lockUnlockMetadata": "Metaadatok zárolása / feloldása" + } } } diff --git a/frontend/src/i18n/id.json b/frontend/src/i18n/id.json index cb9f2b6ef..e563d630d 100644 --- a/frontend/src/i18n/id.json +++ b/frontend/src/i18n/id.json @@ -3679,6 +3679,53 @@ "continueListening": { "short": "Lanjutkan" } + }, + "viewMode": { + "table": "Tabel" + }, + "fields": { + "title": "Title", + "author": "Author", + "genre": "Genre", + "series": "Series", + "seriesNumber": "Series number", + "publisher": "Publisher", + "tag": "Tag", + "mood": "Mood", + "language": "Language", + "narrator": "Narrator", + "fileType": "File format", + "readStatus": "Read status", + "personalRating": "Personal rating", + "amazonRating": "Amazon rating", + "amazonReviewCount": "Amazon reviews", + "goodreadsRating": "Goodreads rating", + "goodreadsReviewCount": "Goodreads reviews", + "hardcoverRating": "Hardcover rating", + "hardcoverReviewCount": "Hardcover reviews", + "ranobedbRating": "RanobeDB rating", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Pages", + "publishedDate": "Published date", + "publishedYear": "Published year", + "addedOn": "Date added", + "lastReadTime": "Last read", + "dateFinished": "Date finished", + "readingProgress": "Reading progress", + "fileName": "File name", + "fileSize": "File size", + "isbn": "ISBN", + "library": "Library", + "shelf": "Shelf", + "ageRating": "Age rating", + "contentRating": "Content rating", + "matchScore": "Metadata match score", + "shelfStatus": "Shelf status", + "comicCharacter": "Comic character", + "comicTeam": "Comic team", + "comicLocation": "Comic location", + "comicCreator": "Comic creator" } }, "readerAudiobook": { @@ -5345,5 +5392,20 @@ "matchFailedDetail": "" } } + }, + "browse": { + "moreActions": "Tindakan lain", + "toolbar": { + "columnGroups": { + "file": "Berkas", + "ratings": "Rating" + }, + "viewMode": "Tampilan", + "density": "Ukuran" + }, + "bulk": { + "organizeFiles": "Atur Berkas", + "lockUnlockMetadata": "Kunci/Buka kunci metadata" + } } } diff --git a/frontend/src/i18n/it.json b/frontend/src/i18n/it.json index 032554282..43a14c9af 100644 --- a/frontend/src/i18n/it.json +++ b/frontend/src/i18n/it.json @@ -3067,7 +3067,8 @@ "customFetchMetadata": "Recupero personalizzato metadati", "autoFetchMetadata": "Recupero automatico metadati", "findDuplicates": "Trova duplicati", - "deleteLibrary": "Elimina libreria" + "deleteLibrary": "Elimina libreria", + "manageLibrary": "Gestire libreria" }, "shelf": { "publicShelfPrefix": "Scaffale pubblico - ", @@ -3706,6 +3707,57 @@ "mergeFailedDetail": "Impossibile unire questo gruppo.", "mergePartialDetail": "{{ success }} uniti, {{ failed }} falliti." } + }, + "viewMode": { + "grid": "Griglia", + "table": "Tabella" + }, + "fields": { + "random": "Casuale", + "title": "Titolo", + "author": "Autore", + "authorSurname": "Autore (Cognome)", + "genre": "Genere", + "series": "Serie", + "seriesNumber": "Numero serie", + "publisher": "Editore", + "tag": "Tag", + "mood": "Mood", + "language": "Lingua", + "narrator": "Narratore", + "fileType": "Tipo libro", + "readStatus": "Stato lettura", + "personalRating": "Valutazione personale", + "amazonRating": "Valutazione Amazon", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Valutazione Goodreads", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Valutazione Hardcover", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Valutazione Ranobedb", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Pagine", + "publishedDate": "Data pubblicazione", + "publishedYear": "Anno pubblicazione", + "addedOn": "Data aggiunta", + "lastReadTime": "Ultima lettura", + "dateFinished": "Data completamento", + "readingProgress": "Progresso lettura", + "fileName": "Nome file", + "fileSize": "Dimensione file", + "isbn": "ISBN", + "library": "Libreria", + "shelf": "Scaffale", + "ageRating": "Classificazione età", + "contentRating": "Classificazione contenuto", + "matchScore": "Punteggio corrispondenza metadati", + "shelfStatus": "Stato scaffale", + "comicCharacter": "Personaggio fumetto", + "comicTeam": "Squadra fumetto", + "comicLocation": "Luogo fumetto", + "comicCreator": "Creatore fumetto", + "audibleReviewCount": "Numero recensioni Audible" } }, "readerAudiobook": { @@ -5375,6 +5427,19 @@ }, "browse": { "showAll": "Mostra tutti", - "moreActions": "Altre azioni" + "moreActions": "Altre azioni", + "toolbar": { + "columnGroups": { + "ratings": "Valutazioni" + }, + "viewMode": "Visualizzazione", + "density": "Dimensione", + "resetColumns": "Ripristina predefiniti" + }, + "bulk": { + "organizeFiles": "Organizza file", + "updateReadStatus": "Aggiorna stato lettura", + "lockUnlockMetadata": "Blocca/Sblocca metadati" + } } } diff --git a/frontend/src/i18n/ja.json b/frontend/src/i18n/ja.json index 1238e5949..ef7f61f9f 100644 --- a/frontend/src/i18n/ja.json +++ b/frontend/src/i18n/ja.json @@ -3068,7 +3068,8 @@ "customFetchMetadata": "メタデータをカスタム取得", "autoFetchMetadata": "メタデータを自動取得", "findDuplicates": "重複を検索", - "deleteLibrary": "ライブラリを削除" + "deleteLibrary": "ライブラリを削除", + "manageLibrary": "ライブラリを管理" }, "shelf": { "publicShelfPrefix": "公開シェルフ - ", @@ -3707,6 +3708,57 @@ "mergeFailedDetail": "このグループのマージができませんでした。", "mergePartialDetail": "{{ success }}件マージ成功、{{ failed }}件失敗。" } + }, + "fields": { + "random": "ランダム", + "title": "タイトル", + "author": "著者", + "authorSurname": "著者(姓)", + "genre": "ジャンル", + "series": "シリーズ", + "seriesNumber": "シリーズ番号", + "publisher": "出版社", + "tag": "タグ", + "mood": "ムード", + "language": "言語", + "narrator": "ナレーター", + "fileType": "本の種類", + "readStatus": "読書状態", + "personalRating": "個人評価", + "amazonRating": "Amazon評価", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Goodreads評価", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Hardcover評価", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Ranobedb評価", + "lubimyczytacRating": "Lubimyczytac評価", + "audibleRating": "Audible評価", + "pageCount": "ページ数", + "publishedDate": "出版日", + "publishedYear": "出版年", + "addedOn": "追加日", + "lastReadTime": "最終閲覧", + "dateFinished": "完了日", + "readingProgress": "読書進捗", + "fileName": "ファイル名", + "fileSize": "ファイルサイズ", + "isbn": "ISBN", + "library": "ライブラリ", + "shelf": "シェルフ", + "ageRating": "年齢制限", + "contentRating": "コンテンツレーティング", + "matchScore": "メタデータマッチスコア", + "shelfStatus": "シェルフ状態", + "comicCharacter": "コミックキャラクター", + "comicTeam": "コミックチーム", + "comicLocation": "コミックロケーション", + "comicCreator": "コミッククリエイター", + "audibleReviewCount": "Audibleレビュー数" + }, + "viewMode": { + "grid": "グリッド", + "table": "テーブル" } }, "readerAudiobook": { @@ -5376,6 +5428,20 @@ }, "browse": { "showAll": "すべて表示", - "moreActions": "その他の操作" + "moreActions": "その他の操作", + "bulk": { + "organizeFiles": "ファイルを整理", + "updateReadStatus": "読書状態を更新", + "lockUnlockMetadata": "メタデータのロック/解除" + }, + "toolbar": { + "columnGroups": { + "file": "ファイル", + "ratings": "評価" + }, + "viewMode": "表示", + "density": "サイズ", + "resetColumns": "デフォルトに戻す" + } } } diff --git a/frontend/src/i18n/ko.json b/frontend/src/i18n/ko.json index 2ac1900c2..d46090234 100644 --- a/frontend/src/i18n/ko.json +++ b/frontend/src/i18n/ko.json @@ -3663,6 +3663,50 @@ "mergeFailedDetail": "", "mergePartialDetail": "" } + }, + "fields": { + "title": "Title", + "author": "Author", + "genre": "Genre", + "series": "Series", + "seriesNumber": "Series number", + "publisher": "Publisher", + "tag": "Tag", + "mood": "Mood", + "language": "Language", + "narrator": "Narrator", + "fileType": "File format", + "readStatus": "Read status", + "personalRating": "Personal rating", + "amazonRating": "Amazon rating", + "amazonReviewCount": "Amazon reviews", + "goodreadsRating": "Goodreads rating", + "goodreadsReviewCount": "Goodreads reviews", + "hardcoverRating": "Hardcover rating", + "hardcoverReviewCount": "Hardcover reviews", + "ranobedbRating": "RanobeDB rating", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Pages", + "publishedDate": "Published date", + "publishedYear": "Published year", + "addedOn": "Date added", + "lastReadTime": "Last read", + "dateFinished": "Date finished", + "readingProgress": "Reading progress", + "fileName": "File name", + "fileSize": "File size", + "isbn": "ISBN", + "library": "Library", + "shelf": "Shelf", + "ageRating": "Age rating", + "contentRating": "Content rating", + "matchScore": "Metadata match score", + "shelfStatus": "Shelf status", + "comicCharacter": "Comic character", + "comicTeam": "Comic team", + "comicLocation": "Comic location", + "comicCreator": "Comic creator" } }, "readerAudiobook": { diff --git a/frontend/src/i18n/nl.json b/frontend/src/i18n/nl.json index a36e574a2..bf5a3b3ce 100644 --- a/frontend/src/i18n/nl.json +++ b/frontend/src/i18n/nl.json @@ -3053,7 +3053,8 @@ "customFetchMetadata": "", "autoFetchMetadata": "", "findDuplicates": "", - "deleteLibrary": "" + "deleteLibrary": "", + "manageLibrary": "Bibliotheek beheren" }, "shelf": { "publicShelfPrefix": "", @@ -3692,6 +3693,50 @@ "mergeFailedDetail": "", "mergePartialDetail": "" } + }, + "fields": { + "title": "Titel", + "author": "Author", + "genre": "Genre", + "series": "Series", + "seriesNumber": "Series number", + "publisher": "Uitgever", + "tag": "Tag", + "mood": "Mood", + "language": "Taal", + "narrator": "Narrator", + "fileType": "File format", + "readStatus": "Read status", + "personalRating": "Personal rating", + "amazonRating": "Amazon rating", + "amazonReviewCount": "Amazon reviews", + "goodreadsRating": "Goodreads rating", + "goodreadsReviewCount": "Goodreads reviews", + "hardcoverRating": "Hardcover rating", + "hardcoverReviewCount": "Hardcover reviews", + "ranobedbRating": "RanobeDB rating", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Pagina's", + "publishedDate": "Published date", + "publishedYear": "Published year", + "addedOn": "Datum toegevoegd", + "lastReadTime": "Laatst gelezen", + "dateFinished": "Date finished", + "readingProgress": "Reading progress", + "fileName": "Bestandsnaam", + "fileSize": "Bestandsgrootte", + "isbn": "ISBN", + "library": "Library", + "shelf": "Shelf", + "ageRating": "Age rating", + "contentRating": "Content rating", + "matchScore": "Metadata match score", + "shelfStatus": "Shelf status", + "comicCharacter": "Comic character", + "comicTeam": "Comic team", + "comicLocation": "Comic location", + "comicCreator": "Comic creator" } }, "readerAudiobook": { @@ -5361,6 +5406,14 @@ }, "browse": { "showAll": "Alles weergeven", - "moreActions": "Meer acties" + "moreActions": "Meer acties", + "toolbar": { + "viewMode": "Weergave", + "resetColumns": "Naar standaard resetten" + }, + "bulk": { + "organizeFiles": "Bestanden ordenen", + "lockUnlockMetadata": "Metadata vergrendelen/ontgrendelen" + } } } diff --git a/frontend/src/i18n/pl.json b/frontend/src/i18n/pl.json index 8085263a6..9ff43685d 100644 --- a/frontend/src/i18n/pl.json +++ b/frontend/src/i18n/pl.json @@ -3067,7 +3067,8 @@ "customFetchMetadata": "Niestandardowe pobieranie metadanych", "autoFetchMetadata": "Automatyczne pobieranie metadanych", "findDuplicates": "Znajdź duplikaty", - "deleteLibrary": "Usuń bibliotekę" + "deleteLibrary": "Usuń bibliotekę", + "manageLibrary": "Zarządzanie biblioteką" }, "shelf": { "publicShelfPrefix": "Półka publiczna - ", @@ -3706,6 +3707,57 @@ "mergeFailedDetail": "Nie udało się scalić tej grupy.", "mergePartialDetail": "{{ success }} scalonych, {{ failed }} nieudanych." } + }, + "fields": { + "random": "Losowo", + "title": "Tytuł", + "author": "Autor", + "authorSurname": "Autor (Nazwisko)", + "genre": "Gatunek", + "series": "Seria", + "seriesNumber": "Numer serii", + "publisher": "Wydawca", + "tag": "Tag", + "mood": "Nastrój", + "language": "Język", + "narrator": "Narrator", + "fileType": "Typ książki", + "readStatus": "Status czytania", + "personalRating": "Ocena osobista", + "amazonRating": "Ocena Amazon", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Ocena Goodreads", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Ocena Hardcover", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Ocena Ranobedb", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Strony", + "publishedDate": "Data wydania", + "publishedYear": "Rok wydania", + "addedOn": "Data dodania", + "lastReadTime": "Ostatnio czytano", + "dateFinished": "Data ukończenia", + "readingProgress": "Postęp czytania", + "fileName": "Nazwa pliku", + "fileSize": "Rozmiar pliku", + "isbn": "ISBN", + "library": "Biblioteka", + "shelf": "Półka", + "ageRating": "Kategoria wiekowa", + "contentRating": "Ocena treści", + "matchScore": "Jakość metadanych", + "shelfStatus": "Status półki", + "comicCharacter": "Postać komiksowa", + "comicTeam": "Drużyna komiksowa", + "comicLocation": "Lokacja komiksowa", + "comicCreator": "Twórca komiksu", + "audibleReviewCount": "Liczba recenzji Audible" + }, + "viewMode": { + "grid": "Siatka", + "table": "Tabela" } }, "readerAudiobook": { @@ -5375,6 +5427,20 @@ }, "browse": { "showAll": "Pokaż wszystkie", - "moreActions": "Więcej akcji" + "moreActions": "Więcej akcji", + "bulk": { + "organizeFiles": "Organizuj pliki", + "updateReadStatus": "Zaktualizuj status czytania", + "lockUnlockMetadata": "Zablokuj/Odblokuj metadane" + }, + "toolbar": { + "columnGroups": { + "file": "Plik", + "ratings": "Oceny" + }, + "viewMode": "Widok", + "density": "Rozmiar", + "resetColumns": "Resetuj do domyślnych" + } } } diff --git a/frontend/src/i18n/pt.json b/frontend/src/i18n/pt.json index 4355f6c2a..d0d6b9a73 100644 --- a/frontend/src/i18n/pt.json +++ b/frontend/src/i18n/pt.json @@ -3067,7 +3067,8 @@ "customFetchMetadata": "Busca Personalizada de Metadados", "autoFetchMetadata": "Busca Automática de Metadados", "findDuplicates": "Encontrar Duplicatas", - "deleteLibrary": "Excluir Biblioteca" + "deleteLibrary": "Excluir Biblioteca", + "manageLibrary": "Gerenciar Biblioteca" }, "shelf": { "publicShelfPrefix": "Prateleira Pública - ", @@ -3706,6 +3707,57 @@ "mergeFailedDetail": "Não foi possível mesclar este grupo.", "mergePartialDetail": "{{ success }} mesclado(s), {{ failed }} falhou(aram)." } + }, + "fields": { + "random": "Aleatório", + "title": "Título", + "author": "Autor", + "authorSurname": "Autor (Sobrenome)", + "genre": "Gênero", + "series": "Série", + "seriesNumber": "Número da Série", + "publisher": "Editora", + "tag": "Tag", + "mood": "Humor", + "language": "Idioma", + "narrator": "Narrador", + "fileType": "Tipo de Livro", + "readStatus": "Status de Leitura", + "personalRating": "Avaliação Pessoal", + "amazonRating": "Avaliação Amazon", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Avaliação Goodreads", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Avaliação Hardcover", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Avaliação Ranobedb", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Páginas", + "publishedDate": "Data de Publicação", + "publishedYear": "Ano de Publicação", + "addedOn": "Adicionado Em", + "lastReadTime": "Última Leitura", + "dateFinished": "Data de Conclusão", + "readingProgress": "Progresso de Leitura", + "fileName": "Nome do Arquivo", + "fileSize": "Tamanho do Arquivo", + "isbn": "ISBN", + "library": "Biblioteca", + "shelf": "Prateleira", + "ageRating": "Classificação Etária", + "contentRating": "Classificação de Conteúdo", + "matchScore": "Pontuação de Correspondência de Metadados", + "shelfStatus": "Status da Prateleira", + "comicCharacter": "Personagem de Quadrinhos", + "comicTeam": "Equipe de Quadrinhos", + "comicLocation": "Local de Quadrinhos", + "comicCreator": "Criador de Quadrinhos", + "audibleReviewCount": "Contagem de Avaliações Audible" + }, + "viewMode": { + "grid": "Grade", + "table": "Tabela" } }, "readerAudiobook": { @@ -5375,6 +5427,20 @@ }, "browse": { "showAll": "Mostrar Todos", - "moreActions": "Mais ações" + "moreActions": "Mais ações", + "bulk": { + "organizeFiles": "Organizar Arquivos", + "updateReadStatus": "Atualizar Status de Leitura", + "lockUnlockMetadata": "Bloquear/Desbloquear metadados" + }, + "toolbar": { + "columnGroups": { + "file": "Arquivo", + "ratings": "Avaliações" + }, + "viewMode": "Visualização", + "density": "Tamanho", + "resetColumns": "Redefinir para Padrão" + } } } diff --git a/frontend/src/i18n/ru.json b/frontend/src/i18n/ru.json index 732a35057..bd5fde22a 100644 --- a/frontend/src/i18n/ru.json +++ b/frontend/src/i18n/ru.json @@ -3067,7 +3067,8 @@ "customFetchMetadata": "Настраиваемое получение метаданных", "autoFetchMetadata": "Автоматическое получение метаданных", "findDuplicates": "Найти дубликаты", - "deleteLibrary": "Удалить библиотеку" + "deleteLibrary": "Удалить библиотеку", + "manageLibrary": "Управление библиотекой" }, "shelf": { "publicShelfPrefix": "Публичная полка - ", @@ -3706,6 +3707,57 @@ "mergeFailedDetail": "Не удалось объединить эту группу.", "mergePartialDetail": "{{ success }} объединено, {{ failed }} с ошибкой." } + }, + "fields": { + "random": "Случайно", + "title": "Название", + "author": "Автор", + "authorSurname": "Автор (фамилия)", + "genre": "Жанр", + "series": "Серия", + "seriesNumber": "Номер в серии", + "publisher": "Издательство", + "tag": "Тег", + "mood": "Настроение", + "language": "Язык", + "narrator": "Чтец", + "fileType": "Тип книги", + "readStatus": "Статус чтения", + "personalRating": "Личная оценка", + "amazonRating": "Рейтинг Amazon", + "amazonReviewCount": "Amazon №", + "goodreadsRating": "Рейтинг Goodreads", + "goodreadsReviewCount": "Goodreads №", + "hardcoverRating": "Рейтинг Hardcover", + "hardcoverReviewCount": "Hardcover №", + "ranobedbRating": "Рейтинг Ranobedb", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Страницы", + "publishedDate": "Дата публикации", + "publishedYear": "Год публикации", + "addedOn": "Дата добавления", + "lastReadTime": "Последнее чтение", + "dateFinished": "Дата завершения", + "readingProgress": "Прогресс чтения", + "fileName": "Имя файла", + "fileSize": "Размер файла", + "isbn": "ISBN", + "library": "Библиотека", + "shelf": "Полка", + "ageRating": "Возрастной рейтинг", + "contentRating": "Рейтинг контента", + "matchScore": "Оценка соответствия метаданных", + "shelfStatus": "Статус полки", + "comicCharacter": "Персонаж комикса", + "comicTeam": "Команда комикса", + "comicLocation": "Место действия комикса", + "comicCreator": "Создатель комикса", + "audibleReviewCount": "Количество отзывов Audible" + }, + "viewMode": { + "grid": "Сетка", + "table": "Таблица" } }, "readerAudiobook": { @@ -5375,6 +5427,20 @@ }, "browse": { "showAll": "Показать все", - "moreActions": "Дополнительные действия" + "moreActions": "Дополнительные действия", + "bulk": { + "organizeFiles": "Организовать файлы", + "updateReadStatus": "Обновить статус чтения", + "lockUnlockMetadata": "Заблокировать/Разблокировать метаданные" + }, + "toolbar": { + "columnGroups": { + "file": "Файл", + "ratings": "Рейтинги" + }, + "viewMode": "Вид", + "density": "Размер", + "resetColumns": "Сбросить по умолчанию" + } } } diff --git a/frontend/src/i18n/sk.json b/frontend/src/i18n/sk.json index e502f0d3f..4c852e0ea 100644 --- a/frontend/src/i18n/sk.json +++ b/frontend/src/i18n/sk.json @@ -3663,6 +3663,50 @@ "mergeFailedDetail": "", "mergePartialDetail": "" } + }, + "fields": { + "title": "Title", + "author": "Author", + "genre": "Genre", + "series": "Series", + "seriesNumber": "Series number", + "publisher": "Publisher", + "tag": "Tag", + "mood": "Mood", + "language": "Language", + "narrator": "Narrator", + "fileType": "File format", + "readStatus": "Read status", + "personalRating": "Personal rating", + "amazonRating": "Amazon rating", + "amazonReviewCount": "Amazon reviews", + "goodreadsRating": "Goodreads rating", + "goodreadsReviewCount": "Goodreads reviews", + "hardcoverRating": "Hardcover rating", + "hardcoverReviewCount": "Hardcover reviews", + "ranobedbRating": "RanobeDB rating", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Pages", + "publishedDate": "Published date", + "publishedYear": "Published year", + "addedOn": "Date added", + "lastReadTime": "Last read", + "dateFinished": "Date finished", + "readingProgress": "Reading progress", + "fileName": "File name", + "fileSize": "File size", + "isbn": "ISBN", + "library": "Library", + "shelf": "Shelf", + "ageRating": "Age rating", + "contentRating": "Content rating", + "matchScore": "Metadata match score", + "shelfStatus": "Shelf status", + "comicCharacter": "Comic character", + "comicTeam": "Comic team", + "comicLocation": "Comic location", + "comicCreator": "Comic creator" } }, "readerAudiobook": { @@ -5330,5 +5374,9 @@ } } }, - "browse": {} + "browse": { + "toolbar": { + "viewMode": "Pohľad" + } + } } diff --git a/frontend/src/i18n/sl.json b/frontend/src/i18n/sl.json index 35b4232fe..4bc65e25a 100644 --- a/frontend/src/i18n/sl.json +++ b/frontend/src/i18n/sl.json @@ -3070,7 +3070,8 @@ "customFetchMetadata": "Pridobi metapodatke po meri", "autoFetchMetadata": "Samodejno pridobi metapodatke", "findDuplicates": "Najdi dvojnike", - "deleteLibrary": "Izbriši knjižnico" + "deleteLibrary": "Izbriši knjižnico", + "manageLibrary": "Upravljanje knjižnice" }, "shelf": { "publicShelfPrefix": "Javna polica - ", @@ -3709,6 +3710,57 @@ "mergeFailedDetail": "Te skupine ni bilo mogoče združiti.", "mergePartialDetail": "{{ success }} združenih, {{ failed }} neuspešnih." } + }, + "fields": { + "random": "Naključno", + "title": "Naslov", + "author": "Avtor", + "authorSurname": "Avtor (Priimek)", + "genre": "Žanr", + "series": "Zbirka", + "seriesNumber": "Številka v zbirki", + "publisher": "Založba", + "tag": "Oznaka", + "mood": "Vzdušje", + "language": "Jezik", + "narrator": "Pripovedovalec", + "fileType": "Oblika datoteke", + "readStatus": "Status branja", + "personalRating": "Osebna ocena", + "amazonRating": "Amazon ocena", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Goodreads ocena", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Hardcover ocena", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Ranobedb ocena", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Strani", + "publishedDate": "Datum izida", + "publishedYear": "Leto izida", + "addedOn": "Dodano dne", + "lastReadTime": "Zadnje brano", + "dateFinished": "Datum dokončanja", + "readingProgress": "Napredek branja", + "fileName": "Ime datoteke", + "fileSize": "Velikost datoteke", + "isbn": "ISBN", + "library": "Knjižnica", + "shelf": "Polica", + "ageRating": "Starostna omejitev", + "contentRating": "Ocena vsebine", + "matchScore": "Ujemanje metapodatkov", + "shelfStatus": "Status police", + "comicCharacter": "Stripovski lik", + "comicTeam": "Stripovska ekipa", + "comicLocation": "Stripovska lokacija", + "comicCreator": "Stripovski ustvarjalec", + "audibleReviewCount": "Število Audible mnenj" + }, + "viewMode": { + "grid": "Mreža", + "table": "Tabela" } }, "readerAudiobook": { @@ -5378,6 +5430,23 @@ }, "browse": { "showAll": "Pokaži vse", - "moreActions": "Več dejanj" + "moreActions": "Več dejanj", + "sort": { + "apply": "Uporabi" + }, + "bulk": { + "organizeFiles": "Organiziraj datoteke", + "updateReadStatus": "Posodobi status branja", + "lockUnlockMetadata": "Zakleni/Odkleni metapodatke" + }, + "toolbar": { + "columnGroups": { + "file": "Datoteka", + "ratings": "Ocene" + }, + "viewMode": "Pogled", + "density": "Velikost", + "resetColumns": "Ponastavi na privzeto" + } } } diff --git a/frontend/src/i18n/sv.json b/frontend/src/i18n/sv.json index 1842faa0c..61b0bb750 100644 --- a/frontend/src/i18n/sv.json +++ b/frontend/src/i18n/sv.json @@ -3069,7 +3069,8 @@ "customFetchMetadata": "Anpassad metadatahämtning", "autoFetchMetadata": "Auto-hämta metadata", "findDuplicates": "Hitta dubbletter", - "deleteLibrary": "Radera bibliotek" + "deleteLibrary": "Radera bibliotek", + "manageLibrary": "Hantera bibliotek" }, "shelf": { "publicShelfPrefix": "Publik hylla - ", @@ -3708,6 +3709,57 @@ "mergeFailedDetail": "Kunde inte sammanfoga denna grupp.", "mergePartialDetail": "{{ success }} sammanfogade, {{ failed }} misslyckades." } + }, + "viewMode": { + "grid": "Rutnät", + "table": "Tabell" + }, + "fields": { + "random": "Slumpmässig", + "title": "Titel", + "author": "Författare", + "authorSurname": "Författare (efternamn)", + "genre": "Genre", + "series": "Serie", + "seriesNumber": "Serienummer", + "publisher": "Förlag", + "tag": "Tagg", + "mood": "Stämning", + "language": "Språk", + "narrator": "Uppläsare", + "fileType": "Filformat", + "readStatus": "Lässtatus", + "personalRating": "Personligt betyg", + "amazonRating": "Amazon-betyg", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Goodreads-betyg", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Hardcover-betyg", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Ranobedb-betyg", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Sidor", + "publishedDate": "Utgivningsdatum", + "publishedYear": "Utgivningsår", + "addedOn": "Tillagd", + "lastReadTime": "Senast läst", + "dateFinished": "Avslutad datum", + "readingProgress": "Läsframsteg", + "fileName": "Filnamn", + "fileSize": "Filstorlek", + "isbn": "ISBN", + "library": "Bibliotek", + "shelf": "Hylla", + "ageRating": "Åldersbetyg", + "contentRating": "Innehållsbetyg", + "matchScore": "Metadatamatchningspoäng", + "shelfStatus": "Hyllstatus", + "comicCharacter": "Serietidningskaraktär", + "comicTeam": "Serietidningsteam", + "comicLocation": "Serietidningsplats", + "comicCreator": "Serietidningsskapare", + "audibleReviewCount": "Audible-recensioner" } }, "readerAudiobook": { @@ -5377,6 +5429,23 @@ }, "browse": { "showAll": "Visa alla", - "moreActions": "Fler åtgärder" + "moreActions": "Fler åtgärder", + "toolbar": { + "columnGroups": { + "file": "Fil", + "ratings": "Betyg" + }, + "viewMode": "Vy", + "density": "Storlek", + "resetColumns": "Återställ till standard" + }, + "sort": { + "apply": "Tillämpa" + }, + "bulk": { + "organizeFiles": "Organisera filer", + "updateReadStatus": "Uppdatera lässtatus", + "lockUnlockMetadata": "Lås/lås upp metadata" + } } } diff --git a/frontend/src/i18n/uk.json b/frontend/src/i18n/uk.json index 611d37947..6e2d7ba7e 100644 --- a/frontend/src/i18n/uk.json +++ b/frontend/src/i18n/uk.json @@ -3070,7 +3070,8 @@ "customFetchMetadata": "Налаштовуване отримання метаданих", "autoFetchMetadata": "Автозавантаження метаданих", "findDuplicates": "Знайти дублікати", - "deleteLibrary": "Видалити бібліотеку" + "deleteLibrary": "Видалити бібліотеку", + "manageLibrary": "Керувати бібліотекою" }, "shelf": { "publicShelfPrefix": "Публічна полиця - ", @@ -3709,6 +3710,57 @@ "mergeFailedDetail": "Не вдалося об'єднати цю групу.", "mergePartialDetail": "{{ success }} об'єднано, {{ failed }} не вдалося." } + }, + "fields": { + "random": "Випадково", + "title": "Назва", + "author": "Автор", + "authorSurname": "Автор (Прізвище)", + "genre": "Жанр", + "series": "Серія", + "seriesNumber": "Номер у серії", + "publisher": "Видавець", + "tag": "Тег", + "mood": "Настрій", + "language": "Мова", + "narrator": "Оповідач", + "fileType": "Тип книги", + "readStatus": "Статус читання", + "personalRating": "Особистий рейтинг", + "amazonRating": "Рейтинг Amazon", + "amazonReviewCount": "Amazon #", + "goodreadsRating": "Рейтинг Goodreads", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Рейтинг Hardcover", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Рейтинг Ranobedb", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "Сторінки", + "publishedDate": "Дата публікації", + "publishedYear": "Рік видання", + "addedOn": "Додано", + "lastReadTime": "Останнє читання", + "dateFinished": "Дата завершення", + "readingProgress": "Прогрес читання", + "fileName": "Назва файлу", + "fileSize": "Розмір файлу", + "isbn": "ISBN", + "library": "Бібліотека", + "shelf": "Полиця", + "ageRating": "Віковий рейтинг", + "contentRating": "Рейтинг контенту", + "matchScore": "Оцінка збігу метаданих", + "shelfStatus": "Статус полиці", + "comicCharacter": "Персонаж коміксу", + "comicTeam": "Команда коміксу", + "comicLocation": "Локація коміксу", + "comicCreator": "Творець коміксу", + "audibleReviewCount": "Кількість відгуків Audible" + }, + "viewMode": { + "grid": "Сітка", + "table": "Таблиця" } }, "readerAudiobook": { @@ -5378,6 +5430,23 @@ }, "browse": { "showAll": "Показати все", - "moreActions": "Додаткові дії" + "moreActions": "Додаткові дії", + "sort": { + "apply": "Застосувати" + }, + "toolbar": { + "columnGroups": { + "file": "Файл", + "ratings": "Рейтинги" + }, + "viewMode": "Вигляд", + "density": "Розмір", + "resetColumns": "Відновити стандартні" + }, + "bulk": { + "organizeFiles": "Організувати файли", + "updateReadStatus": "Оновити статус читання", + "lockUnlockMetadata": "Заблокувати/Розблокувати метадані" + } } } diff --git a/frontend/src/i18n/zh.json b/frontend/src/i18n/zh.json index f5b514634..5e3017e6e 100644 --- a/frontend/src/i18n/zh.json +++ b/frontend/src/i18n/zh.json @@ -3067,7 +3067,8 @@ "customFetchMetadata": "自定义获取元数据", "autoFetchMetadata": "自动获取元数据", "findDuplicates": "查找重复", - "deleteLibrary": "删除书库" + "deleteLibrary": "删除书库", + "manageLibrary": "管理书库" }, "shelf": { "publicShelfPrefix": "公开书架 - ", @@ -3706,6 +3707,57 @@ "mergeFailedDetail": "无法合并此组。", "mergePartialDetail": "{{ success }} 个已合并,{{ failed }} 个失败。" } + }, + "fields": { + "random": "随机", + "title": "标题", + "author": "作者", + "authorSurname": "作者(姓氏)", + "genre": "类型", + "series": "系列", + "seriesNumber": "系列编号", + "publisher": "出版社", + "tag": "标签", + "mood": "情绪", + "language": "语言", + "narrator": "讲述者", + "fileType": "图书类型", + "readStatus": "阅读状态", + "personalRating": "个人评分", + "amazonRating": "亚马逊评分", + "amazonReviewCount": "亚马逊 #", + "goodreadsRating": "Goodreads 评分", + "goodreadsReviewCount": "Goodreads #", + "hardcoverRating": "Hardcover 评分", + "hardcoverReviewCount": "Hardcover #", + "ranobedbRating": "Ranobedb 评分", + "lubimyczytacRating": "Lubimyczytac rating", + "audibleRating": "Audible rating", + "pageCount": "页数", + "publishedDate": "出版日期", + "publishedYear": "出版年份", + "addedOn": "添加时间", + "lastReadTime": "最后阅读", + "dateFinished": "完成日期", + "readingProgress": "阅读进度", + "fileName": "文件名", + "fileSize": "文件大小", + "isbn": "ISBN", + "library": "书库", + "shelf": "书架", + "ageRating": "年龄分级", + "contentRating": "内容分级", + "matchScore": "元数据匹配分数", + "shelfStatus": "书架状态", + "comicCharacter": "漫画角色", + "comicTeam": "漫画团队", + "comicLocation": "漫画地点", + "comicCreator": "漫画创作者", + "audibleReviewCount": "Audible 评论数" + }, + "viewMode": { + "grid": "网格", + "table": "表格" } }, "readerAudiobook": { @@ -5375,6 +5427,20 @@ }, "browse": { "showAll": "全部显示", - "moreActions": "更多操作" + "moreActions": "更多操作", + "bulk": { + "organizeFiles": "整理文件", + "updateReadStatus": "更新阅读状态", + "lockUnlockMetadata": "锁定/解锁元数据" + }, + "toolbar": { + "columnGroups": { + "file": "文件", + "ratings": "评分" + }, + "viewMode": "视图", + "density": "大小", + "resetColumns": "重置为默认" + } } }
{{ 'browse.book.filteredEmpty' | transloco }}
{{ 'browse.book.empty' | transloco }}