feat(ui): paginated book browser page (#2573)

This commit is contained in:
Alex
2026-09-26 12:55:45 +01:00
committed by GitHub
parent e6fed6e2e7
commit a2f41b29d8
70 changed files with 5139 additions and 236 deletions
+12 -5
View File
@@ -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');
+15 -7
View File
@@ -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]},
@@ -0,0 +1,143 @@
@if (selection().active()) {
<app-browse-bulk-actions-bar
[count]="selection().count()"
[total]="total()"
[moreMenu]="bulkMoreMenu"
[moreAlways]="moreMenuOnlyItems()"
[moreDisabled]="isResolving()"
(clearSelection)="selection().clear()"
(selectAll)="selection().selectAll()">
<app-button
appBrowseBulkActionsItem="addToShelf"
variant="ghost"
size="md"
[disabled]="isResolving()"
[label]="'book.menu.addToShelf' | transloco"
[appMenuTriggerFor]="bulkShelfMenuHost.menu()">
<svg lucideBookmark aria-hidden="true"></svg>
</app-button>
<app-button
appBrowseBulkActionsItem="markAs"
variant="ghost"
size="md"
[disabled]="isResolving()"
[label]="'book.menu.markAs' | transloco"
[appMenuTriggerFor]="bulkMarkAsMenu">
<svg lucideCheck aria-hidden="true"></svg>
</app-button>
@if (bulkPermissions().canEditMetadata) {
<app-button
appBrowseBulkActionsItem="edit"
variant="ghost"
size="md"
[disabled]="isResolving()"
[label]="'common.edit' | transloco"
[appMenuTriggerFor]="bulkEditMenu">
<svg lucidePenLine aria-hidden="true"></svg>
</app-button>
}
@if (bulkMetadataAvailable()) {
<app-button
appBrowseBulkActionsItem="metadata"
variant="ghost"
size="md"
[disabled]="isResolving()"
[label]="'book.menu.metadata' | transloco"
[appMenuTriggerFor]="bulkMetadataMenu">
<svg lucideDatabase aria-hidden="true"></svg>
</app-button>
}
@if (actionPermissions().canDeleteBook) {
<span appBrowseBulkActionsItem="delete" appBrowseBulkActionsTrailing class="flex items-center gap-1">
<app-browse-bulk-actions-divider />
<app-button
variant="ghost"
tone="danger"
size="md"
[label]="'common.delete' | transloco"
[loading]="bulkDeleting()"
[disabled]="isResolving()"
(clicked)="commands.delete()" />
</span>
}
</app-browse-bulk-actions-bar>
<app-shelf-membership-menu
#bulkShelfMenuHost
[shelves]="bulkShelves()"
(toggleShelf)="commands.toggleShelf($event.shelfId, $event.checked)"
(createShelf)="commands.createShelf()"
(removeFromAllShelves)="commands.removeFromAllShelves(bulkShelfIds())" />
<app-menu #bulkMarkAsMenu [ariaLabel]="'book.menu.markAs' | transloco">
@for (status of readStatusTargets; track status) {
<app-menu-item [value]="status" [disabled]="isResolving()" (selected)="commands.markAs(status)">{{ statusLabelKey(status) | transloco }}</app-menu-item>
}
<app-menu-separator />
<app-menu-item value="clear-read-status" [disabled]="isResolving()" (selected)="commands.markAs(clearReadStatus)">
{{ clearReadStatusLabelKey | transloco }}
</app-menu-item>
</app-menu>
<app-menu #bulkEditMenu [ariaLabel]="'common.edit' | transloco">
<app-menu-item value="edit-all" [disabled]="isResolving()" (selected)="commands.editAll()">{{ 'browse.bulk.editAll' | transloco }}</app-menu-item>
<app-menu-item value="edit-one-by-one" [disabled]="isResolving()" (selected)="commands.editOneByOne()">{{ 'browse.bulk.editOneByOne' | transloco }}</app-menu-item>
</app-menu>
<app-menu #bulkMetadataMenu [ariaLabel]="'book.menu.metadata' | transloco">
@if (bulkPermissions().canAutoFetchMetadata) {
<app-menu-item value="fetch-metadata" [disabled]="isResolving()" (selected)="commands.fetchMetadata()">{{ 'book.menu.fetchMetadata' | transloco }}</app-menu-item>
}
@if (bulkPermissions().canCustomFetchMetadata) {
<app-menu-item value="fetch-metadata-with-options" [disabled]="isResolving()" (selected)="commands.fetchMetadataWithOptions()">{{ 'book.menu.fetchMetadataWithOptions' | transloco }}</app-menu-item>
}
<app-menu-separator [class]="autoSeparatorClass" />
@if (bulkPermissions().canLockUnlockMetadata) {
<app-menu-item value="lock-metadata" [disabled]="isResolving()" (selected)="commands.setMetadataLocks(true)">{{ 'metadata.editor.lockAllBtn' | transloco }}</app-menu-item>
<app-menu-item value="unlock-metadata" [disabled]="isResolving()" (selected)="commands.setMetadataLocks(false)">{{ 'metadata.editor.unlockAllBtn' | transloco }}</app-menu-item>
<app-menu-item value="lock-unlock-metadata" [disabled]="isResolving()" (selected)="commands.lockUnlockMetadata()">{{ 'browse.bulk.lockUnlockMetadata' | transloco }}</app-menu-item>
}
<app-menu-separator [class]="autoSeparatorClass" />
@if (bulkPermissions().canRegenerateCover) {
<app-menu-item value="restore-cover" [disabled]="isResolving()" (selected)="commands.changeCovers('regenerate')">{{ 'book.menu.restoreCover' | transloco }}</app-menu-item>
<app-menu-item value="generate-cover" [disabled]="isResolving()" (selected)="commands.changeCovers('generate')">{{ 'book.menu.generateCover' | transloco }}</app-menu-item>
}
</app-menu>
<app-menu #bulkMoreMenu [ariaLabel]="'browse.moreActions' | transloco">
@if (overflowed().has('addToShelf')) {
<app-menu-item value="add-to-shelf" [disabled]="isResolving()" [submenu]="bulkShelfMenuHost.ariaMenu()">{{ 'book.menu.addToShelf' | transloco }}</app-menu-item>
}
@if (overflowed().has('markAs')) {
<app-menu-item value="mark-as" [disabled]="isResolving()" [submenu]="bulkMarkAsMenu.menu">{{ 'book.menu.markAs' | transloco }}</app-menu-item>
}
@if (overflowed().has('edit')) {
<app-menu-item value="edit" [disabled]="isResolving()" [submenu]="bulkEditMenu.menu">{{ 'common.edit' | transloco }}</app-menu-item>
}
@if (overflowed().has('metadata')) {
<app-menu-item value="metadata" [disabled]="isResolving()" [submenu]="bulkMetadataMenu.menu">{{ 'book.menu.metadata' | transloco }}</app-menu-item>
}
<app-menu-separator [class]="autoSeparatorClass" />
@if (actionPermissions().canResetGrimmoryProgress) {
<app-menu-item value="reset-grimmory-progress" [disabled]="isResolving()" (selected)="commands.resetProgress('GRIMMORY')">{{ 'book.menu.resetGrimmoryProgress' | transloco }}</app-menu-item>
}
@if (actionPermissions().canResetKoreaderProgress) {
<app-menu-item value="reset-koreader-progress" [disabled]="isResolving()" (selected)="commands.resetProgress('KOREADER')">{{ 'book.menu.resetKoreaderProgress' | transloco }}</app-menu-item>
}
<app-menu-separator [class]="autoSeparatorClass" />
@if (bulkPermissions().canOrganizeFiles) {
<app-menu-item value="organize-files" [disabled]="isResolving()" (selected)="commands.organizeFiles()">{{ 'browse.bulk.organizeFiles' | transloco }}</app-menu-item>
}
@if (bulkPermissions().canAttachFiles) {
<app-menu-item value="attach-files" [disabled]="!bulkAttachEligible() || isResolving()" (selected)="commands.attachFiles()">
{{ 'book.fileAttacher.attachFilesBulk' | transloco }}
</app-menu-item>
}
<app-menu-separator [class]="autoSeparatorClass" />
@if (overflowed().has('delete')) {
<app-menu-item value="delete" variant="destructive" [loading]="bulkDeleting()" [disabled]="isResolving()" (selected)="commands.delete()">
{{ 'common.delete' | transloco }}
</app-menu-item>
}
</app-menu>
}
@@ -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<BrowseSelectionState>({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<string, boolean>, id = 1) {
return {id, permissions};
}
describe('BookBrowseBulkBarComponent', () => {
let fixture: ComponentFixture<BookBrowseBulkBarComponent>;
let currentUser: WritableSignal<ReturnType<typeof user> | 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]);
});
});
@@ -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<string> = 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<BrowseSelection>();
readonly books = input.required<readonly BookSummary[]>();
readonly total = input.required<number | null>();
readonly fetchIds = input.required<() => Promise<readonly number[]>>();
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];
}
}
@@ -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<BrowseSelectionState>({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<typeof vi.fn>
>;
function commandsFor(selected: BrowseSelection) {
return TestBed.runInInjectionContext(() =>
createBookBrowseBulkCommands({
selection: signal(selected),
books: signal([]),
fetchIds: signal(vi.fn()),
}));
}
type Commands = ReturnType<typeof commandsFor>;
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<void>();
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);
});
});
@@ -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<readonly number[]>;
export interface BookBrowseBulkCommandsOptions {
readonly selection: Signal<BrowseSelection>;
readonly books: Signal<readonly BookSummary[]>;
readonly fetchIds: Signal<FetchMatchingIds>;
}
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<void> {
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<number>) => Promise<DynamicDialogRef | null>): 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}));
},
});
},
};
}
@@ -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> = {}): 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('—');
}
});
});
@@ -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)}%`;
}
@@ -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: `
<div class="app-page pb-0!">
<app-page-header [pageHeader]="pageHeader()">
<div class="w-full">
<app-browse-search-input
[value]="stagedQuery()"
[placeholder]="searchHint()"
[ariaLabel]="searchHint()"
[clearLabel]="'book.searcher.clearSearch' | transloco"
(valueChange)="stagedQuery.set($event)"
(cleared)="stagedQuery.set('')"
(entered)="onCommit()" />
</div>
</app-page-header>
<div class="-mx-1.5 pb-28">
<app-browse-filter-rail
alwaysShowBoxes
[groups]="railGroups()"
(toggleValue)="onToggle($event)"
(commitRange)="onCommitRange($event)" />
</div>
<div
class="fixed inset-x-0 bottom-0 z-20 flex items-center gap-3 border-t border-border bg-page px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
<app-button
variant="ghost"
[label]="'browse.clearFilters' | transloco"
[disabled]="!hasActiveFilters()"
(clicked)="onClear()" />
<app-button
tone="primary"
fluid
[label]="'browse.filterPage.show' | transloco: {count: previewTotal() ?? '…'}"
[loading]="previewLoading()"
(clicked)="onCommit()" />
</div>
</div>
`,
})
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<FacetValueMap>(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<PageHeader>(() => {
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<BookQueryFacetKey>): void {
this.staged.update(current =>
toggleBrowseFacetValue(
current,
toggle.key,
toggle.value,
toggle.selected,
),
);
}
protected onCommitRange(commit: BrowseFilterRangeCommit<BookQueryFacetKey>): 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());
}
}
@@ -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: `
<div class="flex flex-col gap-4 rounded-[var(--p-dialog-border-radius)] border border-border bg-page p-5">
<h2 class="text-lg font-semibold text-text">{{ 'browse.sort.multiSort' | transloco }}</h2>
<app-book-browse-multi-sort-editor [(terms)]="draft" [options]="data.options" />
@if (data.saveDefaultFor; as scope) {
<label for="save-as-default" class="flex cursor-pointer select-none items-center gap-2 text-sm text-text">
<app-checkbox inputId="save-as-default" [(checked)]="saveAsDefault" />
{{ 'book.sorting.saveAsDefault' | transloco: {scope} }}
</label>
}
<div class="flex justify-end gap-2">
<app-button variant="ghost" [label]="'common.cancel' | transloco" (clicked)="cancel()" />
<app-button variant="soft" tone="primary" [label]="'browse.sort.apply' | transloco" (clicked)="apply()" />
</div>
</div>
`,
})
export class BookBrowseMultiSortDialogComponent {
private readonly ref = inject(DynamicDialogRef);
protected readonly data = inject<DynamicDialogConfig<BookBrowseMultiSortDialogData>>(DynamicDialogConfig).data!;
protected readonly draft = signal<readonly BookSortTerm[]>([...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();
}
}
@@ -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: `
<div cdkDropList class="flex flex-col gap-1.5" (cdkDropListDropped)="drop($event)">
@for (row of rows(); track row.key) {
<div
cdkDrag
class="flex min-h-10 items-center gap-2 rounded-md border border-border bg-card py-1 pl-1 pr-2
[.cdk-drop-list-dragging_&]:transition-transform [.cdk-drop-list-dragging_&]:duration-[250ms] [.cdk-drop-list-dragging_&]:ease-out
[&.cdk-drag-animating]:transition-transform [&.cdk-drag-animating]:duration-[250ms] [&.cdk-drag-animating]:ease-out
[&.cdk-drag-placeholder]:opacity-0
[&.cdk-drag-preview]:border-primary [&.cdk-drag-preview]:shadow-pop">
<span cdkDragHandle class="flex h-8 w-6 shrink-0 cursor-grab items-center justify-center text-text-muted">
<svg lucideGripVertical class="size-4" aria-hidden="true"></svg>
</span>
<span class="flex size-5 shrink-0 items-center justify-center rounded-sm bg-page text-xs font-medium tabular-nums text-text-muted">{{ $index + 1 }}</span>
<span class="min-w-0 flex-1 truncate text-sm text-text">{{ row.label }}</span>
<app-button
class="pointer-coarse:hidden"
variant="ghost"
iconOnly
[disabled]="$index === 0"
[ariaLabel]="'browse.sort.moveUp' | transloco"
(clicked)="move($index, -1)">
<svg lucideChevronUp aria-hidden="true"></svg>
</app-button>
<app-button
class="pointer-coarse:hidden"
variant="ghost"
iconOnly
[disabled]="$index === rows().length - 1"
[ariaLabel]="'browse.sort.moveDown' | transloco"
(clicked)="move($index, 1)">
<svg lucideChevronDown aria-hidden="true"></svg>
</app-button>
<app-button
variant="ghost"
iconOnly
[disabled]="!row.canFlip"
[ariaLabel]="'browse.sort.flipDirection' | transloco"
(clicked)="flip($index)">
<svg [lucideIcon]="row.icon" aria-hidden="true"></svg>
</app-button>
<app-button
variant="ghost"
iconOnly
[disabled]="rows().length === 1"
[ariaLabel]="'common.remove' | transloco"
(clicked)="removeAt($index)">
<svg lucideX aria-hidden="true"></svg>
</app-button>
</div>
}
</div>
<app-select
class="mt-3 block"
[options]="addOptions()"
[(value)]="addSelection"
[placeholder]="'browse.sort.addField' | transloco"
[ariaLabel]="'browse.sort.addField' | transloco"
(valueChange)="add($event)" />
`,
})
export class BookBrowseMultiSortEditorComponent {
private readonly transloco = inject(TranslocoService);
private readonly activeLang = toSignal(this.transloco.langChanges$, {
initialValue: this.transloco.getActiveLang(),
});
readonly terms = model.required<readonly BookSortTerm[]>();
readonly options = input.required<readonly BookSortOption[]>();
protected readonly addSelection = signal<string | null>(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<SelectOption<string>[]>(() => {
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<unknown>): 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);
}
}
@@ -0,0 +1,174 @@
<div appArtworkRevealGroup [class]="layoutClasses().page">
<app-page-header [pageHeader]="pageHeader()" [stuckHairline]="false">
@if (mobileSelectMode()) {
<app-browse-select-mode-controls
[count]="selection.count()"
[total]="presentation.total()"
(selectAll)="selection.selectAll()"
(cancelled)="onMobileSelectToggle()" />
} @else {
<app-book-browse-toolbar
[sortOptions]="sortOptions()"
[sortTerms]="sortTerms()"
[viewMode]="preferences.viewMode()"
[columnOptions]="preferences.columnOptions()"
[densitySmallerDisabled]="densitySmallerDisabled()"
[densityLargerDisabled]="densityLargerDisabled()"
[filtersOpen]="railVisible()"
[actionTarget]="queries.actionTarget()"
(sortChange)="preferences.setSortTerms([$event])"
(sortDirectionChange)="onSortDirectionChange($event)"
(randomSortRequested)="onRandomSortRequested()"
(multiSortRequested)="onMultiSortRequested()"
(viewModeChange)="urlState.setView($event)"
(columnVisibilityChange)="preferences.setColumnVisibility($event)"
(columnsReset)="preferences.resetColumns()"
(densityChange)="onDensityChange($event)"
(filtersToggle)="onFiltersToggle()"
(mobileSelectToggle)="onMobileSelectToggle()" />
}
</app-page-header>
<app-book-menu
openInNewTab
[books]="books()"
(deleted)="selection.pruneDeleted($event)" />
<app-book-browse-bulk-bar
[selection]="selection"
[books]="books()"
[total]="presentation.total()"
[fetchIds]="fetchMatchingBookIds" />
<div [class]="layoutClasses().row">
<div [class]="layoutClasses().column">
@if (chipsBand().count > 0) {
<div [class]="chipsBandClass()">
<app-browse-filter-chips
[chips]="chipsBand().chips"
[query]="chipsBand().query"
[mobile]="isMobile()"
(removeChip)="onToggleFacet({key: $event.key, value: $event.value, selected: false})"
(removeSearch)="onClearQuery()"
(clearAll)="onClearAllFilters()" />
</div>
} @else {
<div [class]="hairlineStripClass()"></div>
}
@if (preferences.viewMode() === 'table') {
<app-book-browse-table
[books]="books()"
[status]="presentation.status()"
[hasNextPage]="hasNextPage()"
[nextPageError]="presentation.nextPageError()"
[initialErrorMessage]="'browse.book.loadError' | transloco"
[nextPageErrorMessage]="'browse.book.pageError' | transloco"
[useSquareCovers]="squareCovers()"
[pendingDeletionIds]="pendingDeletions()"
[visibleColumns]="preferences.visibleColumns()"
[sortTerms]="sortTerms()"
[sortOptions]="sortOptions()"
[mobile]="mobileTableLayout()"
[selection]="selectionEnabled() ? selection : null"
[selectMode]="mobileSelectMode()"
[openMenuBookId]="menuOpenBookId()"
(sortTermsChange)="preferences.setSortTerms($event)"
(facetRequested)="onToggleFacet({key: $event.key, value: $event.value, selected: true})"
(menuRequested)="bookMenu()?.openFor($event.book, $event.request)"
(detailRequested)="onBookDetailRequested($event)"
(retryInitial)="presentation.retryInitial()"
(retryNextPage)="presentation.retryNextPage()">
<ng-template appBrowseEmpty>
<ng-container *ngTemplateOutlet="emptyState" />
</ng-template>
</app-book-browse-table>
} @else {
<app-browse-grid
[class]="gridBoxClass()"
[items]="books()"
[itemKey]="bookItemKey"
[hasNextPage]="hasNextPage()"
[status]="presentation.status()"
[nextPageError]="presentation.nextPageError()"
[fixedColumns]="gridColumns()"
[minItemWidth]="minCardWidth()"
[gap]="gridGap()"
[rowGap]="gridRowGap"
[estimateItemHeight]="estimateItemHeight"
[initialErrorMessage]="'browse.book.loadError' | transloco"
[nextPageErrorMessage]="'browse.book.pageError' | transloco"
(retryInitial)="presentation.retryInitial()"
(retryNextPage)="presentation.retryNextPage()">
<ng-template [appBrowseGridItemOf]="books()" let-book let-index="index">
<app-book-card
[class.opacity-50]="pendingDeletions().has(book.id)"
[book]="book"
[showFormatPill]="preferences.formatPill()"
[squareCovers]="squareCovers()"
[detailLine]="detailLineFor(book)"
[selectable]="selectionEnabled()"
[selected]="selectionEnabled() && selection.isSelected(book.id)"
[selectionActive]="selectionEnabled() && (selection.active() || mobileSelectMode())"
[detailMode]="'request'"
[menuOpen]="menuOpenBookId() === book.id"
(toggleSelect)="selection.toggle(book, index, $event.shiftKey)"
(action)="bookNavigation.readBook(book)"
(detailRequested)="onBookDetailRequested(book)"
(menuRequested)="bookMenu()?.openFor(book, $event)" />
</ng-template>
<ng-template appBrowseGridSkeleton>
<app-book-card-skeleton [squareCovers]="squareCovers()" [metaLines]="metaLines()" />
</ng-template>
<ng-template appBrowseEmpty>
<ng-container *ngTemplateOutlet="emptyState" />
</ng-template>
</app-browse-grid>
}
</div>
@if (railVisible()) {
<aside [class]="railClass()">
<div class="-mx-1.5 flex min-h-0 flex-1 flex-col">
<div class="mb-2 border-b border-border/50 pb-4">
<div class="mb-2 flex h-6 items-center px-2">
<h3 class="m-0 text-[13px] font-semibold text-text-secondary">{{ queries.searchHint() }}</h3>
</div>
<div class="px-2">
<app-browse-search-input
size="sm"
[value]="searchDraft.value()"
[placeholder]="'browse.rail.searchFields' | transloco"
[ariaLabel]="queries.searchHint()"
[clearLabel]="'book.searcher.clearSearch' | transloco"
(valueChange)="searchDraft.set($event)"
(cleared)="onClearQuery()" />
</div>
</div>
<div class="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-6 [--page-stuck-offset:0px]">
@if (railReady()) {
<app-browse-filter-rail
[groups]="queries.railGroups()"
(toggleValue)="onToggleFacet($event)"
(commitRange)="onCommitFacetRange($event)" />
}
</div>
</div>
</aside>
}
</div>
</div>
<ng-template #emptyState>
@if (chipsBand().count > 0) {
<div class="flex flex-col items-center gap-2 py-16">
<p class="m-0 text-sm text-text-muted">{{ 'browse.book.filteredEmpty' | transloco }}</p>
<app-button
variant="ghost"
size="sm"
[label]="'browse.clearFilters' | transloco"
(clicked)="onClearAllFilters()" />
</div>
} @else {
<p class="py-16 text-center text-sm text-text-muted">{{ 'browse.book.empty' | transloco }}</p>
}
</ng-template>
@@ -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<string, boolean>, id?: number, global: Record<string, unknown> = {}) {
return {
...(id === undefined ? {} : {id}),
permissions,
userSettings: {entityViewPreferences: {global: {...GLOBAL_PREFERENCE, ...global}, overrides: []}},
};
}
describe('BookBrowsePageComponent', () => {
let fixture: ComponentFixture<BookBrowsePageComponent>;
let http: HttpTestingController;
let queryClient: QueryClient;
let currentUser: WritableSignal<ReturnType<typeof userFixture> | null>;
let updateUserSetting: ReturnType<typeof vi.fn>;
function grid(): BrowseGridComponent<BookSummary> {
return fixture.debugElement.query(By.directive(BrowseGridComponent))
.componentInstance as BrowseGridComponent<BookSummary>;
}
function viewport(): BrowseGridViewportComponent<BookSummary> {
return fixture.debugElement.query(By.directive(BrowseGridViewportComponent))
.componentInstance as BrowseGridViewportComponent<BookSummary>;
}
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<RouterTestingHarness> {
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();
}
});
});
@@ -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<BookQueryFacetKey>[];
}
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<boolean, boolean>({
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<boolean>(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<ReadonlySet<BookQuerySortKey>>(
() => 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<BookPageParams>(() => ({
...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<BookSummary>({
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<BrowseChipsBand>(
() => ({
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<PendingBookOverlay>(() => ({
readStatuses: this.pendingReadStatuses(),
progressResets: this.pendingProgressResets(),
}));
protected readonly books = computed<readonly BookSummary[]>(() => {
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<readonly number[]> =>
this.queryClient.query(this.bookQuery.ids(this.params()));
private readonly detailLineKey = heldSignal<BookDetailLineSortKey | null>(
() => {
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<PageHeader>(() => {
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<BookQueryFacetKey>): void {
this.urlState.setFacets(toggleBrowseFacetValue(
this.urlState.facets(),
toggle.key,
toggle.value,
toggle.selected,
));
}
protected onCommitFacetRange(commit: BrowseFilterRangeCommit<BookQueryFacetKey>): 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<void> {
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);
}
});
}
}
@@ -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<EntityViewPreferenceContext | null>;
readonly availableSortKeys: Signal<ReadonlySet<BookQuerySortKey>>;
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<BookBrowseViewMode>(() =>
urlState.view() ?? (entityViewMode(entityViewPreferences(), context()) === 'TABLE' ? 'table' : 'grid'));
const formatPill = computed(() => entityViewPreferences()?.global?.overlayBookType ?? true);
const defaultSortTerms = computed<readonly BookSortTerm[]>(() => {
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<readonly BookSortTerm[]>(() => {
const terms = urlState.sortTerms();
return terms.length > 0 ? terms : defaultSortTerms();
});
const isDefaultSort = (terms: readonly BookSortTerm[]): boolean =>
sortTermsToken(terms) === sortTermsToken(defaultSortTerms());
const columnPreferences = linkedSignal<TableColumnPreference[]>(() =>
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<EntityViewPreference>): 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),
));
},
};
}
@@ -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<FacetValueMap>;
readonly query: Signal<string>;
readonly scope: Signal<BookBrowseScope | null>;
readonly enabled?: Signal<boolean>;
}
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<BookCollectionFilterParams>(() => ({
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<BrowseFacetDefinitions<BookQueryFacetKey>>(() => {
activeLang();
return bookFacetDefinitions(bookFacetLabelDeps(
shelfDefinitions(),
libraryService.libraries(),
key => transloco.translate(key),
));
});
const frozen = computed<BrowseFrozenFacetOrders | undefined>(() => {
const data = scopeFacetsQuery.data();
return data ? browseFrozenFacetOrders(data.facets, definitions()) : undefined;
});
const railGroups = computed<BrowseFilterGroup<BookQueryFacetKey>[]>(() =>
browseFilterGroups(facetsQuery.data()?.facets ?? [], frozen(), definitions(), selection()));
const chips = computed<BrowseFilterChip<BookQueryFacetKey>[]>(() =>
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<LibraryShelfMenuTarget | null>(() => {
const target = bookBrowseScopeMenuTarget(
scope(),
libraryService.libraries(),
shelfDefinitions(),
magicShelfService.shelves(),
);
return target && libraryShelfMenuAvailable(target, userService.currentUser()) ? target : null;
});
return {
collectionParams,
definitions,
sortTokens: computed<readonly string[]>(() => scopeFacetsQuery.data()?.sortTokens ?? []),
pending: computed(() => facetsQuery.isPending()),
chips,
railGroups,
title,
searchHint,
actionTarget,
};
}
@@ -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']});
});
});
@@ -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;
}
@@ -0,0 +1,185 @@
<app-radio-group
class="hidden sm:block"
variant="segmented"
size="md"
[ariaLabel]="'browse.toolbar.viewMode' | transloco"
[options]="[
{value: 'grid', label: ('book.viewMode.grid' | transloco), icon: gridIcon},
{value: 'table', label: ('book.viewMode.table' | transloco), icon: tableIcon}
]"
[value]="viewMode()"
(valueChange)="onViewModeValue($event)" />
<span
role="group"
[class]="sortGroupClass"
[attr.aria-label]="'browse.toolbar.sort' | transloco">
<app-button
variant="soft"
[styleClass]="sortFieldButtonClass()"
[label]="(activeField().labelKey | transloco) + (multiSortActive() ? ' ' + multiSortShortcut() : '')"
[ariaLabel]="'browse.toolbar.sortAria' | transloco: {
field: activeField().labelKey | transloco
}"
[appMenuTriggerFor]="sortMenu" />
@if (activeSortHasSecondaryAction()) {
<app-button
variant="soft"
iconOnly
[styleClass]="sortDirectionButtonClass"
[ariaLabel]="secondarySortActionLabelKey() | transloco"
[title]="secondarySortActionLabelKey() | transloco"
(clicked)="activateSecondarySortAction()">
<svg [lucideIcon]="activeSortIcon()" aria-hidden="true"></svg>
</app-button>
}
</span>
<app-menu #sortMenu menuClass="w-60" [ariaLabel]="'browse.toolbar.sort' | transloco" (opened)="onSortMenuOpened()">
@for (option of commonOptions(); track option.id) {
<app-menu-item
[value]="option.id"
[icon]="directionIconFor(option)"
[badge]="sortRankFor(option)"
inset
(selected)="onSelect(option)">
{{ option.labelKey | transloco }}
</app-menu-item>
}
@if (moreOptions().length > 0) {
@if (moreSortsExpanded()) {
<div class="grid grid-rows-[1fr] transition-[grid-template-rows] duration-200 ease-out starting:grid-rows-[0fr] motion-reduce:transition-none">
<div class="min-h-0 overflow-hidden">
@for (option of moreOptions(); track option.id) {
<app-menu-item
[value]="option.id"
[icon]="directionIconFor(option)"
[badge]="sortRankFor(option)"
inset
(selected)="onSelect(option)">
{{ option.labelKey | transloco }}
</app-menu-item>
}
</div>
</div>
}
<app-menu-item value="toggle-more-sorts" [icon]="moreSortsToggleIcon()" [closeOnSelect]="false" (selected)="moreSortsExpanded.set(!moreSortsExpanded())">
<span class="text-text-muted">
{{ (moreSortsExpanded() ? 'browse.showFewer' : 'browse.showAll') | transloco }}
</span>
</app-menu-item>
}
@if (sortOptions().length > 0) {
<app-menu-separator />
<app-menu-item
value="multi-sort"
[class]="multiSortActive() ? 'bg-active-surface text-primary! [&_svg]:text-primary!' : ''"
[icon]="multiSortIcon"
[shortcut]="multiSortShortcut()"
(selected)="multiSortRequested.emit()">
{{ 'browse.sort.multiSort' | transloco }}
</app-menu-item>
}
</app-menu>
<app-button
class="sm:hidden"
variant="soft"
[label]="'browse.filter' | transloco"
[ariaExpanded]="filtersOpen()"
(clicked)="filtersToggle.emit()">
<svg
lucideFunnel
[attr.fill]="filtersOpen() ? 'currentColor' : 'none'"
aria-hidden="true"></svg>
</app-button>
<app-button
class="sm:hidden"
variant="soft"
[label]="'common.select' | transloco"
(clicked)="mobileSelectToggle.emit()" />
<span class="hidden h-6 w-px bg-border sm:block" aria-hidden="true"></span>
<app-button
class="ml-auto sm:ml-0"
variant="ghost"
iconOnly
[ariaLabel]="'browse.moreActions' | transloco"
[appMenuTriggerFor]="moreMenu">
<svg lucideEllipsis aria-hidden="true"></svg>
</app-button>
<app-menu #moreMenu [ariaLabel]="'browse.moreActions' | transloco">
<app-menu-section class="hidden sm:block">{{ 'browse.toolbar.viewMode' | transloco }}</app-menu-section>
@if (viewMode() === 'grid') {
<div class="flex min-h-8 w-full select-none items-center gap-2 pl-2 pr-0 text-sm leading-5 text-text pointer-coarse:min-h-11 pointer-coarse:pl-3">
<span class="min-w-0 flex-1 truncate">{{ 'browse.toolbar.density' | transloco }}</span>
<app-menu-item
value="smaller-cards"
[class]="stepperItemClass"
[icon]="smallerIcon"
[disabled]="densitySmallerDisabled()"
[closeOnSelect]="false"
[attr.aria-label]="'browse.toolbar.smallerCards' | transloco"
(selected)="densityChange.emit('smaller')" />
<app-menu-item
value="larger-cards"
[class]="stepperItemClass"
[icon]="largerIcon"
[disabled]="densityLargerDisabled()"
[closeOnSelect]="false"
[attr.aria-label]="'browse.toolbar.largerCards' | transloco"
(selected)="densityChange.emit('larger')" />
</div>
<app-menu-separator />
}
<div class="contents sm:hidden">
<app-menu-radio-group [value]="viewMode()" (valueSelected)="selectView($event)">
<app-menu-radio value="grid">{{ 'book.viewMode.grid' | transloco }}</app-menu-radio>
<app-menu-radio value="table">{{ 'book.viewMode.table' | transloco }}</app-menu-radio>
</app-menu-radio-group>
</div>
@if (viewMode() !== 'grid') {
<app-menu-separator class="sm:hidden" />
<app-menu-item value="columns" [submenu]="columnsMenu">{{ 'browse.toolbar.columns' | transloco }}</app-menu-item>
}
<div class="hidden sm:contents">
<app-menu-checkbox
value="show-filters"
[checked]="filtersOpen()"
(selected)="filtersToggle.emit()">
{{ 'browse.toolbar.showFilters' | transloco }}
</app-menu-checkbox>
</div>
@if (actionTarget(); as target) {
<app-menu-separator />
<app-menu-section>{{ target.entity.name }}</app-menu-section>
<app-library-shelf-menu-items [target]="target" />
}
</app-menu>
<app-menu
#columnsMenu="ngMenu"
menuClass="w-[34rem] max-w-[calc(100vw-1rem)]"
[ariaLabel]="'browse.toolbar.columns' | transloco">
<div class="columns-1 gap-3 sm:max-h-[min(32rem,calc(100vh-2rem))] sm:overflow-y-auto sm:columns-2">
@for (section of columnSections(); track section.id) {
<div class="min-w-0 break-inside-avoid">
<app-menu-section>{{ 'browse.toolbar.columnGroups.' + section.id | transloco }}</app-menu-section>
@for (column of section.columns; track column.field) {
<app-menu-checkbox
[value]="column.field"
[checked]="!column.hideable || column.visible"
[disabled]="!column.hideable"
[closeOnSelect]="false"
(selected)="columnVisibilityChange.emit({field: column.field, visible: $event})">
{{ column.labelKey | transloco }}
</app-menu-checkbox>
}
</div>
}
</div>
<app-menu-separator />
<app-menu-item value="reset-columns" (selected)="columnsReset.emit()">
{{ 'browse.toolbar.resetColumns' | transloco }}
</app-menu-item>
</app-menu>
@@ -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<BookBrowseToolbarComponent>;
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;
}
});
@@ -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 BookSortOption[]>();
readonly sortTerms = input.required<readonly BookSortTerm[]>();
readonly viewMode = input.required<BookBrowseViewMode>();
readonly columnOptions = input.required<readonly BookColumnOption[]>();
readonly densitySmallerDisabled = input.required<boolean>();
readonly densityLargerDisabled = input.required<boolean>();
readonly filtersOpen = input.required<boolean>();
readonly actionTarget = input.required<LibraryShelfMenuTarget | null>();
readonly sortChange = output<BookSortTerm>();
readonly sortDirectionChange = output<BookSortTerm>();
readonly randomSortRequested = output();
readonly multiSortRequested = output();
readonly viewModeChange = output<BookBrowseViewMode>();
readonly columnVisibilityChange = output<BookBrowseColumnVisibilityChange>();
readonly columnsReset = output();
readonly densityChange = output<GridDensityDirection>();
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<LucideIconData>(() =>
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<BookSortTerm>(() => 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<readonly BookColumnSection[]>(() => {
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());
}
}
@@ -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<typeof createBookBrowseUrlState>;
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<readonly BookSortTerm[]>(() =>
parseSortTermsToken(queryParamMap().get('sort')));
const view = computed<BookBrowseViewMode | null>(() => {
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',
});
},
};
}
@@ -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<DynamicDialogRef | null> {
async openBulkBookFileAttacherDialog(
sourceBooks: readonly BookFileAttacherSourceBook[],
): Promise<DynamicDialogRef | null> {
return this.dialogLauncherService.launchLazyDialog(async () => {
const {BookFileAttacherComponent} = await import('../book-file-attacher/book-file-attacher.component');
return this.openDialog(BookFileAttacherComponent, {
@@ -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');
@@ -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') {
<app-menu-item value="add-physical-book" (selected)="actions.addPhysicalBook(current.entity.id)">
{{ 'book.shelfMenuService.library.addPhysicalBook' | transloco }}
</app-menu-item>
<app-menu-item value="import-isbns" (selected)="actions.importIsbns(current.entity.id)">
{{ 'book.shelfMenuService.library.bulkIsbnImport' | transloco }}
</app-menu-item>
<app-menu-item value="rescan-library" (selected)="actions.rescanLibrary(current.entity)">
{{ 'book.shelfMenuService.library.rescanLibrary' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item value="manage-library" [submenu]="manageLibraryMenu">
{{ 'book.shelfMenuService.library.manageLibrary' | transloco }}
</app-menu-item>
<app-menu
#manageLibraryMenu="ngMenu"
[ariaLabel]="'book.shelfMenuService.library.manageLibrary' | transloco">
<app-menu-item value="edit-library" (selected)="actions.editLibrary(current.entity.id)">
{{ 'book.shelfMenuService.library.editLibrary' | transloco }}
</app-menu-item>
<app-menu-item value="custom-fetch-metadata" (selected)="actions.customFetchLibraryMetadata(current.entity.id)">
{{ 'book.shelfMenuService.library.customFetchMetadata' | transloco }}
</app-menu-item>
<app-menu-item value="auto-fetch-metadata" (selected)="actions.autoFetchLibraryMetadata(current.entity.id)">
{{ 'book.shelfMenuService.library.autoFetchMetadata' | transloco }}
</app-menu-item>
<app-menu-item value="find-duplicates" (selected)="actions.findLibraryDuplicates(current.entity.id)">
{{ 'book.shelfMenuService.library.findDuplicates' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item value="delete-library" variant="destructive" (selected)="actions.deleteLibrary(current.entity)">
{{ 'book.shelfMenuService.library.deleteLibrary' | transloco }}
</app-menu-item>
</app-menu>
}
@case ('shelf') {
@if (current.entity.publicShelf || !canManageShelf()) {
<app-menu-section>
@if (current.entity.publicShelf) {
{{ 'book.shelfMenuService.shelf.publicShelfPrefix' | transloco }}
}
{{ (canManageShelf()
? 'book.shelfMenuService.shelf.optionsLabel'
: 'book.shelfMenuService.shelf.readOnly') | transloco }}
</app-menu-section>
}
<app-menu-item
value="edit-shelf"
[disabled]="!canManageShelf()"
(selected)="actions.editShelf(current.entity.id)">
{{ 'book.shelfMenuService.shelf.editShelf' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
value="delete-shelf"
[disabled]="!canManageShelf()"
variant="destructive"
(selected)="actions.deleteShelf(current.entity)">
{{ 'book.shelfMenuService.shelf.deleteShelf' | transloco }}
</app-menu-item>
}
@case ('magicShelf') {
<app-menu-item
value="edit-magic-shelf"
[disabled]="!canManageMagicShelf()"
(selected)="actions.editMagicShelf(current.entity.id)">
{{ 'book.shelfMenuService.magicShelf.editMagicShelf' | transloco }}
</app-menu-item>
<app-menu-item value="export-magic-shelf" (selected)="actions.copyMagicShelfJson(current.entity.filterJson)">
{{ 'book.shelfMenuService.magicShelf.exportJson' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
value="delete-magic-shelf"
[disabled]="!canManageMagicShelf()"
variant="destructive"
(selected)="actions.deleteMagicShelf(current.entity)">
{{ 'book.shelfMenuService.magicShelf.deleteMagicShelf' | transloco }}
</app-menu-item>
}
}
`,
})
export class LibraryShelfMenuItemsComponent {
readonly target = input.required<LibraryShelfMenuTarget>();
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);
});
}
@@ -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);
@@ -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<T extends {id?: number | null}> = Omit<T, 'id'> & {id: number};
export type LibraryShelfMenuTarget =
| {type: 'library'; entity: Persisted<Library>}
| {type: 'shelf'; entity: Persisted<Shelf>}
| {type: 'magicShelf'; entity: Persisted<MagicShelf>};
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();
<app-menu
[ariaLabel]="ariaLabel()"
(opened)="opened.emit()"
(closed)="closed.emit()">
<ng-template appMenuContent>
@if (available()) {
@switch (currentTarget.type) {
@case ('library') {
<app-menu-item value="add-physical-book" (selected)="actions.addPhysicalBook(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.addPhysicalBook' | transloco }}
</app-menu-item>
<app-menu-item value="import-isbns" (selected)="actions.importIsbns(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.bulkIsbnImport' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
value="edit-library"
(selected)="actions.editLibrary(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.editLibrary' | transloco }}
</app-menu-item>
<app-menu-item value="rescan-library" (selected)="actions.rescanLibrary(currentTarget.entity)">
{{ 'book.shelfMenuService.library.rescanLibrary' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item value="custom-fetch-metadata" (selected)="actions.customFetchLibraryMetadata(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.customFetchMetadata' | transloco }}
</app-menu-item>
<app-menu-item value="auto-fetch-metadata" (selected)="actions.autoFetchLibraryMetadata(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.autoFetchMetadata' | transloco }}
</app-menu-item>
<app-menu-item value="find-duplicates" (selected)="actions.findLibraryDuplicates(currentTarget.entity.id)">
{{ 'book.shelfMenuService.library.findDuplicates' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
value="delete-library"
[icon]="trashIcon"
variant="destructive"
(selected)="actions.deleteLibrary(currentTarget.entity)">
{{ 'book.shelfMenuService.library.deleteLibrary' | transloco }}
</app-menu-item>
}
@case ('shelf') {
@if (currentTarget.entity.publicShelf || !canManageShelf()) {
<app-menu-section>
@if (currentTarget.entity.publicShelf) {
{{ 'book.shelfMenuService.shelf.publicShelfPrefix' | transloco }}
}
{{ (canManageShelf()
? 'book.shelfMenuService.shelf.optionsLabel'
: 'book.shelfMenuService.shelf.readOnly') | transloco }}
</app-menu-section>
}
<app-menu-item
value="edit-shelf"
[disabled]="!canManageShelf()"
(selected)="actions.editShelf(currentTarget.entity.id)">
{{ 'book.shelfMenuService.shelf.editShelf' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
value="delete-shelf"
[icon]="trashIcon"
[disabled]="!canManageShelf()"
variant="destructive"
(selected)="actions.deleteShelf(currentTarget.entity)">
{{ 'book.shelfMenuService.shelf.deleteShelf' | transloco }}
</app-menu-item>
}
@case ('magicShelf') {
<app-menu-item
value="edit-magic-shelf"
[disabled]="!canManageMagicShelf()"
(selected)="actions.editMagicShelf(currentTarget.entity.id)">
{{ 'book.shelfMenuService.magicShelf.editMagicShelf' | transloco }}
</app-menu-item>
<app-menu-item value="export-magic-shelf" (selected)="actions.copyMagicShelfJson(currentTarget.entity.filterJson)">
{{ 'book.shelfMenuService.magicShelf.exportJson' | transloco }}
</app-menu-item>
<app-menu-separator />
<app-menu-item
value="delete-magic-shelf"
[icon]="trashIcon"
[disabled]="!canManageMagicShelf()"
variant="destructive"
(selected)="actions.deleteMagicShelf(currentTarget.entity)">
{{ 'book.shelfMenuService.magicShelf.deleteMagicShelf' | transloco }}
</app-menu-item>
}
}
<app-library-shelf-menu-items [target]="target()" />
}
</ng-template>
</app-menu>
@@ -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()),
);
}
@@ -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}`,
},
});
}
@@ -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);
});
});
@@ -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)]),
};
}
@@ -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) {
@@ -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<Record<ReadStatus, string>>;
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<Record<string, string>> = {
'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;
}
@@ -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({
@@ -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]);
});
});
@@ -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<BookNavigationState | null>(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) {
@@ -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}});
@@ -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(['/']);
}
}
@@ -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
@@ -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',
}
});
});
@@ -580,7 +580,7 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
onMetadataClick(type: MetadataType, value: string): void {
const filterKeyMap: Record<MetadataType, string> = {
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}`,
}
});
}
@@ -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();
});
});
@@ -0,0 +1,66 @@
import {
type EntityViewPreference,
type EntityViewPreferenceOverride,
type EntityViewPreferences,
type SortCriterion,
} from './user.service';
export type EntityViewPreferenceContext = Pick<EntityViewPreferenceOverride, 'entityType' | 'entityId'>;
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<EntityViewPreference> {
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<EntityViewPreference>,
): 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;
}
@@ -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<void>(`${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,
});
}
@@ -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};
};
@@ -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'
@@ -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<DynamicDialogRef | null> {
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<DynamicDialogRef | null> {
return this.launchLazyDialog(async () => {
const {IconPickerComponent} = await import('../components/icon-picker/icon-picker-component');
@@ -0,0 +1,8 @@
import {linkedSignal, type Signal} from '@angular/core';
export function heldSignal<S>(value: () => S, hold: () => boolean): Signal<S> {
return linkedSignal<{stale: boolean; value: S}, S>({
source: () => ({stale: hold(), value: value()}),
computation: (source, previous) => (source.stale && previous ? previous.value : source.value),
});
}
+4
View File
@@ -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%);
}
+44
View File
@@ -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": {
+44
View File
@@ -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": {
+71 -2
View File
@@ -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"
}
}
}
+59 -4
View File
@@ -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"
}
}
}
+70 -1
View File
@@ -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"
}
}
}
+67 -1
View File
@@ -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"
}
}
}
+70 -1
View File
@@ -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"
}
}
}
+53 -1
View File
@@ -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"
}
}
}
+62
View File
@@ -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"
}
}
}
+67 -2
View File
@@ -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"
}
}
}
+68 -2
View File
@@ -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": "デフォルトに戻す"
}
}
}
+44
View File
@@ -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": {
+55 -2
View File
@@ -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"
}
}
}
+68 -2
View File
@@ -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"
}
}
}
+68 -2
View File
@@ -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"
}
}
}
+68 -2
View File
@@ -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": "Сбросить по умолчанию"
}
}
}
+49 -1
View File
@@ -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"
}
}
}
+71 -2
View File
@@ -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"
}
}
}
+71 -2
View File
@@ -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"
}
}
}
+71 -2
View File
@@ -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": "Заблокувати/Розблокувати метадані"
}
}
}
+68 -2
View File
@@ -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": "重置为默认"
}
}
}