refactor(frontend): rename booklore-ui to frontend

- Frontend path:
  - rename the tracked Angular app tree from `booklore-ui/` to `frontend/`
  - preserve file contents during the move so this commit stays focused on the path change itself
- Frontend docs:
  - update the moved frontend README and contribution guide where they refer to the renamed folder
  - keep those edits limited to path references introduced by the directory rename
This commit is contained in:
James Cox
2026-04-22 17:26:39 -04:00
committed by Zach Yale
parent c99aa87877
commit 874b013f75
1493 changed files with 3 additions and 3 deletions
@@ -0,0 +1,97 @@
import {Injectable, inject} from '@angular/core';
import {ParamMap} from '@angular/router';
import {Library} from '../../model/library.model';
import {Shelf} from '../../model/shelf.model';
import {Book} from '../../model/book.model';
import {LibraryService} from '../../service/library.service';
import {ShelfService} from '../../service/shelf.service';
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
import {EntityType} from './book-browser.component';
export interface EntityInfo {
entityId: number;
entityType: EntityType;
}
@Injectable({providedIn: 'root'})
export class BookBrowserEntityService {
private libraryService = inject(LibraryService);
private shelfService = inject(ShelfService);
private magicShelfService = inject(MagicShelfService);
private bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
getEntityInfo(paramMap: ParamMap): EntityInfo {
const libraryId = Number(paramMap.get('libraryId') || NaN);
const shelfId = Number(paramMap.get('shelfId') || NaN);
const magicShelfId = Number(paramMap.get('magicShelfId') || NaN);
if (!Number.isNaN(libraryId)) {
return {entityId: libraryId, entityType: EntityType.LIBRARY};
}
if (!Number.isNaN(shelfId)) {
return {entityId: shelfId, entityType: EntityType.SHELF};
}
if (!Number.isNaN(magicShelfId)) {
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
}
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
getEntity(entityId: number, entityType: EntityType): Library | Shelf | MagicShelf | null {
switch (entityType) {
case EntityType.LIBRARY:
return this.libraryService.libraries().find(lib => lib.id === entityId) ?? null;
case EntityType.SHELF:
return this.shelfService.shelves().find(shelf => shelf.id === entityId) ?? null;
case EntityType.MAGIC_SHELF:
return this.magicShelfService.findShelfById(entityId) ?? null;
default:
return null;
}
}
getBooksByEntity(books: Book[], entityId: number, entityType: EntityType): Book[] {
switch (entityType) {
case EntityType.LIBRARY:
return books.filter(book => book.libraryId === entityId);
case EntityType.SHELF:
return books.filter(book => book.shelves?.some(shelf => shelf.id === entityId) ?? false);
case EntityType.MAGIC_SHELF: {
const magicShelf = this.getEntity(entityId, entityType);
return this.isMagicShelf(magicShelf) ? this.filterByMagicShelf(books, magicShelf) : [];
}
case EntityType.UNSHELVED:
return books.filter(book => !book.shelves || book.shelves.length === 0);
case EntityType.ALL_BOOKS:
default:
return books;
}
}
isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
return (entity as Library).paths !== undefined;
}
isMagicShelf(entity: Library | Shelf | MagicShelf | null): entity is MagicShelf {
return !!entity && 'filterJson' in entity;
}
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
if (!magicShelf.filterJson) {
return [];
}
try {
const groupRule = JSON.parse(magicShelf.filterJson) as GroupRule;
return books.filter(book => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule, books));
} catch {
console.warn('Invalid filterJson for MagicShelf');
return [];
}
}
}
@@ -0,0 +1,306 @@
import {Injectable, inject} from '@angular/core';
import {ActivatedRoute, ParamMap, Router} from '@angular/router';
import {SortDirection, SortOption} from '../../model/sort.model';
import {BookFilterMode, EntityViewPreference, EntityViewPreferences, SortCriterion} from '../../../settings/user-management/user.service';
import {EntityType} from './book-browser.component';
export const QUERY_PARAMS = {
VIEW: 'view',
SORT: 'sort',
DIRECTION: 'direction',
FILTER: 'filter',
FMODE: 'fmode',
SIDEBAR: 'sidebar',
FROM: 'from',
} as const;
export const VIEW_MODES = {
GRID: 'grid',
TABLE: 'table',
} as const;
export const SORT_DIRECTION = {
ASCENDING: 'asc',
DESCENDING: 'desc',
} as const;
export interface BookBrowserQueryState {
viewMode: 'grid' | 'table';
sortField: string;
sortDirection: SortDirection;
filters: Record<string, string[]>;
filterMode: BookFilterMode;
}
export interface QueryParseResult {
viewMode: string;
sortOption: SortOption;
sortCriteria: SortOption[];
filters: Record<string, string[]>;
filterMode: BookFilterMode;
viewModeFromToggle: boolean;
}
@Injectable({providedIn: 'root'})
export class BookBrowserQueryParamsService {
private router = inject(Router);
private activatedRoute = inject(ActivatedRoute);
parseQueryParams(
queryParamMap: ParamMap,
userPrefs: EntityViewPreferences | undefined,
entityType: EntityType | undefined,
entityId: number | undefined,
sortOptions: SortOption[],
defaultFilterMode: BookFilterMode
): QueryParseResult {
const viewParam = queryParamMap.get(QUERY_PARAMS.VIEW);
const sortParam = queryParamMap.get(QUERY_PARAMS.SORT);
const directionParam = queryParamMap.get(QUERY_PARAMS.DIRECTION);
const filterParams = queryParamMap.get(QUERY_PARAMS.FILTER);
const filterModeParam = queryParamMap.get(QUERY_PARAMS.FMODE);
const fromParam = queryParamMap.get(QUERY_PARAMS.FROM);
const filterMode = (filterModeParam || defaultFilterMode) as BookFilterMode;
// Parse filters
const filters = this.deserializeFilters(filterParams);
// Determine effective preferences
const globalPrefs = userPrefs?.global;
const currentEntityTypeStr = entityType?.toString().toUpperCase().replaceAll(' ', '_');
const override = userPrefs?.overrides?.find(o =>
o.entityType?.toUpperCase() === currentEntityTypeStr &&
o.entityId === entityId
);
const effectivePrefs: EntityViewPreference = override?.preferences ?? globalPrefs ?? {
sortKey: 'addedOn',
sortDir: 'ASC',
view: 'GRID',
coverSize: 1.0,
seriesCollapsed: false,
overlayBookType: true
};
// Parse sort criteria - supports both legacy and new multi-sort format
let sortCriteria: SortOption[];
if (sortParam) {
// Check if it's new multi-sort format (contains colons like "author:asc,title:desc")
if (sortParam.includes(':')) {
sortCriteria = this.deserializeSort(sortParam, sortOptions);
} else {
// Legacy format: separate sort and direction params
const effectiveSortDir = directionParam
? (directionParam.toLowerCase() === SORT_DIRECTION.DESCENDING ? SortDirection.DESCENDING : SortDirection.ASCENDING)
: SortDirection.ASCENDING;
const matchedSort = sortOptions.find(opt => opt.field === sortParam);
sortCriteria = matchedSort ? [{
label: matchedSort.label,
field: matchedSort.field,
direction: effectiveSortDir
}] : [];
}
} else {
// Use user preferences
if (effectivePrefs.sortCriteria && effectivePrefs.sortCriteria.length > 0) {
sortCriteria = effectivePrefs.sortCriteria.map((c: SortCriterion) => {
const matchedSort = sortOptions.find(opt => opt.field === c.field);
return {
label: matchedSort?.label ?? c.field,
field: c.field,
direction: c.direction === 'DESC' ? SortDirection.DESCENDING : SortDirection.ASCENDING
};
});
} else {
// Fall back to legacy single sort preference
const userSortKey = effectivePrefs.sortKey;
const userSortDir = effectivePrefs.sortDir?.toUpperCase() === 'DESC'
? SortDirection.DESCENDING
: SortDirection.ASCENDING;
const matchedSort = sortOptions.find(opt => opt.field === userSortKey);
sortCriteria = matchedSort ? [{
label: matchedSort.label,
field: matchedSort.field,
direction: userSortDir
}] : [];
}
}
// Ensure we have at least a default sort
if (sortCriteria.length === 0) {
sortCriteria = [{
label: 'Added On',
field: 'addedOn',
direction: SortDirection.DESCENDING
}];
}
// For backward compatibility, expose the first sort as sortOption
const sortOption = sortCriteria[0];
// Determine view mode
const viewModeFromToggle = fromParam === 'toggle';
const viewMode = viewModeFromToggle
? (viewParam === VIEW_MODES.TABLE || viewParam === VIEW_MODES.GRID
? viewParam
: VIEW_MODES.GRID)
: (effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID);
return {
viewMode,
sortOption,
sortCriteria,
filters,
filterMode,
viewModeFromToggle
};
}
updateViewMode(mode: 'grid' | 'table'): void {
this.router.navigate([], {
queryParams: {
[QUERY_PARAMS.VIEW]: mode,
[QUERY_PARAMS.FROM]: 'toggle'
},
queryParamsHandling: 'merge',
replaceUrl: true
});
}
updateSort(sortOption: SortOption): void {
this.updateMultiSort([sortOption]);
}
updateMultiSort(sortCriteria: SortOption[]): void {
const currentParams = this.activatedRoute.snapshot.queryParams;
const newParams = {
...currentParams,
[QUERY_PARAMS.SORT]: this.serializeSort(sortCriteria),
[QUERY_PARAMS.DIRECTION]: null // Remove legacy direction param
};
this.router.navigate([], {
queryParams: newParams,
replaceUrl: true
});
}
serializeSort(criteria: SortOption[]): string {
return criteria.map(c =>
`${c.field}:${c.direction === SortDirection.ASCENDING ? 'asc' : 'desc'}`
).join(',');
}
deserializeSort(sortParam: string, sortOptions: SortOption[]): SortOption[] {
const criteria: SortOption[] = [];
sortParam.split(',').forEach(part => {
const [field, dir] = part.split(':');
if (field) {
const matchedSort = sortOptions.find(opt => opt.field === field);
if (matchedSort) {
criteria.push({
label: matchedSort.label,
field: matchedSort.field,
direction: dir?.toLowerCase() === 'desc' ? SortDirection.DESCENDING : SortDirection.ASCENDING
});
}
}
});
return criteria;
}
updateFilters(filters: Record<string, string[]> | null): void {
const queryParam = filters && Object.keys(filters).length > 0
? this.serializeFilters(filters)
: null;
if (queryParam !== this.activatedRoute.snapshot.queryParamMap.get(QUERY_PARAMS.FILTER)) {
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {[QUERY_PARAMS.FILTER]: queryParam},
queryParamsHandling: 'merge',
replaceUrl: false
});
}
}
updateFilterMode(mode: BookFilterMode, currentFilters: Record<string, string[]>): void {
const params: Record<string, string | null> = {[QUERY_PARAMS.FMODE]: mode};
// Clear filters if switching from multiple selected to single mode
if (mode === 'single') {
const categories = Object.keys(currentFilters);
if (categories.length > 1 || (categories.length === 1 && currentFilters[categories[0]].length > 1)) {
params[QUERY_PARAMS.FILTER] = null;
}
}
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: params,
queryParamsHandling: 'merge',
replaceUrl: false
});
}
serializeFilters(filters: Record<string, string[]>): string {
return Object.entries(filters)
.map(([k, v]) => `${k}:${v.map(val => encodeURIComponent(val)).join('|')}`)
.join(',');
}
deserializeFilters(filterParam: string | null): Record<string, string[]> {
const parsedFilters: Record<string, string[]> = {};
if (!filterParam) return parsedFilters;
filterParam.split(',').forEach(pair => {
const [key, ...valueParts] = pair.split(':');
const value = valueParts.join(':');
if (key && value) {
parsedFilters[key] = value.split('|').map(v => decodeURIComponent(v.trim())).filter(Boolean);
}
});
return parsedFilters;
}
syncQueryParams(
viewMode: string,
filterMode: BookFilterMode,
filters: Record<string, string[]>
): void {
const queryParams: Record<string, string | number | null | undefined> = {
[QUERY_PARAMS.VIEW]: viewMode,
[QUERY_PARAMS.FMODE]: filterMode,
};
if (Object.keys(filters).length > 0) {
queryParams[QUERY_PARAMS.FILTER] = this.serializeFilters(filters);
}
const currentParams = this.activatedRoute.snapshot.queryParams;
const changed = Object.keys(queryParams).some(k => (queryParams[k] ?? undefined) !== (currentParams[k] ?? undefined));
if (changed) {
const mergedParams = {...currentParams, ...queryParams};
this.router.navigate([], {
queryParams: mergedParams,
replaceUrl: true
});
}
}
shouldForceExpandSeries(queryParamMap: ParamMap): boolean {
const filterParam = queryParamMap.get(QUERY_PARAMS.FILTER);
return (
!!filterParam &&
typeof filterParam === 'string' &&
filterParam.split(',').some(pair => pair.trim().startsWith('series:'))
);
}
}
@@ -0,0 +1,25 @@
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class BookBrowserScrollService {
private scrollPositions = new Map<string, number>();
savePosition(key: string, position: number): void {
this.scrollPositions.set(key, position);
}
getPosition(key: string): number | undefined {
return this.scrollPositions.get(key);
}
clearPosition(key: string): void {
this.scrollPositions.delete(key);
}
createKey(path: string, params: Record<string, string>): string {
const paramValues = Object.values(params).join('-');
return paramValues ? `${path}:${paramValues}` : path;
}
}
@@ -0,0 +1,467 @@
<ng-container *transloco="let t; prefix: 'book.browser'">
<div class="book-browser-container">
<div class="book-browser-main">
<div class="book-browser-header">
<div class="entity-info-wrapper">
@if (entityType(); as entityType) {
<div class="entity-info">
<p class="entity-title">
@if (entityType === EntityType.ALL_BOOKS) {
@if (currentFilterLabel && rawFilterParamFromUrl) {
{{ currentFilterLabel }}
} @else if (isFilterActive || hasSearchTerm) {
{{ computedFilterLabel }}
} @else {
{{ t('labels.allBooks') }}
}
} @else if (entityType === EntityType.UNSHELVED) {
{{ (isFilterActive || hasSearchTerm) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
} @else {
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive || hasSearchTerm) ? ' ' + t('labels.filteredSuffix') : '' }}
}
</p>
@if (seriesCollapseFilter.seriesCollapsed() && books(); as books) {
<p class="series-collapsed-info">
{{ t('labels.seriesCollapsedInfo', { count: books.length, itemWord: books.length === 1 ? t('labels.item') : t('labels.items') }) }}
</p>
}
</div>
@if (userService.currentUser(); as currentUser) {
@if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED &&
(currentUser.permissions.admin || currentUser.permissions.canManageLibrary)) {
<div class="entity-menu-wrapper">
<p-button
icon="pi pi-ellipsis-v"
[rounded]="true"
[text]="true"
severity="info"
(click)="entitymenu.toggle($event)">
</p-button>
<p-menu #entitymenu [model]="entityOptions()" [popup]="true" appendTo="body"></p-menu>
</div>
}
}
}
</div>
<div class="toolbar-actions">
<div class="toolbar-icons">
@if (isFilterActive) {
<a class="topbar-items topbar-item" (click)="clearFilter()">
<i
class="pi pi-filter-slash filter-clear-icon"
[pTooltip]="t('tooltip.clearFilters')"
tooltipPosition="top">
</i>
</a>
}
@if (currentViewMode === 'table') {
<div>
<a class="topbar-items topbar-item" (click)="columnPopover.toggle($event)">
<i
class="pi pi-eye"
[pTooltip]="t('tooltip.visibleColumns')"
tooltipPosition="top">
</i>
</a>
<p-popover #columnPopover [dismissable]="true" appendTo="body">
<div class="column-popover-content">
<p-multiSelect
optionLabel="header"
[options]="columnPreferenceService.allColumns"
[(ngModel)]="visibleColumns"
(ngModelChange)="onVisibleColumnsChange($event)"
display="chip"
[placeholder]="t('placeholder.selectColumns')"
[style]="{ width: '100%' }"
[filter]="true"
[showClear]="true"
></p-multiSelect>
</div>
<div class="column-popover-footer">
<p>{{ t('labels.setAsDefault') }}</p>
<p-button
[label]="t('labels.save')"
outlined
size="small"
(click)="columnPreferenceService.saveVisibleColumns(visibleColumns)"></p-button>
</div>
</p-popover>
</div>
}
<div>
<a
class="topbar-items topbar-item"
(click)="seriesCollapseOverlay.toggle($event)"
[pTooltip]="t('tooltip.displaySettings')"
tooltipPosition="top">
<i class="pi pi-cog"></i>
</a>
<p-popover #seriesCollapseOverlay [dismissable]="true" appendTo="body">
<div class="display-settings-popover">
<div class="display-settings-section">
<div class="display-settings-checkbox-row">
<p-checkbox
inputId="collapse-series-checkbox"
[binary]="true"
[ngModel]="seriesCollapseFilter.seriesCollapsed()"
(onChange)="onSeriesCollapseCheckboxChange($event.checked)">
</p-checkbox>
<label for="collapse-series-checkbox" class="display-settings-label">{{ t('labels.collapseSeries') }}</label>
</div>
</div>
@if (isMobile) {
<div class="display-settings-section">
<label class="display-settings-label">{{ t('labels.gridColumns') }}</label>
<div class="column-options">
<button
type="button"
class="column-option-btn"
[class.active]="mobileColumnCount === 2"
(click)="setMobileColumns(2)">2</button>
<button
type="button"
class="column-option-btn"
[class.active]="mobileColumnCount === 3"
(click)="setMobileColumns(3)">3</button>
<button
type="button"
class="column-option-btn"
[class.active]="mobileColumnCount === 4"
(click)="setMobileColumns(4)">4</button>
</div>
</div>
} @else {
<div class="display-settings-section">
<label class="display-settings-label">{{ t('labels.gridItemSize') }}</label>
<p-slider
[ngModel]="coverScalePreferenceService.scaleFactor()"
(ngModelChange)="coverScalePreferenceService.setScale($event)"
[min]="0.5"
[max]="1.5"
[step]="0.01"
[style]="{ width: '100%' }">
</p-slider>
<div class="scale-value-display">
{{ coverScalePreferenceService.scaleFactor().toFixed(2) }}x
</div>
</div>
}
<div class="display-settings-section">
<div class="display-settings-checkbox-row">
<p-checkbox
inputId="show-book-type-pill-checkbox"
[binary]="true"
[ngModel]="bookCardOverlayPreferenceService.showBookTypePill()"
(onChange)="bookCardOverlayPreferenceService.setShowBookTypePill($event.checked)">
</p-checkbox>
<label for="show-book-type-pill-checkbox" class="display-settings-label">{{ t('labels.bookTypeOverlay') }}</label>
</div>
</div>
</div>
</p-popover>
</div>
<div class="sort-button-wrapper">
<a class="topbar-items topbar-item" (click)="sortPopover.toggle($event)">
<i
class="pi pi-sort"
[pTooltip]="t('tooltip.selectSorting')"
tooltipPosition="top">
</i>
@if (sortCriteriaCount > 1) {
<p-badge [value]="sortCriteriaCount.toString()" class="sort-badge"/>
}
</a>
<p-popover #sortPopover [dismissable]="true" appendTo="body">
<app-multi-sort-popover
[sortCriteria]="this.bookSorter.selectedSortCriteria"
[availableSortOptions]="visibleSortOptions"
[showSaveButton]="canSaveSort"
(criteriaChange)="onSortCriteriaChange($event)"
(saveSortConfig)="onSaveSortConfig($event)">
</app-multi-sort-popover>
</p-popover>
</div>
<a class="topbar-items topbar-item" (click)="toggleTableGrid()">
<i
[ngClass]="viewIcon"
[pTooltip]="t('tooltip.toggleView')"
tooltipPosition="top">
</i>
</a>
</div>
<!-- MOBILE SEARCH (only visible below md) -->
<div class="mobile-search-wrapper">
<button
type="button"
class="topbar-items topbar-item"
(click)="searchDropdown.toggle($event)"
[pTooltip]="t('tooltip.search')"
tooltipPosition="top"
>
<i class="pi pi-search"></i>
</button>
<p-popover #searchDropdown [dismissable]="true" appendTo="body" [style]="{ width: '24rem' }">
<div class="search-popover-content">
<input
type="text"
pInputText
[placeholder]="t('placeholder.search')"
[(ngModel)]="bookTitle"
(ngModelChange)="onSearchTermChange($event)"
class="search-input-full"
/>
<p-button
icon="pi pi-times"
[text]="true"
size="small"
[rounded]="true"
class="search-clear-btn"
(click)="clearSearch(); searchDropdown.hide()"
></p-button>
</div>
</p-popover>
</div>
<div class="desktop-search-wrapper">
<i class="pi pi-search search-icon"></i>
<input
type="text"
pInputText
[placeholder]="t('placeholder.search')"
[(ngModel)]="bookTitle"
(ngModelChange)="onSearchTermChange($event)"
class="search-input"
/>
@if (bookTitle) {
<p-button
icon="pi pi-times"
[text]="true"
size="small"
[rounded]="true"
class="search-clear-btn"
(click)="clearSearch()"
></p-button>
}
</div>
<a class="topbar-items topbar-item" (click)="toggleSidebar()">
<i
[ngClass]="showFilter() ? 'pi pi-angle-double-right' : 'pi pi-angle-double-left'"
[pTooltip]="t('tooltip.toggleSidebar')"
tooltipPosition="top">
</i>
</a>
</div>
</div>
@if (books(); as books) {
<div>
@if (isBooksLoading()) {
<div>
<p-progressSpinner></p-progressSpinner>
</div>
}
<div class="book-state-wrapper">
@if (booksError()) {
<div class="no-books-container">
<p class="no-books-text">
{{ entityType() === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
</p>
</div>
} @else if (!isBooksLoading() && books.length === 0) {
<div class="no-books-container">
<p class="no-books-text">
{{ t('labels.noBooks') }}
</p>
</div>
}
@if (currentViewMode === 'table' && books.length > 0) {
<app-book-table
[books]="books"
[preselectedBookIds]="selectedBooks()"
(selectedBooksChange)="onSelectedBooksChange($event)"
[sortOption]="this.bookSorter.selectedSort!"
[visibleColumns]="visibleColumns"
></app-book-table>
}
@if (currentViewMode === 'grid') {
<virtual-scroller class="virtual-scroller" #scroll [items]="books">
<div
class="grid"
#container
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
@for (book of scroll.viewPortItems; let i = $index; track book.id) {
<div
class="virtual-scroller-item"
[ngStyle]="{width: currentCardSize.width + 'px', height: getCardHeight(book) + 'px'}">
<app-book-card
[index]="books.indexOf(book)"
[book]="book"
[isCheckboxEnabled]="true"
[seriesViewEnabled]="seriesViewEnabled"
[onBookSelect]="handleBookSelect.bind(this)"
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="selectedBooks().has(book.id)"
[useSquareCovers]="isAudiobookOnlyLibrary"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
}
</div>
</virtual-scroller>
}
@if (userService.currentUser(); as currentUser) {
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
<div class="footer-content">
<div class="footer-left">
<div class="selected-count-badge">
<i class="pi pi-check-circle"></i>
<span class="selected-count">{{ selectedCount() }}</span>
<span class="selected-label">{{ t('labels.selected') }}</span>
</div>
</div>
<div class="footer-center">
@if (entityType(); as entityType) {
<div class="action-buttons-group">
@if (hasMetadataMenuItems) {
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
<p-button
(click)="menu.toggle($event)"
[pTooltip]="t('tooltip.metadataActions')"
tooltipPosition="top"
outlined="true"
severity="info"
icon="pi pi-database">
</p-button>
}
<p-button
icon="pi pi-bookmark-fill"
outlined="true"
severity="info"
(onClick)="openShelfAssigner()"
[pTooltip]="t('tooltip.assignToShelf')"
tooltipPosition="top">
</p-button>
@if (entityType === EntityType.SHELF) {
<p-button
icon="pi pi-bookmark"
outlined="true"
severity="info"
(click)="unshelfBooks()"
[pTooltip]="t('tooltip.removeFromShelf')"
tooltipPosition="top">
</p-button>
}
@if (currentUser.permissions.canBulkLockUnlockMetadata) {
<p-button
outlined="true"
icon="pi pi-lock"
severity="info"
(click)="lockUnlockMetadata()"
[pTooltip]="t('tooltip.lockUnlockMetadata')"
tooltipPosition="top">
</p-button>
}
@if (currentUser.permissions.canMoveOrganizeFiles && appSettingsService.appSettings()?.diskType === 'LOCAL') {
<p-button
outlined="true"
icon="pi pi-arrows-h"
severity="info"
(click)="moveFiles()"
[pTooltip]="t('tooltip.organizeFiles')"
tooltipPosition="top">
</p-button>
}
@if (currentUser.permissions.canManageLibrary || currentUser.permissions.admin) {
<p-button
outlined="true"
icon="pi pi-link"
severity="info"
(click)="attachFilesToBook()"
[disabled]="!canAttachFiles()"
[pTooltip]="t('tooltip.attachToBook')"
tooltipPosition="top">
</p-button>
}
@if (hasMoreActionsItems) {
<div class="more-actions-wrapper">
<p-button
(click)="menu.toggle($event)"
[pTooltip]="t('tooltip.moreActions')"
tooltipPosition="top"
outlined="true"
severity="info"
icon="pi pi-ellipsis-v">
</p-button>
<p-tieredMenu #menu [model]="moreActionsMenuItems" [popup]="true" appendTo="body" styleClass="footer-menu"/>
</div>
}
</div>
}
<p-divider layout="vertical"></p-divider>
<div class="action-buttons-group">
<p-button
outlined="true"
icon="pi pi-check-square"
severity="success"
(click)="selectAllBooks()"
[pTooltip]="t('tooltip.selectAll')"
tooltipPosition="top">
</p-button>
<p-button
outlined="true"
icon="pi pi-times"
severity="warn"
(click)="deselectAllBooks()"
[pTooltip]="t('tooltip.deselectAll')"
tooltipPosition="top">
</p-button>
</div>
@if (currentUser?.permissions?.admin || currentUser?.permissions?.canDeleteBook) {
<p-divider layout="vertical"></p-divider>
<p-button
outlined="true"
icon="pi pi-trash"
severity="danger"
(click)="confirmDeleteBooks()"
[pTooltip]="t('tooltip.deleteSelected')"
tooltipPosition="top">
</p-button>
}
</div>
<div class="footer-right"></div>
</div>
</div>
}
</div>
</div>
}
</div>
@if (showFilter()) {
<div
class="mobile-filter-mask"
(click)="toggleSidebar()">
</div>
<app-book-filter
[showFilter]="showFilter()"
class="filter-overlay-container"
[ngClass]="{ 'active': showFilter() }"
[entity]="entity()"
[entityType]="entityType()"
[resetFilter$]="resetFilterSubject"
(filterSelected)="onFilterSelected($event)"
(filterModeChanged)="onFilterModeChanged($event)">
</app-book-filter>
}
</div>
</ng-container>
@@ -0,0 +1,536 @@
// Layout containers
.book-browser-container {
position: relative;
display: flex;
flex-direction: row;
}
.book-browser-main {
display: flex;
flex-direction: column;
width: 100%;
}
// Header bar
.book-browser-header {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
gap: 0.25rem;
padding: 0.35rem 0.35rem;
border-radius: 0.75rem 0.75rem 0 0;
margin-bottom: 0.5rem;
background-color: var(--card-background);
border: 1px solid var(--p-content-border-color);
@media (min-width: 768px) {
gap: 1rem;
padding: 0.5rem 1rem;
margin-bottom: 1rem;
}
}
// Entity info section
.entity-info-wrapper {
display: flex;
align-items: center;
min-width: 0;
flex-shrink: 1;
overflow: hidden;
}
.entity-info {
display: flex;
flex-direction: column;
gap: 0.125rem;
min-width: 0;
overflow: hidden;
@media (max-width: 767px) {
gap: 0;
}
}
.entity-title {
font-size: 1.25rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin: 0;
@media (max-width: 767px) {
font-size: 1rem;
padding-left: 0.25rem;
}
}
.series-collapsed-info {
font-size: 0.875rem;
color: #6b7280;
margin: 0;
@media (max-width: 767px) {
display: none;
margin: 0;
padding: 0;
height: 0;
}
}
.entity-menu-wrapper {
margin-left: 0.5rem;
flex-shrink: 0;
}
// Toolbar actions
.toolbar-actions {
display: flex;
flex-wrap: nowrap;
align-items: center;
gap: 0.25rem;
flex-shrink: 0;
@media (min-width: 768px) {
gap: 1rem;
}
}
.toolbar-icons {
display: flex;
flex-wrap: nowrap;
align-items: center;
gap: 0.25rem;
@media (min-width: 768px) {
gap: 1.5rem;
}
}
// Icon with orange color for filter
.filter-clear-icon {
color: orange;
}
// Popover content containers
.column-popover-content {
width: 200px;
}
.column-popover-footer {
display: flex;
align-items: center;
gap: 0.5rem;
padding-top: 1rem;
padding-left: 0.25rem;
}
.display-settings-popover {
width: 220px;
padding: 0.5rem;
display: flex;
flex-direction: column;
gap: 1rem;
font-size: 0.875rem;
}
.display-settings-section {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.display-settings-checkbox-row {
display: flex;
align-items: center;
gap: 0.5rem;
}
.display-settings-label {
font-weight: 500;
}
.scale-value-display {
text-align: center;
}
.column-options {
display: flex;
gap: 0.5rem;
}
.column-option-btn {
flex: 1;
padding: 0.25rem 0.5rem;
border: 1px solid var(--p-content-border-color);
border-radius: 6px;
background-color: var(--card-background);
color: var(--text-color);
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.15s ease;
&:hover {
border-color: var(--primary-color);
}
&.active {
background-color: var(--primary-color);
border-color: var(--primary-color);
color: var(--primary-color-text);
}
}
// Sort button wrapper
.sort-button-wrapper {
position: relative;
.sort-badge {
position: absolute;
top: -6px;
right: -6px;
}
}
// Sort menu item (kept for backward compat)
.sort-menu-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 1rem;
cursor: pointer;
}
// Search section
.mobile-search-wrapper {
position: relative;
@media (min-width: 768px) {
display: none;
}
}
.desktop-search-wrapper {
display: none;
position: relative;
@media (min-width: 768px) {
display: block;
}
}
.search-popover-content {
position: relative;
width: 100%;
}
.search-input-full {
width: 100%;
}
.search-clear-btn {
position: absolute;
right: 0.5rem;
top: 50%;
transform: translateY(-50%);
}
// Footer bar
.book-browser-footer {
position: absolute;
bottom: 0;
left: 10%;
right: 10%;
display: flex;
align-items: center;
overflow: hidden;
padding: 1rem 0.5rem 0.5rem;
z-index: 1;
border-radius: 10px 10px 0 0;
border: 1px solid rgba(255, 255, 255, 0.5);
border-width: 1px 1px 0 1px;
background-color: var(--card-background);
transition: transform 0.15s ease-out, opacity 0.15s ease-out;
transform: translateY(0);
opacity: 1;
&.footer-hidden {
transform: translateY(100%);
opacity: 0;
pointer-events: none;
}
@media (max-width: 768px) {
left: 0;
right: 0;
}
}
.footer-content {
display: flex;
align-items: center;
min-width: 0;
flex: 1;
}
.footer-left {
display: flex;
align-items: center;
padding-left: 0.5rem;
flex-shrink: 0;
width: 120px;
@media (max-width: 768px) {
width: auto;
}
}
.footer-center {
display: flex;
justify-content: center;
flex: 1;
min-width: 0;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
mask-image: linear-gradient(to right, transparent 0, black 12px, black calc(100% - 32px), transparent 100%);
-webkit-mask-image: linear-gradient(to right, transparent 0, black 12px, black calc(100% - 32px), transparent 100%);
padding: 0 16px;
&::-webkit-scrollbar {
display: none;
}
@media (max-width: 768px) {
justify-content: flex-start;
}
}
.footer-right {
flex-shrink: 0;
width: 120px;
@media (max-width: 768px) {
display: none;
}
}
.selected-count-badge {
display: inline-flex;
align-items: center;
padding: 0.5rem 1rem;
font-size: 0.9rem;
color: #e4e4e7;
i {
font-size: 1rem;
margin-right: 0.5rem;
}
@media (max-width: 768px) {
padding: 0.4rem 0.8rem;
font-size: 0.85rem;
i {
font-size: 0.9rem;
}
}
}
.selected-count {
font-weight: 700;
font-size: 1rem;
color: var(--primary-color);
}
.selected-label {
margin-left: 0.25rem;
}
.action-buttons-group {
display: flex;
flex-shrink: 0;
gap: 0.5rem;
@media (min-width: 768px) {
gap: 1.5rem;
}
}
.more-actions-wrapper {
display: flex;
justify-content: center;
}
// Virtual scroller and grid
.virtual-scroller {
width: 100%;
height: calc(100dvh - 10.9rem);
padding: 1rem;
box-sizing: border-box;
overflow-y: auto;
@media (max-width: 768px) {
height: calc(100dvh - 9rem);
}
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(1px, 1fr));
gap: 1.3rem;
align-items: start;
width: 100%;
// Mobile: fixed 2 or 3 columns based on phone width
@media (max-width: 767px) {
gap: 0.5rem;
padding: 0 0.5rem;
}
}
.virtual-scroller-item {
position: relative;
transition: width 0.2s ease, height 0.2s ease;
}
// No books state
.no-books-container {
padding-top: 3rem;
display: flex;
justify-content: center;
align-items: center;
}
.no-books-text {
font-size: 1rem;
font-weight: 500;
color: var(--text-color);
background: var(--card-background);
padding: 0.75rem 1rem;
border-radius: 0.5rem;
}
// Topbar items (icon buttons)
.topbar-item {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
border: 1px solid var(--border-color);
width: 2.5rem;
height: 2.5rem;
transition: outline-color 0.2s, border-color 0.2s;
border-radius: 6px;
margin: 0;
padding: 0;
outline-color: transparent;
background-color: var(--card-background);
cursor: pointer;
@media (max-width: 767px) {
width: 2rem;
height: 2rem;
}
&:hover {
border-color: var(--primary-color);
}
i, span {
color: var(--primary-color);
font-size: 1.25rem;
font-weight: 100;
@media (max-width: 767px) {
font-size: 1rem;
}
}
}
// Search input styling
.search-icon {
position: absolute;
top: 50%;
left: 10px;
transform: translateY(-50%);
color: var(--text-secondary-color);
font-size: 1rem;
pointer-events: none;
}
.search-input {
min-width: 22rem;
padding-left: 30px;
height: 2.5rem;
line-height: 2.5rem;
font-size: 1rem;
box-sizing: border-box;
@media (max-width: 767px) {
min-width: 0;
}
}
// Filter overlay (mobile sidebar)
.mobile-filter-mask {
@media (max-width: 991px) {
position: absolute;
top: 0;
left: 0;
z-index: 998;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
}
.filter-overlay-container {
flex-shrink: 0;
z-index: 50;
@media (max-width: 991px) {
width: var(--sidebar-width, 225px);
position: fixed;
top: 3.85rem;
right: 0;
bottom: 0;
height: calc(100% - 3.85rem);
background-color: var(--card-background);
box-shadow: -2px 0 10px rgba(0, 0, 0, 0.15);
transform: translateX(100%);
transition: transform 0.3s ease;
z-index: 1001;
&.active {
transform: translateX(0);
margin-left: 0;
}
}
@media (min-width: 992px) {
position: relative;
overflow: hidden;
flex-shrink: 0;
&:not(.active) {
width: 0 !important;
opacity: 0;
pointer-events: none;
margin-left: 0;
}
&.active {
width: var(--sidebar-width, 225px);
opacity: 1;
pointer-events: auto;
margin-left: 1rem;
}
}
}
// Book state container
.book-state-wrapper {
position: relative;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,115 @@
import {effect, inject, Injectable, signal} from '@angular/core';
import {UserService} from '../../../settings/user-management/user.service';
@Injectable({
providedIn: 'root'
})
export class BookCardOverlayPreferenceService {
private static readonly PERSIST_DELAY_MS = 500;
private readonly userService = inject(UserService);
private readonly _showBookTypePill = signal(true);
readonly showBookTypePill = this._showBookTypePill.asReadonly();
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
private persistTimeout: ReturnType<typeof setTimeout> | null = null;
constructor() {
effect(() => {
const user = this.userService.currentUser();
if (user) {
this.loadPreferencesFromUser();
}
});
}
setShowBookTypePill(show: boolean): void {
this._showBookTypePill.set(show);
this.schedulePersist(show);
}
private loadPreferencesFromUser(): void {
const user = this.userService.getCurrentUser();
const prefs = user?.userSettings?.entityViewPreferences;
let show = true;
if (prefs) {
const globalAny = prefs.global as any;
show = prefs.global?.overlayBookType ?? globalAny?.showBookTypePill ?? true;
if (this.currentContext) {
const override = prefs.overrides?.find(o =>
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
);
if (override) {
const prefAny = override.preferences as any;
if (override.preferences.overlayBookType !== undefined) {
show = override.preferences.overlayBookType;
} else if (prefAny?.showBookTypePill !== undefined) {
show = prefAny.showBookTypePill;
}
}
}
}
if (this._showBookTypePill() !== show) {
this._showBookTypePill.set(show);
}
}
private schedulePersist(show: boolean): void {
if (this.persistTimeout) {
clearTimeout(this.persistTimeout);
}
this.persistTimeout = setTimeout(() => {
this.persistPreference(show);
}, BookCardOverlayPreferenceService.PERSIST_DELAY_MS);
}
private persistPreference(show: boolean): void {
const user = this.userService.getCurrentUser();
if (!user) return;
const prefs = structuredClone(user.userSettings.entityViewPreferences ?? {
global: {
sortKey: 'addedOn',
sortDir: 'DESC',
view: 'GRID',
coverSize: 1.0,
seriesCollapsed: false,
overlayBookType: true
},
overrides: []
});
if (!prefs.overrides) {
prefs.overrides = [];
}
if (this.currentContext) {
let override = prefs.overrides.find(o =>
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
);
if (!override) {
override = {
entityType: this.currentContext.type,
entityId: this.currentContext.id,
preferences: {
...prefs.global,
overlayBookType: show
}
};
prefs.overrides.push(override);
} else {
override.preferences.overlayBookType = show;
}
} else {
prefs.global.overlayBookType = show;
}
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
}
}
@@ -0,0 +1,115 @@
<div class="book-card"
[class.selected]="isSelected"
(click)="onCardClick($event)">
<div class="cover-container" [ngClass]="{ 'center-info-btn': _isSeriesViewActive || !hasDigitalFile(), 'loaded': isImageLoaded, 'audiobook-cover': _isAudiobook, 'square-library-cover': useSquareCovers }">
<img
[src]="coverImageUrl"
class="book-cover"
[class.loaded]="isImageLoaded"
[class.square-cover]="_isAudiobook || useSquareCovers"
[alt]="('book.card.alt.cover' | transloco: { title: displayTitle })"
loading="lazy"
decoding="async"
(load)="onImageLoad()"/>
<div class="top-left-overlay-stack">
@if ((overlayPreferenceService?.showBookTypePill() ?? true) && getDisplayFormat(); as displayFormat) {
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + displayFormat.toLowerCase()">
{{ displayFormat }}
</div>
}
@if (!book.seriesCount && book.metadata?.seriesNumber != null) {
<div class="series-number-overlay">
#{{ book.metadata?.seriesNumber }}
</div>
}
@if (book.seriesCount && book.seriesCount >= 1) {
<div class="series-items-count-overlay">
<i class="pi pi-book series-items-count-icon"></i>{{ book.seriesCount }}
</div>
}
</div>
@if (_isSeriesViewActive) {
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openSeriesInfo()" [ariaLabel]="'book.card.alt.viewSeriesInfo' | transloco"></p-button>
} @else {
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)" [ariaLabel]="'book.card.alt.viewDetails' | transloco">
</p-button>
}
@if (!_isSeriesViewActive && hasDigitalFile()) {
<a [routerLink]="urlHelper.getBookPrimaryReadingUrl(book)" (click)="readBook(book)"><p-button [rounded]="true" [icon]="readButtonIcon" class="read-btn" (click)="readBook(book)"
[pTooltip]="_isContinueReading ? ('book.card.alt.continueReading' | transloco) : ''"
tooltipPosition="bottom"
[ariaLabel]="_isContinueReading ? ('book.card.alt.continueReading' | transloco) : (_isAudiobook ? ('book.card.alt.playAudiobook' | transloco) : ('book.card.alt.readBook' | transloco))"></p-button></a>
}
@if (isCheckboxEnabled) {
<p-checkbox
[binary]="true"
class="select-checkbox"
(click)="captureMouseEvent($event)"
[ngModel]="isSelected"
(onChange)="toggleSelection($event)">
</p-checkbox>
}
@if (hasProgress) {
<div class="cover-progress-bar-container" [pTooltip]="progressTooltip" tooltipPosition="top">
@if (_progressPercentage !== null) {
<p-progressBar
[value]="_progressPercentage"
[showValue]="false"
class="cover-progress-bar"
[ngClass]="{ 'progress-complete': _progressPercentage === 100, 'progress-incomplete': _progressPercentage < 100 }">
</p-progressBar>
}
@if (_koProgressPercentage !== null) {
<p-progressBar
[value]="_koProgressPercentage"
[showValue]="false"
class="cover-progress-bar"
[ngClass]="_koProgressPercentage === 100 ? 'progress-complete-ko' : 'progress-incomplete-ko'">
</p-progressBar>
}
@if (_koboProgressPercentage !== null) {
<p-progressBar
[value]="_koboProgressPercentage"
[showValue]="false"
class="cover-progress-bar"
[ngClass]="_koboProgressPercentage === 100 ? 'progress-complete-kobo' : 'progress-incomplete-kobo'">
</p-progressBar>
}
</div>
}
</div>
@if (!bottomBarHidden) {
<div class="book-title-container">
<div class="read-status-indicator"
[ngClass]="_readStatusClass"
[pTooltip]="readStatusTooltip"
tooltipPosition="bottom"
(click)="toggleReadStatusMenu($event, readStatusMenu)"
[attr.aria-label]="'book.card.alt.readStatusMenu' | transloco">
<i [class]="_readStatusIcon" style="font-size: 0.9rem"></i>
</div>
<p-tieredmenu #readStatusMenu [model]="readStatusMenuItems" [popup]="true" appendTo="body"></p-tieredmenu>
<h4 class="book-title"
tooltipPosition="bottom"
[pTooltip]="titleTooltip">
{{ displayTitle }}
</h4>
<p-tieredmenu #menu [model]="items" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()"></p-tieredmenu>
<p-button
class="custom-button-padding"
size="small"
[text]="true"
(click)="onMenuToggle($event, menu)"
icon="pi pi-ellipsis-v"
[ariaLabel]="'book.card.alt.bookMenu' | transloco">
</p-button>
</div>
}
</div>
@@ -0,0 +1,464 @@
.book-card {
background-color: var(--card-background);
border-radius: 8px;
position: relative;
overflow: hidden;
height: 100%;
display: flex;
flex-direction: column;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
transition: box-shadow 0.25s ease, transform 0.25s ease;
&:hover {
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
transform: translateY(-2px);
}
&.selected {
border: 2px solid var(--primary-color);
}
}
@keyframes shimmer {
0% {
background-position: -200% 0;
}
100% {
background-position: 200% 0;
}
}
.cover-container {
position: relative;
width: 100%;
aspect-ratio: 5/7;
background-color: var(--card-background);
border-radius: 8px 8px 0 0;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.cover-container:not(.loaded) {
background: linear-gradient(
90deg,
var(--surface-ground) 25%,
var(--surface-hover, rgba(255, 255, 255, 0.08)) 50%,
var(--surface-ground) 75%
);
background-size: 200% 100%;
animation: shimmer 1.5s ease-in-out infinite;
}
.cover-container.audiobook-cover {
aspect-ratio: 5/7;
background-color: var(--surface-ground);
}
.cover-container.square-library-cover {
aspect-ratio: 1/1;
background-color: var(--surface-ground);
}
.book-cover {
width: 100%;
height: 100%;
border-radius: 8px 8px 0 0;
opacity: 0;
transition: opacity 0.2s ease-in, transform 0.35s ease;
}
.book-cover.loaded {
opacity: 1;
}
.book-card:hover .book-cover.loaded {
transform: scale(1.04);
}
.book-cover.square-cover {
object-fit: contain;
}
.cover-container::after {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: radial-gradient(circle, rgba(0, 0, 0, 0) 25%, rgba(0, 0, 0, 0.6) 100%);
opacity: 0;
transition: opacity 0.15s ease-in-out;
pointer-events: none;
}
.cover-container:hover::after {
opacity: 1;
}
.book-title-container {
display: flex;
align-items: center;
justify-content: space-between;
}
.book-title {
flex-grow: 1;
font-size: 0.9rem;
color: var(--text-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
margin: 0;
padding-left: 0.5rem;
@media (max-width: 767px) {
font-size: 0.75rem;
padding-left: 0.25rem;
}
}
.info-btn,
.read-btn {
position: absolute;
left: 50%;
transform: translateX(-50%);
opacity: 0;
visibility: hidden;
transition: opacity 0.15s ease, visibility 0.15s ease;
z-index: 2;
will-change: opacity, visibility;
::ng-deep .p-button {
box-shadow:
0 2px 8px rgba(0, 0, 0, 0.4),
inset 0 1px 0 rgba(255, 255, 255, 0.15);
border: 1px solid rgba(255, 255, 255, 0.1);
transition: transform 0.15s ease, box-shadow 0.15s ease;
&:hover {
transform: scale(1.08);
box-shadow:
0 4px 12px rgba(0, 0, 0, 0.5),
inset 0 1px 0 rgba(255, 255, 255, 0.2);
}
@media (max-width: 767px) {
width: clamp(1.5rem, 8vw, 2.5rem);
height: clamp(1.5rem, 8vw, 2.5rem);
padding: 0;
.pi {
font-size: clamp(0.65rem, 3.5vw, 1rem);
}
}
}
}
.info-btn {
top: 21%;
}
.read-btn {
bottom: 21%;
}
.cover-container:hover .info-btn,
.cover-container:hover .read-btn {
opacity: 1;
visibility: visible;
}
.cover-container.center-info-btn .info-btn {
top: 50%;
transform: translate(-50%, -50%);
}
.select-checkbox {
position: absolute;
top: 8px;
right: 8px;
opacity: 0;
visibility: hidden;
transition: opacity 0.15s ease, visibility 0.15s ease;
z-index: 2;
will-change: opacity, visibility;
@media (max-width: 767px) {
top: 4px;
right: 4px;
}
}
.select-checkbox .p-checkbox {
vertical-align: top;
}
.cover-container:hover .select-checkbox,
.book-card.selected .select-checkbox {
opacity: 1;
visibility: visible;
}
.cover-progress-bar-container {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 7.5px;
z-index: 2;
display: flex;
flex-direction: column;
justify-content: flex-end;
}
.cover-progress-bar {
left: 0;
right: 0;
height: 2.5px;
z-index: 1;
opacity: 0.9;
}
.series-number-overlay {
position: absolute;
top: 8px;
left: 8px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
font-size: 0.75rem;
padding: 1px 3px;
border-radius: 3px;
z-index: 3;
}
.series-items-count-overlay {
position: absolute;
background-color: var(--primary-color);
color: var(--primary-text-color-dark);
font-size: 0.7rem;
padding: 0 5px;
border-radius: 6px;
z-index: 3;
white-space: nowrap;
user-select: none;
font-weight: 700;
text-align: center;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
border: 1px solid rgba(255, 255, 255, 0.2);
display: flex;
align-items: center;
gap: 2px;
}
.series-items-count-icon {
font-size: 0.6rem;
margin-right: 2px;
}
.book-type-pill-overlay {
position: absolute;
background: var(--primary-color, #6366f1);
color: var(--primary-text-color-dark, #fff);
font-size: 0.675rem;
font-weight: 700;
padding: 1px 6px;
border-radius: 6px;
z-index: 3;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
letter-spacing: 0.03em;
user-select: none;
pointer-events: none;
text-transform: uppercase;
transition: background 0.2s;
}
.top-left-overlay-stack {
position: absolute;
top: 7px;
left: 7px;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
z-index: 4;
@media (max-width: 767px) {
top: 4px;
left: 4px;
gap: 2px;
}
}
.book-type-pill-overlay,
.series-number-overlay,
.series-items-count-overlay {
position: static;
margin: 0;
@media (max-width: 767px) {
font-size: 0.6rem;
padding: 1px 4px;
}
}
.book-type-epub {
background: var(--book-type-epub-color);
color: #fff;
}
.book-type-pdf {
background: var(--book-type-pdf-color);
color: #fff;
}
.book-type-cbx {
background: var(--book-type-cbx-color);
color: #fff;
}
.book-type-mobi {
background: var(--book-type-mobi-color);
color: #fff;
}
.book-type-azw3 {
background: var(--book-type-azw3-color);
color: #fff;
}
.book-type-fb2 {
background: var(--book-type-fb2-color);
color: #fff;
}
.book-type-audiobook {
background: var(--book-type-audiobook-color);
color: #fff;
}
.book-type-m4b {
background: var(--book-type-m4b-color);
color: #fff;
}
.book-type-mp3 {
background: var(--book-type-mp3-color);
color: #fff;
}
.book-type-m4a {
background: var(--book-type-m4a-color);
color: #fff;
}
.book-type-opus {
background: var(--book-type-opus-color);
color: #fff;
}
.book-type-cbz {
background: var(--book-type-cbz-color);
color: #fff;
}
.book-type-cbr {
background: var(--book-type-cbr-color);
color: #fff;
}
.book-type-cb7 {
background: var(--book-type-cb7-color);
color: #fff;
}
.book-type-phy {
background: var(--book-type-physical-color);
color: #fff;
}
.read-status-indicator {
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
margin-left: 0.5rem;
cursor: pointer;
border-radius: 4px;
transition: opacity 0.15s ease;
&:hover {
opacity: 0.7;
}
}
.status-read {
color: #22c55e;
}
.status-reading {
color: #3b82f6;
}
.status-re-reading {
color: #06b6d4;
}
.status-partially-read {
color: #f59e0b;
}
.status-paused {
color: #eab308;
}
.status-abandoned {
color: #ef4444;
}
.status-wont-read {
color: #ec4899;
}
.status-unset {
color: var(--text-color-secondary);
}
::ng-deep .progress-incomplete .p-progressbar-value {
background-color: #3b82f6;
}
::ng-deep .progress-complete .p-progressbar-value {
background-color: #22c55e;
}
::ng-deep .progress-incomplete-ko .p-progressbar-value {
background-color: #fbbf24;
}
::ng-deep .progress-complete-ko .p-progressbar-value {
background-color: #8b5cf6;
}
::ng-deep .progress-incomplete-kobo .p-progressbar-value {
background-color: #bf0000;
}
::ng-deep .progress-complete-kobo .p-progressbar-value {
background-color: #f65c9c;
}
::ng-deep .cover-progress-bar {
--p-progressbar-border-radius: 0 !important;
}
::ng-deep .custom-button-padding .p-button {
padding-block: 0.25rem !important;
}
::ng-deep .book-details-dialog .p-dialog-header {
padding: 1rem 1.25rem !important;
}
@@ -0,0 +1,929 @@
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core';
import {TooltipModule} from "primeng/tooltip";
import {AdditionalFile, Book, BookType, ReadStatus} from '../../../model/book.model';
import {Button} from 'primeng/button';
import {MenuModule} from 'primeng/menu';
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
import {BookService} from '../../../service/book.service';
import {BookFileService} from '../../../service/book-file.service';
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
import {CheckboxChangeEvent, CheckboxModule} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms';
import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {NgClass} from '@angular/common';
import {User, UserService} from '../../../../settings/user-management/user.service';
import {EmailService} from '../../../../settings/email-v2/email.service';
import {TieredMenu} from 'primeng/tieredmenu';
import {Router} from '@angular/router';
import {RouterLink} from '@angular/router';
import {ProgressBar} from 'primeng/progressbar';
import {readStatusLabels} from '../book-filter/book-filter.config';
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
import {BookDialogHelperService} from '../book-dialog-helper.service';
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
import {BookNavigationService} from '../../../service/book-navigation.service';
import {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service';
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {QueryClient} from '@tanstack/angular-query-experimental';
@Component({
selector: 'app-book-card',
templateUrl: './book-card.component.html',
styleUrls: ['./book-card.component.scss'],
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgClass, TieredMenu, ProgressBar, TooltipModule, RouterLink, TranslocoPipe],
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class BookCardComponent implements OnInit, OnChanges {
@Output() checkboxClick = new EventEmitter<{ index: number; book: Book; selected: boolean; shiftKey: boolean }>();
@Output() menuToggled = new EventEmitter<boolean>();
@Input() index!: number;
@Input() book!: Book;
@Input() isCheckboxEnabled: boolean = false;
@Input() onBookSelect?: (book: Book, selected: boolean) => void;
@Input() isSelected: boolean = false;
@Input() bottomBarHidden: boolean = false;
@Input() seriesViewEnabled: boolean = false;
@Input() isSeriesCollapsed: boolean = false;
@Input() overlayPreferenceService?: BookCardOverlayPreferenceService;
@Input() forceEbookMode: boolean = false;
@Input() useSquareCovers: boolean = false;
@ViewChild('checkboxElem') checkboxElem!: ElementRef<HTMLInputElement>;
items: MenuItem[] | undefined;
readStatusMenuItems: MenuItem[] = [];
isImageLoaded: boolean = false;
isSubMenuLoading = false;
private additionalFilesLoaded = false;
private bookService = inject(BookService);
private bookFileService = inject(BookFileService);
private bookMetadataManageService = inject(BookMetadataManageService);
private taskHelperService = inject(TaskHelperService);
private userService = inject(UserService);
private emailService = inject(EmailService);
private messageService = inject(MessageService);
private router = inject(Router);
protected urlHelper = inject(UrlHelperService);
private confirmationService = inject(ConfirmationService);
private bookDialogHelperService = inject(BookDialogHelperService);
private bookNavigationService = inject(BookNavigationService);
private cdr = inject(ChangeDetectorRef);
private appSettingsService = inject(AppSettingsService);
private readonly t = inject(TranslocoService);
private queryClient = inject(QueryClient);
protected _progressPercentage: number | null = null;
protected _koProgressPercentage: number | null = null;
protected _koboProgressPercentage: number | null = null;
protected _displayTitle: string | undefined = undefined;
protected _isSeriesViewActive: boolean = false;
protected _coverImageUrl: string = '';
protected _readStatusIcon: string = '';
protected _readStatusClass: string = '';
protected _readStatusTooltip: string = '';
protected _shouldShowStatusIcon: boolean = false;
protected _seriesCountTooltip: string = '';
protected _titleTooltip: string = '';
protected _hasProgress: boolean = false;
protected _isAudiobook: boolean = false;
protected _progressTooltip: string = '';
protected _isContinueReading: boolean = false;
protected _readButtonIcon: string = 'pi pi-book';
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
protected readStatusHelper = inject(ReadStatusHelper);
private user: User | null = null;
private diskType: string = 'LOCAL';
private menuInitialized = false;
ngOnInit(): void {
this.computeAllMemoizedValues();
const currentUser = this.userService.currentUser();
if (currentUser) {
this.user = currentUser;
this.metadataCenterViewMode = currentUser.userSettings?.metadataCenterViewMode ?? 'route';
}
const settings = this.appSettingsService.appSettings();
if (settings) {
this.diskType = settings.diskType ?? 'LOCAL';
}
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['book'] || changes['forceEbookMode'] || changes['useSquareCovers']) {
this.computeAllMemoizedValues();
if (changes['book'] && !changes['book'].firstChange && this.menuInitialized) {
this.additionalFilesLoaded = false;
this.initMenu();
}
}
if (changes['seriesViewEnabled'] || changes['isSeriesCollapsed']) {
this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1;
this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata?.seriesName : this.book.metadata?.title;
this._titleTooltip = this.t.translate('book.card.alt.titleTooltip', { title: this._displayTitle });
}
}
private computeAllMemoizedValues(): void {
this._progressPercentage = this.book.epubProgress?.percentage
?? this.book.pdfProgress?.percentage
?? this.book.cbxProgress?.percentage
?? null;
this._koProgressPercentage = this.book.koreaderProgress?.percentage ?? null;
this._koboProgressPercentage = this.book.koboProgress?.percentage ?? null;
this._hasProgress = this._progressPercentage !== null || this._koProgressPercentage !== null || this._koboProgressPercentage !== null;
this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1;
this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName)
? this.book.metadata?.seriesName
: this.book.metadata?.title;
this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK' && !this.forceEbookMode;
this._coverImageUrl = this._isAudiobook
? this.urlHelper.getAudiobookThumbnailUrl(this.book.id, this.book.metadata?.audiobookCoverUpdatedOn)
: this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
this._readStatusIcon = this.readStatusHelper.getReadStatusIcon(this.book.readStatus);
this._readStatusClass = this.readStatusHelper.getReadStatusClass(this.book.readStatus);
this._readStatusTooltip = this.readStatusHelper.getReadStatusTooltip(this.book.readStatus);
this._shouldShowStatusIcon = this.readStatusHelper.shouldShowStatusIcon(this.book.readStatus);
this._seriesCountTooltip = this.t.translate('book.card.alt.seriesCollapsed', { count: this.book.seriesCount });
this._titleTooltip = this.t.translate('book.card.alt.titleTooltip', { title: this._displayTitle });
const progressParts: string[] = [];
if (this._progressPercentage !== null) {
progressParts.push(`${this._progressPercentage}% (Grimmory)`);
}
if (this._koProgressPercentage !== null) {
progressParts.push(`${this._koProgressPercentage}% (KOReader)`);
}
if (this._koboProgressPercentage !== null) {
progressParts.push(`${this._koboProgressPercentage}% (Kobo)`);
}
this._progressTooltip = progressParts.join(' | ');
const maxProgress = Math.max(
this._progressPercentage ?? 0,
this._koProgressPercentage ?? 0,
this._koboProgressPercentage ?? 0
);
this._isContinueReading = maxProgress > 0 && maxProgress < 100;
if (this._isAudiobook) {
this._readButtonIcon = this._isContinueReading ? 'pi pi-forward' : 'pi pi-play';
} else {
this._readButtonIcon = this._isContinueReading ? 'pi pi-forward' : 'pi pi-book';
}
}
get hasProgress(): boolean {
return this._hasProgress;
}
get seriesCountTooltip(): string {
return this._seriesCountTooltip;
}
get titleTooltip(): string {
return this._titleTooltip;
}
get readStatusTooltip(): string {
return this._readStatusTooltip;
}
get progressTooltip(): string {
return this._progressTooltip;
}
get readButtonIcon(): string {
return this._readButtonIcon;
}
get displayTitle(): string | undefined {
return this._displayTitle;
}
get coverImageUrl(): string {
return this._coverImageUrl;
}
private buildReadStatusMenuItems(): void {
this.readStatusMenuItems = Object.entries(readStatusLabels).map(([status, label]) => ({
label,
command: () => {
this.bookService.updateBookReadStatus(this.book.id, status as ReadStatus).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.card.toast.readStatusUpdatedSummary'),
detail: this.t.translate('book.card.toast.readStatusUpdatedDetail', {label}),
life: 2000
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.card.toast.readStatusFailedSummary'),
detail: this.t.translate('book.card.toast.readStatusFailedDetail'),
life: 3000
});
}
});
}
}));
}
toggleReadStatusMenu(event: Event, menu: TieredMenu): void {
event.stopPropagation();
if (this.readStatusMenuItems.length === 0) {
this.buildReadStatusMenuItems();
}
menu.toggle(event);
}
onImageLoad(): void {
this.isImageLoaded = true;
this.cdr.markForCheck();
}
readBook(book: Book): void {
if (this.forceEbookMode && book.primaryFile?.bookType === 'AUDIOBOOK') {
const ebookType = this.getEbookType(book);
if (ebookType) {
this.bookService.readBook(book.id, undefined, ebookType);
return;
}
}
this.bookService.readBook(book.id);
}
private getEbookType(book: Book): BookType | undefined {
if (book.epubProgress) return 'EPUB';
if (book.pdfProgress) return 'PDF';
if (book.cbxProgress) return 'CBX';
const alternativeFormat = book.alternativeFormats?.find(f =>
f.bookType && ['EPUB', 'PDF', 'CBX', 'FB2', 'MOBI', 'AZW3'].includes(f.bookType)
);
return alternativeFormat?.bookType;
}
onMenuShow(): void {
this.menuToggled.emit(true);
}
onMenuHide(): void {
this.menuToggled.emit(false);
}
onMenuToggle(event: Event, menu: TieredMenu): void {
if (!this.menuInitialized) {
this.menuInitialized = true;
this.initMenu();
this.cdr.markForCheck();
}
menu.toggle(event);
if (!this.additionalFilesLoaded && !this.isSubMenuLoading && this.needsAdditionalFilesData()) {
this.isSubMenuLoading = true;
this.cdr.markForCheck();
const requestedBookId = this.book.id;
void this.queryClient.fetchQuery(this.bookService.bookDetailQueryOptions(requestedBookId, true))
.then((book) => {
if (this.book.id !== requestedBookId) {
return;
}
this.book = book;
this.additionalFilesLoaded = true;
this.isSubMenuLoading = false;
this.initMenu();
this.cdr.markForCheck();
})
.catch(() => {
if (this.book.id !== requestedBookId) {
return;
}
this.isSubMenuLoading = false;
this.cdr.markForCheck();
});
}
}
private needsAdditionalFilesData(): boolean {
if (this.additionalFilesLoaded) {
return false;
}
const hasNoAlternativeFormats = !this.book.alternativeFormats || this.book.alternativeFormats.length === 0;
const hasNoSupplementaryFiles = !this.book.supplementaryFiles || this.book.supplementaryFiles.length === 0;
const canDownload = !!this.user?.permissions.canDownload;
const canDeleteBook = !!this.user?.permissions.canDeleteBook;
return (canDownload || canDeleteBook) && hasNoAlternativeFormats && hasNoSupplementaryFiles;
}
private initMenu() {
this.items = [
{
label: this.t.translate('book.card.menu.assignShelf'),
icon: 'pi pi-folder',
command: () => this.openShelfDialog()
},
{
label: this.t.translate('book.card.menu.viewDetails'),
icon: 'pi pi-info-circle',
command: () => {
setTimeout(() => {
this.openBookInfo(this.book);
}, 150);
},
},
...this.getPermissionBasedMenuItems(),
...this.moreMenuItems(),
];
}
private getPermissionBasedMenuItems(): MenuItem[] {
const items: MenuItem[] = [];
if (this.user?.permissions.canDownload) {
const hasAdditionalFiles = (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
if (hasAdditionalFiles) {
const downloadItems = this.getDownloadMenuItems();
items.push({
label: this.t.translate('book.card.menu.download'),
icon: 'pi pi-download',
items: downloadItems
});
} else if (this.additionalFilesLoaded) {
items.push({
label: this.t.translate('book.card.menu.download'),
icon: 'pi pi-download',
command: () => {
this.bookFileService.downloadFile(this.book);
}
});
} else {
items.push({
label: this.t.translate('book.card.menu.download'),
icon: this.isSubMenuLoading ? 'pi pi-spin pi-spinner' : 'pi pi-download',
items: [{label: this.t.translate('book.card.menu.loading'), disabled: true}]
});
}
}
if (this.user?.permissions.canDeleteBook) {
const hasAdditionalFiles = (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
if (hasAdditionalFiles) {
const deleteItems = this.getDeleteMenuItems();
items.push({
label: this.t.translate('book.card.menu.delete'),
icon: 'pi pi-trash',
items: deleteItems
});
} else if (this.additionalFilesLoaded) {
items.push({
label: this.t.translate('book.card.menu.delete'),
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.card.confirm.deleteBookMessage', {title: this.book.metadata?.title}),
header: this.t.translate('book.card.confirm.deleteBookHeader'),
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
rejectIcon: 'pi pi-times',
acceptLabel: this.t.translate('common.delete'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonStyleClass: 'p-button-danger',
rejectButtonStyleClass: 'p-button-outlined',
accept: () => {
this.bookService.deleteBooks(new Set([this.book.id])).subscribe();
}
});
}
});
} else {
items.push({
label: this.t.translate('book.card.menu.delete'),
icon: this.isSubMenuLoading ? 'pi pi-spin pi-spinner' : 'pi pi-trash',
items: [{label: this.t.translate('book.card.menu.loading'), disabled: true}]
});
}
}
if (this.user?.permissions.canEmailBook) {
items.push(
{
label: this.t.translate('book.card.menu.emailBook'),
icon: 'pi pi-envelope',
items: [{
label: this.t.translate('book.card.menu.quickSend'),
icon: 'pi pi-envelope',
command: () => {
const doSend = () => {
this.emailService.emailBookQuick(this.book.id).subscribe({
next: () => {
this.messageService.add({
severity: 'info',
summary: this.t.translate('common.success'),
detail: this.t.translate('book.card.toast.quickSendSuccessDetail'),
});
},
error: (err) => {
const errorMessage = err?.error?.message || this.t.translate('book.card.toast.quickSendErrorDetail');
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: errorMessage,
});
},
});
};
if (this.book.primaryFile?.fileSizeKb && this.book.primaryFile.fileSizeKb > 25 * 1024) {
this.confirmationService.confirm({
message: this.t.translate('book.card.confirm.largeFileMessage'),
header: this.t.translate('book.card.confirm.largeFileHeader'),
icon: 'pi pi-exclamation-triangle',
acceptLabel: this.t.translate('book.card.confirm.sendAnyway'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: { severity: 'warn' },
rejectButtonProps: { severity: 'secondary' },
accept: doSend,
});
} else {
doSend();
}
}
},
{
label: this.t.translate('book.card.menu.customSend'),
icon: 'pi pi-envelope',
command: () => {
this.bookDialogHelperService.openCustomSendDialog(this.book);
}
}
]
});
}
if (this.user?.permissions.canEditMetadata) {
items.push({
label: this.t.translate('book.card.menu.metadata'),
icon: 'pi pi-database',
items: [
{
label: this.t.translate('book.card.menu.searchMetadata'),
icon: 'pi pi-sparkles',
command: () => {
setTimeout(() => {
this.router.navigate(['/book', this.book.id], {
queryParams: {tab: 'match'}
})
}, 150);
},
},
{
label: this.t.translate('book.card.menu.autoFetch'),
icon: 'pi pi-bolt',
command: () => {
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.BOOKS,
bookIds: [this.book.id],
}).subscribe();
}
},
{
label: this.t.translate('book.card.menu.customFetch'),
icon: 'pi pi-sync',
command: () => {
this.bookDialogHelperService.openMetadataRefreshDialog(new Set([this.book!.id]))
},
},
{
label: this.t.translate('book.card.menu.regenerateCover'),
icon: 'pi pi-image',
command: () => {
this.bookMetadataManageService.regenerateCover(this.book.id).subscribe({
next: () => this.messageService.add({
severity: 'success',
summary: this.t.translate('common.success'),
detail: this.t.translate('book.card.toast.coverRegenSuccessDetail')
}),
error: (err) => this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: err?.error?.message || this.t.translate('book.card.toast.coverRegenFailedDetail')
})
});
}
},
{
label: this.t.translate('book.card.menu.generateCustomCover'),
icon: 'pi pi-palette',
command: () => {
this.bookMetadataManageService.generateCustomCover(this.book.id).subscribe({
next: () => this.messageService.add({
severity: 'success',
summary: this.t.translate('common.success'),
detail: this.t.translate('book.card.toast.customCoverSuccessDetail')
}),
error: (err) => this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: err?.error?.message || this.t.translate('book.card.toast.customCoverFailedDetail')
})
});
}
}
]
});
}
return items;
}
private moreMenuItems(): MenuItem[] {
const items: MenuItem[] = [];
const moreActions: MenuItem[] = [];
if (this.user?.permissions.canMoveOrganizeFiles && this.diskType === 'LOCAL') {
moreActions.push({
label: this.t.translate('book.card.menu.organizeFile'),
icon: 'pi pi-arrows-h',
command: () => {
this.bookDialogHelperService.openFileMoverDialog(new Set([this.book.id]));
}
});
}
moreActions.push(
{
label: this.t.translate('book.card.menu.readStatus'),
icon: 'pi pi-book',
items: Object.entries(readStatusLabels).map(([status, label]) => ({
label,
command: () => {
this.bookService.updateBookReadStatus(this.book.id, status as ReadStatus).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.card.toast.readStatusUpdatedSummary'),
detail: this.t.translate('book.card.toast.readStatusUpdatedDetail', {label}),
life: 2000
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.card.toast.readStatusFailedSummary'),
detail: this.t.translate('book.card.toast.readStatusFailedDetail'),
life: 3000
});
}
});
}
}))
},
{
label: this.t.translate('book.card.menu.resetGrimmoryProgress'),
icon: 'pi pi-undo',
command: () => {
this.bookService.resetProgress(this.book.id, ResetProgressTypes.GRIMMORY).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.card.toast.progressResetSummary'),
detail: this.t.translate('book.card.toast.progressResetGrimmoryDetail'),
life: 1500
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.card.toast.progressResetFailedSummary'),
detail: this.t.translate('book.card.toast.progressResetGrimmoryFailedDetail'),
life: 1500
});
}
});
},
},
{
label: this.t.translate('book.card.menu.resetKOReaderProgress'),
icon: 'pi pi-undo',
command: () => {
this.bookService.resetProgress(this.book.id, ResetProgressTypes.KOREADER).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.card.toast.progressResetSummary'),
detail: this.t.translate('book.card.toast.progressResetKOReaderDetail'),
life: 1500
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.card.toast.progressResetFailedSummary'),
detail: this.t.translate('book.card.toast.progressResetKOReaderFailedDetail'),
life: 1500
});
}
});
},
}
);
items.push({
label: this.t.translate('book.card.menu.moreActions'),
icon: 'pi pi-ellipsis-h',
items: moreActions
});
return items;
}
private openShelfDialog(): void {
this.bookDialogHelperService.openShelfAssignerDialog(this.book, null);
}
openSeriesInfo(): void {
const seriesName = this.book?.metadata?.seriesName;
if (this.isSeriesCollapsed && seriesName) {
const encodedSeriesName = encodeURIComponent(seriesName);
this.router.navigate(['/series', encodedSeriesName]);
} else {
this.openBookInfo(this.book);
}
}
openBookInfo(book: Book): void {
const allBookIds = this.bookNavigationService.availableBookIds();
if (allBookIds.length > 0) {
this.bookNavigationService.setNavigationContext(allBookIds, book.id);
}
if (this.metadataCenterViewMode === 'route') {
this.router.navigate(['/book', book.id], {
queryParams: {tab: 'view'}
});
} else {
this.bookDialogHelperService.openBookDetailsDialog(book.id);
}
}
private getDownloadMenuItems(): MenuItem[] {
const items: MenuItem[] = [];
items.push({
label: `${this.book.fileName || 'Book File'}`,
icon: 'pi pi-file',
command: () => {
this.bookFileService.downloadFile(this.book);
}
});
if (this.hasAdditionalFiles()) {
items.push({separator: true});
}
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) {
this.book.alternativeFormats.forEach(format => {
const extension = this.getFileExtension(format.filePath);
items.push({
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
icon: this.getFileIcon(extension),
command: () => this.downloadAdditionalFile(this.book, format.id)
});
});
}
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0 &&
this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
items.push({separator: true});
}
if (this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
this.book.supplementaryFiles.forEach(file => {
const extension = this.getFileExtension(file.filePath);
items.push({
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
icon: this.getFileIcon(extension),
command: () => this.downloadAdditionalFile(this.book, file.id)
});
});
}
return items;
}
private getDeleteMenuItems(): MenuItem[] {
const items: MenuItem[] = [];
items.push({
label: this.t.translate('book.card.menu.book'),
icon: 'pi pi-book',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.card.confirm.deleteBookMessage', {title: this.book.metadata?.title}),
header: this.t.translate('book.card.confirm.deleteBookHeader'),
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
rejectIcon: 'pi pi-times',
acceptLabel: this.t.translate('common.delete'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonStyleClass: 'p-button-danger',
rejectButtonStyleClass: 'p-button-outlined',
accept: () => {
this.bookService.deleteBooks(new Set([this.book.id])).subscribe();
}
});
}
});
if (this.hasAdditionalFiles()) {
items.push({separator: true});
}
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) {
this.book.alternativeFormats.forEach(format => {
const extension = this.getFileExtension(format.filePath);
items.push({
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
icon: this.getFileIcon(extension),
command: () => this.deleteAdditionalFile(this.book.id, format.id, format.fileName || 'file')
});
});
}
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0 &&
this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
items.push({separator: true});
}
if (this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
this.book.supplementaryFiles.forEach(file => {
const extension = this.getFileExtension(file.filePath);
items.push({
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
icon: this.getFileIcon(extension),
command: () => this.deleteAdditionalFile(this.book.id, file.id, file.fileName || 'file')
});
});
}
return items;
}
private hasAdditionalFiles(): boolean {
return !!(this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
!!(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
}
private downloadAdditionalFile(book: Book, fileId: number): void {
this.bookFileService.downloadAdditionalFile(book, fileId);
}
private deleteAdditionalFile(bookId: number, fileId: number, fileName: string): void {
this.confirmationService.confirm({
message: this.t.translate('book.card.confirm.deleteFileMessage', {fileName}),
header: this.t.translate('book.card.confirm.deleteFileHeader'),
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
rejectIcon: 'pi pi-times',
acceptButtonStyleClass: 'p-button-danger',
accept: () => {
this.bookFileService.deleteAdditionalFile(bookId, fileId).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('common.success'),
detail: this.t.translate('book.card.toast.deleteFileSuccessDetail', {fileName})
});
},
error: (error) => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: this.t.translate('book.card.toast.deleteFileErrorDetail', {error: error.message || 'Unknown error'})
});
}
});
}
});
}
getFileExtension(filePath?: string): string | null {
if (!filePath) return null;
const parts = filePath.split('.');
if (parts.length < 2) return null;
return parts.pop()?.toUpperCase() || null;
}
getDisplayFormat(): string | null {
if (!this.book?.primaryFile) {
return 'PHY';
}
if (this.forceEbookMode && this.book.primaryFile?.bookType === 'AUDIOBOOK') {
const ebookType = this.getEbookType(this.book);
if (ebookType) {
return ebookType;
}
}
const ext = this.book?.primaryFile?.extension;
if (ext) {
return ext.toUpperCase();
}
return this.getFileExtension(this.book?.primaryFile?.filePath);
}
hasDigitalFile(): boolean {
return !!this.book?.primaryFile;
}
private getFileIcon(fileType: string | null): string {
if (!fileType) return 'pi pi-file';
switch (fileType.toLowerCase()) {
case 'pdf':
return 'pi pi-file-pdf';
case 'epub':
case 'mobi':
case 'azw3':
case 'fb2':
return 'pi pi-book';
case 'cbz':
case 'cbr':
case 'cbx':
return 'pi pi-image';
case 'audiobook':
case 'm4b':
case 'm4a':
case 'mp3':
case 'opus':
return 'pi pi-headphones';
default:
return 'pi pi-file';
}
}
private getFileSizeInMB(fileInfo: AdditionalFile): string {
const sizeKb = fileInfo?.fileSizeKb;
return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-';
}
private lastMouseEvent: MouseEvent | null = null;
captureMouseEvent(event: MouseEvent): void {
this.lastMouseEvent = event;
}
onCardClick(event: MouseEvent): void {
if (!event.ctrlKey) {
return;
}
this.toggleCardSelection(!this.isSelected)
}
toggleCardSelection(selected: boolean): void {
if (!this.isCheckboxEnabled) {
return;
}
this.isSelected = selected;
const shiftKey = this.lastMouseEvent?.shiftKey ?? false;
this.checkboxClick.emit({
index: this.index,
book: this.book,
selected: selected,
shiftKey: shiftKey,
});
if (this.onBookSelect) {
this.onBookSelect(this.book, selected);
}
this.lastMouseEvent = null;
}
toggleSelection(event: CheckboxChangeEvent): void {
this.toggleCardSelection(event.checked);
}
}
@@ -0,0 +1,199 @@
import {inject, Injectable} from '@angular/core';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {DialogLauncherService, DialogSize, DialogStyle} from '../../../../shared/services/dialog-launcher.service';
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component';
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
import {BulkMetadataUpdateComponent} from '../../../metadata/component/bulk-metadata-update/bulk-metadata-update-component';
import {MultiBookMetadataEditorComponent} from '../../../metadata/component/multi-book-metadata-editor/multi-book-metadata-editor-component';
import {MultiBookMetadataFetchComponent} from '../../../metadata/component/multi-book-metadata-fetch/multi-book-metadata-fetch-component';
import {FileMoverComponent} from '../../../../shared/components/file-mover/file-mover-component';
import {ShelfCreatorComponent} from '../shelf-creator/shelf-creator.component';
import {BookSenderComponent} from '../book-sender/book-sender.component';
import {MetadataFetchOptionsComponent} from '../../../metadata/component/metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component';
import {BookMetadataCenterComponent} from '../../../metadata/component/book-metadata-center/book-metadata-center.component';
import {CoverSearchComponent} from '../../../metadata/component/cover-search/cover-search.component';
import {Book} from '../../model/book.model';
import {AdditionalFileUploaderComponent} from '../additional-file-uploader/additional-file-uploader.component';
import {BookFileAttacherComponent} from '../book-file-attacher/book-file-attacher.component';
import {AddPhysicalBookDialogComponent} from '../add-physical-book-dialog/add-physical-book-dialog.component';
import {BulkIsbnImportDialogComponent} from '../bulk-isbn-import-dialog/bulk-isbn-import-dialog.component';
import {DuplicateMergerComponent} from '../duplicate-merger/duplicate-merger.component';
@Injectable({providedIn: 'root'})
export class BookDialogHelperService {
private dialogLauncherService = inject(DialogLauncherService);
private openDialog(component: unknown, options: {}): DynamicDialogRef | null {
return this.dialogLauncherService.openDialog(component, options);
}
openBookDetailsDialog(bookId: number): DynamicDialogRef | null {
return this.openDialog(BookMetadataCenterComponent, {
showHeader: false,
styleClass: `book-details-dialog ${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
data: {
bookId: bookId,
},
});
}
openShelfAssignerDialog(book: Book | null, bookIds: Set<number> | null): DynamicDialogRef | null {
const data: any = {};
if (book !== null) {
data.isMultiBooks = false;
data.book = book;
} else if (bookIds !== null) {
data.isMultiBooks = true;
data.bookIds = bookIds;
} else {
return null;
}
return this.openDialog(ShelfAssignerComponent, {
showHeader: false,
data: data,
styleClass: `${DialogSize.SM} ${DialogStyle.MINIMAL}`,
});
}
openShelfCreatorDialog(): DynamicDialogRef {
return this.openDialog(ShelfCreatorComponent, {
showHeader: false,
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
})!;
}
openLockUnlockMetadataDialog(bookIds: Set<number>): DynamicDialogRef | null {
return this.openDialog(LockUnlockMetadataDialogComponent, {
showHeader: false,
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
data: {
bookIds: Array.from(bookIds),
},
});
}
openMetadataRefreshDialog(bookIds: Set<number>): DynamicDialogRef | null {
return this.openDialog(MultiBookMetadataFetchComponent, {
showHeader: false,
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
data: {
bookIds: Array.from(bookIds),
metadataRefreshType: MetadataRefreshType.BOOKS,
},
});
}
openBulkMetadataEditDialog(bookIds: Set<number>): DynamicDialogRef | null {
return this.openDialog(BulkMetadataUpdateComponent, {
showHeader: false,
styleClass: `${DialogSize.XL} ${DialogStyle.MINIMAL}`,
data: {
bookIds: Array.from(bookIds),
},
});
}
openMultibookMetadataEditorDialog(bookIds: Set<number>): DynamicDialogRef | null {
return this.openDialog(MultiBookMetadataEditorComponent, {
showHeader: false,
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
data: {
bookIds: Array.from(bookIds),
},
});
}
openFileMoverDialog(bookIds: Set<number>): DynamicDialogRef | null {
return this.openDialog(FileMoverComponent, {
showHeader: false,
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
maximizable: true,
data: {
bookIds: Array.from(bookIds),
},
});
}
openCustomSendDialog(book: Book): DynamicDialogRef | null {
return this.openDialog(BookSenderComponent, {
showHeader: false,
styleClass: `${DialogSize.SM} ${DialogStyle.MINIMAL}`,
data: {
book: book,
},
});
}
openCoverSearchDialog(bookId: number, coverType?: 'ebook' | 'audiobook'): DynamicDialogRef | null {
return this.openDialog(CoverSearchComponent, {
showHeader: false,
styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`,
data: {
bookId: bookId,
coverType: coverType,
},
});
}
openAdditionalFileUploaderDialog(book: Book): DynamicDialogRef | null {
return this.openDialog(AdditionalFileUploaderComponent, {
showHeader: false,
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
data: {
book: book,
},
});
}
openBookFileAttacherDialog(sourceBook: Book): DynamicDialogRef | null {
return this.openDialog(BookFileAttacherComponent, {
showHeader: false,
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
data: {
sourceBook: sourceBook,
},
});
}
openBulkBookFileAttacherDialog(sourceBooks: Book[]): DynamicDialogRef | null {
return this.openDialog(BookFileAttacherComponent, {
showHeader: false,
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
data: {
sourceBooks: sourceBooks,
},
});
}
openDuplicateMergerDialog(libraryId: number): DynamicDialogRef | null {
return this.openDialog(DuplicateMergerComponent, {
showHeader: false,
styleClass: `${DialogSize.XL} ${DialogStyle.MINIMAL}`,
data: {
libraryId: libraryId,
},
});
}
openAddPhysicalBookDialog(libraryId?: number): DynamicDialogRef | null {
return this.openDialog(AddPhysicalBookDialogComponent, {
showHeader: false,
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
data: {
libraryId: libraryId,
},
});
}
openBulkIsbnImportDialog(libraryId?: number): DynamicDialogRef | null {
return this.openDialog(BulkIsbnImportDialogComponent, {
showHeader: false,
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
data: {
libraryId: libraryId,
},
});
}
}
@@ -0,0 +1,36 @@
import {inject, Injectable} from '@angular/core';
import {ParamMap} from '@angular/router';
import {Book} from '../../model/book.model';
import {SortOption} from '../../model/sort.model';
import {SortService} from '../../service/sort.service';
import {filterBooksBySearchTerm} from './filters/HeaderFilter';
import {filterBooksByFilters} from './filters/sidebar-filter';
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
import {QUERY_PARAMS} from './book-browser-query-params.service';
import {BookFilterMode} from '../../../settings/user-management/user.service';
@Injectable({providedIn: 'root'})
export class BookFilterOrchestrationService {
private sortService = inject(SortService);
applyFilters(
books: Book[],
searchTerm: string,
activeFilters: Record<string, unknown[]> | null,
filterMode: BookFilterMode,
seriesCollapseFilter: SeriesCollapseFilter,
isSeriesCollapsed: boolean,
forceExpandSeries: boolean,
sortCriteria: SortOption[]
): Book[] {
const searchedBooks = filterBooksBySearchTerm(books, searchTerm);
const filteredBooks = filterBooksByFilters(searchedBooks, activeFilters, filterMode);
const collapsedBooks = seriesCollapseFilter.collapseBooks(filteredBooks, forceExpandSeries, isSeriesCollapsed);
return this.sortService.applyMultiSort(collapsedBooks, sortCriteria);
}
shouldForceExpandSeries(queryParamMap: ParamMap): boolean {
const filterParam = queryParamMap.get(QUERY_PARAMS.FILTER);
return !!filterParam && filterParam.split(',').some(pair => pair.trim().startsWith('series:'));
}
}
@@ -0,0 +1,71 @@
<ng-container *transloco="let t; prefix: 'book.filter'">
<div class="book-filter-container">
<div class="filter-header">
<span class="filter-title">{{ t('title') }}</span>
<p-selectButton
[options]="filterModeOptions"
[(ngModel)]="selectedFilterMode"
optionLabel="label"
optionValue="value"
class="filter-mode-select"
allowEmpty="false"
></p-selectButton>
</div>
<div class="filter-content">
<p-accordion [value]="expandedPanels" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
@for (filterType of visibleFilterTypes; track trackByFilterType(i, filterType); let i = $index) {
@if (filterSignals[filterType](); as filters) {
@if (filters.length > 0) {
<p-accordion-panel [value]="i">
<p-accordion-header>
<span class="filter-type-label">
<span class="filter-label-text">
{{ getFilterLabel(filterType) }}
</span>
@if (activeFilters[filterType]?.length) {
<span class="active-filter-count">
({{ activeFilters[filterType].length }})
</span>
}
</span>
</p-accordion-header>
<p-accordion-content>
@if (expandedPanels.includes(i)) {
<cdk-virtual-scroll-viewport
[itemSize]="28"
[style.height.px]="getVirtualScrollHeight(filters.length)"
class="filter-list">
<div
*cdkVirtualFor="let filter of filters; trackBy: trackByFilter"
class="filter-row"
[ngClass]="{
'active': activeFilters[filterType]?.includes(getFilterValueId(filter)),
'active-not': activeFilters[filterType]?.includes(getFilterValueId(filter)) && selectedFilterMode === 'not'
}"
(click)="handleFilterClick(filterType, getFilterValueId(filter))">
<span class="filter-value-text">{{ getFilterValueDisplay(filter) }}</span>
<p-badge class="filter-value-badge" [value]="filter.bookCount"></p-badge>
</div>
</cdk-virtual-scroll-viewport>
@if (truncatedFilters[filterType]) {
<div class="truncation-notice">
{{ t('showingFirst100') }}
</div>
}
}
</p-accordion-content>
</p-accordion-panel>
}
}
}
</p-accordion>
<div class="footer-notice">
{{ t('footerNote') }}
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,129 @@
:host ::ng-deep p-accordion-header {
--p-accordion-header-padding: 0.6rem 1rem;
}
:host ::ng-deep .p-togglebutton {
--p-togglebutton-content-padding: 0.25rem 0.35rem;
}
:host ::ng-deep .cdk-virtual-scroll-orientation-vertical .cdk-virtual-scroll-content-wrapper {
width: calc(var(--sidebar-width, 225px) - 35px) !important;
min-width: unset;
}
.book-filter-container {
height: calc(100dvh - 6.1rem);
border-radius: 0.75rem;
overflow: hidden;
background: var(--card-background);
display: flex;
flex-direction: column;
border: 1px solid var(--p-content-border-color);
}
.filter-header {
display: inline-flex;
align-items: center;
justify-content: space-between;
padding: 1rem;
border-bottom: 1px solid var(--p-content-border-color);
}
.filter-title {
font-weight: 600;
}
.filter-mode-select {
font-size: 0.75rem;
}
:host ::ng-deep .filter-mode-select .p-togglebutton-label {
font-size: 0.75rem;
}
.filter-content {
flex: 1;
overflow-y: auto;
padding-bottom: 1rem;
overscroll-behavior: contain;
}
.filter-type-label {
display: inline-flex;
align-items: center;
gap: 0.25rem;
max-width: 100%;
overflow: hidden;
min-width: 0;
}
.filter-label-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex-shrink: 1;
max-width: 175px;
}
.active-filter-count {
font-size: 0.875rem;
color: var(--primary-color);
flex-shrink: 0;
white-space: nowrap;
min-width: 0;
}
.filter-list {
padding-right: 0.25rem;
}
.filter-row {
cursor: pointer;
transition: colors 200ms ease-in-out;
height: 26px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
max-width: 97%;
&.active {
color: var(--primary-color);
}
&.active-not {
color: var(--p-red-400);
text-decoration: line-through;
}
}
.filter-value-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.filter-value-badge {
flex-shrink: 0;
}
.truncation-notice {
font-size: 0.75rem;
color: #6b7280;
text-align: center;
padding-top: 0.5rem;
border-top: 1px solid #e5e7eb;
}
.footer-notice {
font-size: 0.75rem;
color: #6b7280;
text-align: center;
padding-top: 1rem;
padding-left: 1rem;
padding-right: 1rem;
margin-top: 0.5rem;
}
@@ -0,0 +1,236 @@
import {ChangeDetectionStrategy, Component, effect, EventEmitter, inject, Input, OnDestroy, OnInit, Output, Signal, signal} from '@angular/core';
import {Subject, takeUntil} from 'rxjs';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {EntityType} from '../book-browser.component';
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
import {CdkFixedSizeVirtualScroll, CdkVirtualForOf, CdkVirtualScrollViewport} from '@angular/cdk/scrolling';
import {NgClass} from '@angular/common';
import {Badge} from 'primeng/badge';
import {FormsModule} from '@angular/forms';
import {SelectButton} from 'primeng/selectbutton';
import {BookFilterMode, DEFAULT_VISIBLE_FILTERS, UserService, VisibleFilterType} from '../../../../settings/user-management/user.service';
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {Filter, FILTER_LABEL_KEYS, FilterType} from './book-filter.config';
import {BookFilterService} from './book-filter.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
interface FilterModeOption {
label: string;
value: BookFilterMode;
}
@Component({
selector: 'app-book-filter',
templateUrl: './book-filter.component.html',
styleUrls: ['./book-filter.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [
Accordion, AccordionPanel, AccordionHeader, AccordionContent,
CdkVirtualScrollViewport, CdkFixedSizeVirtualScroll, CdkVirtualForOf,
NgClass, Badge, FormsModule, SelectButton,
TranslocoDirective
]
})
export class BookFilterComponent implements OnInit, OnDestroy {
@Input() set entity(value: Library | Shelf | MagicShelf | null | undefined) {
this.entitySignal.set(value ?? null);
}
@Input() set entityType(value: EntityType | undefined) {
this.entityTypeSignal.set(value ?? EntityType.ALL_BOOKS);
}
@Input() resetFilter$!: Subject<void>;
@Input() showFilter = false;
@Output() filterSelected = new EventEmitter<Record<string, unknown> | null>();
@Output() filterModeChanged = new EventEmitter<BookFilterMode>();
private readonly filterService = inject(BookFilterService);
private readonly userService = inject(UserService);
private readonly t = inject(TranslocoService);
private readonly destroy$ = new Subject<void>();
private readonly entitySignal = signal<Library | Shelf | MagicShelf | null>(null);
private readonly entityTypeSignal = signal<EntityType>(EntityType.ALL_BOOKS);
private readonly activeFiltersSignal = signal<Record<string, unknown[]> | null>(null);
private readonly filterModeSignal = signal<BookFilterMode>('and');
activeFilters: Record<string, unknown[]> = {};
filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.createFilterSignals(
this.entitySignal,
this.entityTypeSignal,
this.activeFiltersSignal,
this.filterModeSignal
);
filterTypes: FilterType[] = Object.keys(this.filterSignals) as FilterType[];
visibleFilterTypes: FilterType[] = [];
expandedPanels: number[] = [0];
truncatedFilters: Record<string, boolean> = {};
private _selectedFilterMode: BookFilterMode = 'and';
private _visibleFilters: VisibleFilterType[] = [...DEFAULT_VISIBLE_FILTERS];
readonly filterLabelKeys = FILTER_LABEL_KEYS;
getFilterLabel(type: FilterType): string {
const key = this.filterLabelKeys[type];
return key ? this.t.translate(key) : type;
}
readonly filterModeOptions: FilterModeOption[] = [
{label: 'AND', value: 'and'},
{label: 'OR', value: 'or'},
{label: 'NOT', value: 'not'},
{label: '1', value: 'single'}
];
get selectedFilterMode(): BookFilterMode {
return this._selectedFilterMode;
}
set selectedFilterMode(mode: BookFilterMode) {
if (mode === this._selectedFilterMode) return;
this._selectedFilterMode = mode;
this.filterModeSignal.set(mode);
this.filterModeChanged.emit(mode);
this.emitFilters();
}
ngOnInit(): void {
this.updateVisibleFilterTypes();
this.updateExpandedPanels();
this.subscribeToUserSettings();
this.subscribeToReset();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
handleFilterClick(filterType: string, value: unknown): void {
if (this._selectedFilterMode === 'single') {
this.handleSingleMode(filterType, value);
} else {
this.handleMultiMode(filterType, value);
}
this.emitFilters();
}
setFilters(filters: Record<string, unknown>): void {
this.activeFilters = {};
for (const [key, value] of Object.entries(filters)) {
const values = Array.isArray(value) ? value : [value];
this.activeFilters[key] = values.map(v => this.filterService.processFilterValue(key, v));
}
this.emitFilters();
}
clearActiveFilter(): void {
this.activeFilters = {};
this.expandedPanels = [0];
this.activeFiltersSignal.set(null);
this.filterSelected.emit(null);
}
onExpandedPanelsChange(value: string | number | string[] | number[] | null | undefined): void {
if (Array.isArray(value)) {
this.expandedPanels = value.map(Number);
}
}
onFiltersChanged(): void {
this.updateExpandedPanels();
}
getVirtualScrollHeight = (itemCount: number): number => Math.min(itemCount * 28, 440);
trackByFilterType = (_: number, type: FilterType): string => type;
trackByFilter = (_: number, f: Filter): unknown => this.getFilterValueId(f);
getFilterValueId(f: Filter): unknown {
const value = f.value;
return typeof value === 'object' && value !== null && 'id' in value
? value.id
: f.value;
}
getFilterValueDisplay(f: Filter): string {
const value = f.value;
if (typeof value === 'object' && value !== null && 'name' in value) {
return String(value.name ?? '');
}
return String(value ?? '');
}
private subscribeToUserSettings(): void {
effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this._visibleFilters = user.userSettings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS];
this.updateVisibleFilterTypes();
});
}
private updateVisibleFilterTypes(): void {
this.visibleFilterTypes = this._visibleFilters.filter(
vf => this.filterTypes.includes(vf as FilterType)
) as FilterType[];
}
private subscribeToReset(): void {
this.resetFilter$?.pipe(takeUntil(this.destroy$)).subscribe(() => this.clearActiveFilter());
}
private handleSingleMode(filterType: string, value: unknown): void {
const id = this.extractId(value);
const current = this.activeFilters[filterType];
const isSame = current?.length === 1 && this.valuesMatch(current[0], id);
this.activeFilters = isSame ? {} : {[filterType]: [id]};
}
private handleMultiMode(filterType: string, value: unknown): void {
const id = this.extractId(value);
if (!this.activeFilters[filterType]) {
this.activeFilters[filterType] = [];
}
const arr = this.activeFilters[filterType];
const index = arr.findIndex(v => this.valuesMatch(v, id));
if (index > -1) {
arr.splice(index, 1);
if (arr.length === 0) delete this.activeFilters[filterType];
} else {
arr.push(id);
}
}
private extractId(value: unknown): unknown {
return typeof value === 'object' && value !== null && 'id' in value
? (value as { id: unknown }).id
: value;
}
private valuesMatch(a: unknown, b: unknown): boolean {
return a === b || String(a) === String(b);
}
private emitFilters(): void {
const hasFilters = Object.keys(this.activeFilters).length > 0;
const filtersToEmit = hasFilters ? {...this.activeFilters} : null;
this.activeFiltersSignal.set(filtersToEmit);
this.filterSelected.emit(filtersToEmit);
}
private updateExpandedPanels(): void {
const panels = new Set(this.expandedPanels);
this.visibleFilterTypes.forEach((type, i) => {
if (this.activeFilters[type]?.length) panels.add(i);
});
this.expandedPanels = panels.size > 0 ? [...panels] : [0];
}
}
@@ -0,0 +1,365 @@
import {Book, ReadStatus} from '../../../model/book.model';
// ============================================================================
// TYPES
// ============================================================================
export interface FilterValue {
id?: string | number;
name?: string;
sortIndex?: number;
}
export interface Filter<T extends FilterValue = FilterValue> {
value: T;
bookCount: number;
}
export type FilterType =
| 'author' | 'category' | 'series' | 'bookType' | 'readStatus'
| 'personalRating' | 'publisher' | 'matchScore' | 'library' | 'shelf'
| 'shelfStatus' | 'tag' | 'publishedDate' | 'fileSize' | 'amazonRating'
| 'goodreadsRating' | 'hardcoverRating' | 'language' | 'pageCount' | 'mood'
| 'ageRating' | 'contentRating'
| 'narrator'
| 'comicCharacter' | 'comicTeam' | 'comicLocation' | 'comicCreator';
export type SortMode = 'count' | 'sortIndex';
export interface RangeConfig {
id: number;
label: string;
min: number;
max: number;
sortIndex: number;
}
export interface FilterConfig {
label: string;
extractor: (book: Book) => FilterValue[];
sortMode: SortMode;
isNumericId?: boolean;
}
// ============================================================================
// CONSTANTS
// ============================================================================
export const READ_STATUS_LABELS: Readonly<Record<ReadStatus, string>> = {
[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'
};
export const RATING_RANGES_5: readonly RangeConfig[] = [
{id: 0, label: '0 to 1', min: 0, max: 1, sortIndex: 0},
{id: 1, label: '1 to 2', min: 1, max: 2, sortIndex: 1},
{id: 2, label: '2 to 3', min: 2, max: 3, sortIndex: 2},
{id: 3, label: '3 to 4', min: 3, max: 4, sortIndex: 3},
{id: 4, label: '4 to 4.5', min: 4, max: 4.5, sortIndex: 4},
{id: 5, label: '4.5+', min: 4.5, max: Infinity, sortIndex: 5}
];
export const RATING_OPTIONS_10: readonly RangeConfig[] = Array.from({length: 10}, (_, i) => ({
id: i + 1,
label: `${i + 1}`,
min: i + 1,
max: i + 2,
sortIndex: i
}));
export const FILE_SIZE_RANGES: readonly RangeConfig[] = [
{id: 0, label: '< 1 MB', min: 0, max: 1024, sortIndex: 0},
{id: 1, label: '1–10 MB', min: 1024, max: 10240, sortIndex: 1},
{id: 2, label: '10–50 MB', min: 10240, max: 51200, sortIndex: 2},
{id: 3, label: '50–100 MB', min: 51200, max: 102400, sortIndex: 3},
{id: 4, label: '250–500 MB', min: 256000, max: 512000, sortIndex: 4},
{id: 5, label: '0.5–1 GB', min: 512000, max: 1048576, sortIndex: 5},
{id: 6, label: '1–2 GB', min: 1048576, max: 2097152, sortIndex: 6},
{id: 7, label: '5+ GB', min: 5242880, max: Infinity, sortIndex: 7}
];
export const PAGE_COUNT_RANGES: readonly RangeConfig[] = [
{id: 0, label: '< 50 pages', min: 0, max: 50, sortIndex: 0},
{id: 1, label: '50–100 pages', min: 50, max: 100, sortIndex: 1},
{id: 2, label: '100–200 pages', min: 100, max: 200, sortIndex: 2},
{id: 3, label: '200–400 pages', min: 200, max: 400, sortIndex: 3},
{id: 4, label: '400–600 pages', min: 400, max: 600, sortIndex: 4},
{id: 5, label: '600–1000 pages', min: 600, max: 1000, sortIndex: 5},
{id: 6, label: '1000+ pages', min: 1000, max: Infinity, sortIndex: 6}
];
export const MATCH_SCORE_RANGES: readonly RangeConfig[] = [
{id: 0, min: 0.95, max: 1.01, label: 'Outstanding (95–100%)', sortIndex: 0},
{id: 1, min: 0.90, max: 0.95, label: 'Excellent (90–94%)', sortIndex: 1},
{id: 2, min: 0.80, max: 0.90, label: 'Great (80–89%)', sortIndex: 2},
{id: 3, min: 0.70, max: 0.80, label: 'Good (70–79%)', sortIndex: 3},
{id: 4, min: 0.50, max: 0.70, label: 'Fair (50–69%)', sortIndex: 4},
{id: 5, min: 0.30, max: 0.50, label: 'Weak (30–49%)', sortIndex: 5},
{id: 6, min: 0.00, max: 0.30, label: 'Poor (0–29%)', sortIndex: 6}
];
export const AGE_RATING_OPTIONS: readonly RangeConfig[] = [
{id: 0, min: 0, max: 1, label: 'All Ages', sortIndex: 0},
{id: 6, min: 6, max: 7, label: '6+', sortIndex: 1},
{id: 10, min: 10, max: 11, label: '10+', sortIndex: 2},
{id: 13, min: 13, max: 14, label: '13+', sortIndex: 3},
{id: 16, min: 16, max: 17, label: '16+', sortIndex: 4},
{id: 18, min: 18, max: 19, label: '18+', sortIndex: 5},
{id: 21, min: 21, max: 22, label: '21+', sortIndex: 6}
];
export const CONTENT_RATING_LABELS: Readonly<Record<string, string>> = {
'EVERYONE': 'Everyone',
'TEEN': 'Teen',
'MATURE': 'Mature',
'ADULT': 'Adult',
'EXPLICIT': 'Explicit'
};
export const readStatusLabels = READ_STATUS_LABELS;
export const ratingRanges = RATING_RANGES_5;
export const ratingOptions10 = RATING_OPTIONS_10;
export const fileSizeRanges = FILE_SIZE_RANGES;
export const pageCountRanges = PAGE_COUNT_RANGES;
export const matchScoreRanges = MATCH_SCORE_RANGES;
export const NUMERIC_ID_FILTER_TYPES = new Set<FilterType>([
'personalRating', 'matchScore', 'fileSize', 'amazonRating',
'goodreadsRating', 'hardcoverRating', 'pageCount', 'library', 'shelf',
'ageRating'
]);
export const FILTER_LABELS: Readonly<Record<FilterType, string>> = {
author: 'Author',
category: 'Genre',
series: 'Series',
bookType: 'File Format',
readStatus: 'Read Status',
personalRating: 'Personal Rating',
publisher: 'Publisher',
matchScore: 'Metadata Match Score',
library: 'Library',
shelf: 'Shelf',
shelfStatus: 'Shelf Status',
tag: 'Tag',
publishedDate: 'Published Year',
fileSize: 'File Size',
amazonRating: 'Amazon Rating',
goodreadsRating: 'Goodreads Rating',
hardcoverRating: 'Hardcover Rating',
language: 'Language',
pageCount: 'Page Count',
mood: 'Mood',
ageRating: 'Age Rating',
contentRating: 'Content Rating',
narrator: 'Narrator',
comicCharacter: 'Comic Character',
comicTeam: 'Comic Team',
comicLocation: 'Comic Location',
comicCreator: 'Comic Creator'
};
// ============================================================================
// FILTER EXTRACTORS
// ============================================================================
const findInRange = (value: number | null | undefined, ranges: readonly RangeConfig[]): FilterValue[] => {
if (value == null) return [];
const match = ranges.find(r => value >= r.min && value < r.max);
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
};
const findExactRating10 = (rating: number | undefined): FilterValue[] => {
if (!rating || rating < 1 || rating > 10) return [];
const match = RATING_OPTIONS_10.find(r => r.id === rating);
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
};
const normalizeMatchScore = (score: number | null | undefined): number | null => {
if (score == null) return null;
return score > 1 ? score / 100 : score;
};
const extractStringsAsFilters = (values: string[] | undefined): FilterValue[] =>
values?.map(name => ({id: name, name})) ?? [];
const extractSingleString = (value: string | undefined | null): FilterValue[] =>
value ? [{id: value, name: value}] : [];
const findExactAgeRating = (ageRating: number | null | undefined): FilterValue[] => {
if (ageRating == null) return [];
const match = AGE_RATING_OPTIONS.find(r => r.id === ageRating);
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
};
export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>, (book: Book) => FilterValue[]>> = {
author: (book) => extractStringsAsFilters(book.metadata?.authors),
category: (book) => extractStringsAsFilters(book.metadata?.categories),
series: (book) => extractSingleString(book.metadata?.seriesName?.trim()),
bookType: (book) => book.isPhysical ? [{id: 'PHYSICAL', name: 'PHYSICAL'}] : extractSingleString(book.primaryFile?.bookType),
readStatus: (book) => {
const status = book.readStatus ?? ReadStatus.UNSET;
const validStatus = status in READ_STATUS_LABELS ? status : ReadStatus.UNSET;
return [{id: validStatus, name: READ_STATUS_LABELS[validStatus]}];
},
personalRating: (book) => findExactRating10(book.personalRating ?? undefined),
publisher: (book) => extractSingleString(book.metadata?.publisher),
matchScore: (book) => findInRange(normalizeMatchScore(book.metadataMatchScore), MATCH_SCORE_RANGES),
shelf: (book) => book.shelves?.map(s => ({id: s.id, name: s.name})) ?? [],
shelfStatus: (book) => {
const isShelved = (book.shelves?.length ?? 0) > 0;
return [{id: isShelved ? 'shelved' : 'unshelved', name: isShelved ? 'Shelved' : 'Unshelved'}];
},
tag: (book) => extractStringsAsFilters(book.metadata?.tags),
publishedDate: (book) => {
const date = book.metadata?.publishedDate;
if (!date) return [];
const year = new Date(date).getFullYear().toString();
return [{id: year, name: year}];
},
fileSize: (book) => findInRange(book.fileSizeKb, FILE_SIZE_RANGES),
amazonRating: (book) => findInRange(book.metadata?.amazonRating, RATING_RANGES_5),
goodreadsRating: (book) => findInRange(book.metadata?.goodreadsRating, RATING_RANGES_5),
hardcoverRating: (book) => findInRange(book.metadata?.hardcoverRating, RATING_RANGES_5),
language: (book) => extractSingleString(book.metadata?.language),
pageCount: (book) => findInRange(book.metadata?.pageCount, PAGE_COUNT_RANGES),
mood: (book) => extractStringsAsFilters(book.metadata?.moods),
ageRating: (book) => findExactAgeRating(book.metadata?.ageRating),
contentRating: (book) => {
const rating = book.metadata?.contentRating;
if (!rating) return [];
const label = CONTENT_RATING_LABELS[rating] ?? rating;
return [{id: rating, name: label}];
},
narrator: (book) => extractSingleString(book.metadata?.narrator),
comicCharacter: (book) => extractStringsAsFilters(book.metadata?.comicMetadata?.characters),
comicTeam: (book) => extractStringsAsFilters(book.metadata?.comicMetadata?.teams),
comicLocation: (book) => extractStringsAsFilters(book.metadata?.comicMetadata?.locations),
comicCreator: (book) => {
const comic = book.metadata?.comicMetadata;
if (!comic) return [];
const creators: FilterValue[] = [];
const roleLabels: Record<string, string> = {
penciller: 'Penciller', inker: 'Inker', colorist: 'Colorist',
letterer: 'Letterer', coverArtist: 'Cover Artist', editor: 'Editor'
};
const roles: [string[] | undefined, string][] = [
[comic.pencillers, 'penciller'],
[comic.inkers, 'inker'],
[comic.colorists, 'colorist'],
[comic.letterers, 'letterer'],
[comic.coverArtists, 'coverArtist'],
[comic.editors, 'editor']
];
for (const [names, role] of roles) {
if (names) {
for (const name of names) {
creators.push({id: `${name}:${role}`, name: `${name} (${roleLabels[role]})`});
}
}
}
return creators;
}
};
// Translation key for each FilterType — used by UI components to translate filter labels
export const FILTER_LABEL_KEYS: Readonly<Record<FilterType, string>> = {
author: 'book.filter.labels.author',
category: 'book.filter.labels.category',
series: 'book.filter.labels.series',
bookType: 'book.filter.labels.bookType',
readStatus: 'book.filter.labels.readStatus',
personalRating: 'book.filter.labels.personalRating',
publisher: 'book.filter.labels.publisher',
matchScore: 'book.filter.labels.matchScore',
library: 'book.filter.labels.library',
shelf: 'book.filter.labels.shelf',
shelfStatus: 'book.filter.labels.shelfStatus',
tag: 'book.filter.labels.tag',
publishedDate: 'book.filter.labels.publishedDate',
fileSize: 'book.filter.labels.fileSize',
amazonRating: 'book.filter.labels.amazonRating',
goodreadsRating: 'book.filter.labels.goodreadsRating',
hardcoverRating: 'book.filter.labels.hardcoverRating',
language: 'book.filter.labels.language',
pageCount: 'book.filter.labels.pageCount',
mood: 'book.filter.labels.mood',
ageRating: 'book.filter.labels.ageRating',
contentRating: 'book.filter.labels.contentRating',
narrator: 'book.filter.labels.narrator',
comicCharacter: 'book.filter.labels.comicCharacter',
comicTeam: 'book.filter.labels.comicTeam',
comicLocation: 'book.filter.labels.comicLocation',
comicCreator: 'book.filter.labels.comicCreator'
};
export const READ_STATUS_LABEL_KEYS: Readonly<Record<ReadStatus, string>> = {
[ReadStatus.UNREAD]: 'book.filter.readStatus.unread',
[ReadStatus.READING]: 'book.filter.readStatus.reading',
[ReadStatus.RE_READING]: 'book.filter.readStatus.reReading',
[ReadStatus.PARTIALLY_READ]: 'book.filter.readStatus.partiallyRead',
[ReadStatus.PAUSED]: 'book.filter.readStatus.paused',
[ReadStatus.READ]: 'book.filter.readStatus.read',
[ReadStatus.WONT_READ]: 'book.filter.readStatus.wontRead',
[ReadStatus.ABANDONED]: 'book.filter.readStatus.abandoned',
[ReadStatus.UNSET]: 'book.filter.readStatus.unset'
};
export const CONTENT_RATING_LABEL_KEYS: Readonly<Record<string, string>> = {
'EVERYONE': 'book.filter.contentRating.everyone',
'TEEN': 'book.filter.contentRating.teen',
'MATURE': 'book.filter.contentRating.mature',
'ADULT': 'book.filter.contentRating.adult',
'EXPLICIT': 'book.filter.contentRating.explicit'
};
export const SHELF_STATUS_LABEL_KEYS: Readonly<Record<string, string>> = {
'shelved': 'book.filter.shelfStatus.shelved',
'unshelved': 'book.filter.shelfStatus.unshelved'
};
export const COMIC_ROLE_LABEL_KEYS: Readonly<Record<string, string>> = {
penciller: 'book.filter.comicRoles.penciller',
inker: 'book.filter.comicRoles.inker',
colorist: 'book.filter.comicRoles.colorist',
letterer: 'book.filter.comicRoles.letterer',
coverArtist: 'book.filter.comicRoles.coverArtist',
editor: 'book.filter.comicRoles.editor'
};
export const FILTER_CONFIGS: Readonly<Record<Exclude<FilterType, 'library'>, Omit<FilterConfig, 'extractor'>>> = {
author: {label: 'Author', sortMode: 'count'},
category: {label: 'Genre', sortMode: 'count'},
series: {label: 'Series', sortMode: 'count'},
bookType: {label: 'Book Type', sortMode: 'count'},
readStatus: {label: 'Read Status', sortMode: 'count'},
personalRating: {label: 'Personal Rating', sortMode: 'sortIndex', isNumericId: true},
publisher: {label: 'Publisher', sortMode: 'count'},
matchScore: {label: 'Metadata Match Score', sortMode: 'sortIndex', isNumericId: true},
shelf: {label: 'Shelf', sortMode: 'count', isNumericId: true},
shelfStatus: {label: 'Shelf Status', sortMode: 'count'},
tag: {label: 'Tag', sortMode: 'count'},
publishedDate: {label: 'Published Year', sortMode: 'count'},
fileSize: {label: 'File Size', sortMode: 'sortIndex', isNumericId: true},
amazonRating: {label: 'Amazon Rating', sortMode: 'sortIndex', isNumericId: true},
goodreadsRating: {label: 'Goodreads Rating', sortMode: 'sortIndex', isNumericId: true},
hardcoverRating: {label: 'Hardcover Rating', sortMode: 'sortIndex', isNumericId: true},
language: {label: 'Language', sortMode: 'count'},
pageCount: {label: 'Page Count', sortMode: 'sortIndex', isNumericId: true},
mood: {label: 'Mood', sortMode: 'count'},
ageRating: {label: 'Age Rating', sortMode: 'sortIndex', isNumericId: true},
contentRating: {label: 'Content Rating', sortMode: 'count'},
narrator: {label: 'Narrator', sortMode: 'count'},
comicCharacter: {label: 'Comic Character', sortMode: 'count'},
comicTeam: {label: 'Comic Team', sortMode: 'count'},
comicLocation: {label: 'Comic Location', sortMode: 'count'},
comicCreator: {label: 'Comic Creator', sortMode: 'count'}
};
@@ -0,0 +1,168 @@
import {computed, inject, Injectable, Signal} from '@angular/core';
import {Book} from '../../../model/book.model';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {BookService} from '../../../service/book.service';
import {LibraryService} from '../../../service/library.service';
import {BookRuleEvaluatorService} from '../../../../magic-shelf/service/book-rule-evaluator.service';
import {GroupRule} from '../../../../magic-shelf/component/magic-shelf-component';
import {EntityType} from '../book-browser.component';
import {Filter, FILTER_CONFIGS, FILTER_EXTRACTORS, FilterType, FilterValue, NUMERIC_ID_FILTER_TYPES, SortMode} from './book-filter.config';
import {filterBooksByFilters} from '../filters/sidebar-filter';
import {BookFilterMode} from '../../../../settings/user-management/user.service';
const MAX_FILTER_ITEMS = 100;
@Injectable({providedIn: 'root'})
export class BookFilterService {
private readonly bookService = inject(BookService);
private readonly libraryService = inject(LibraryService);
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
createFilterSignals(
entity: Signal<Library | Shelf | MagicShelf | null>,
entityType: Signal<EntityType>,
activeFilters: Signal<Record<string, unknown[]> | null>,
filterMode: Signal<BookFilterMode>
): Record<FilterType, Signal<Filter[]>> {
const filteredBooks = computed(() =>
this.filterBooksByEntity(this.bookService.books(), entity(), entityType())
);
const signals = {} as Record<FilterType, Signal<Filter[]>>;
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
const filterType = type as Exclude<FilterType, 'library'>;
signals[filterType] = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
});
}
signals.library = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
const libraries = this.libraryService.libraries();
const libraryMap = new Map(
libraries
.filter(lib => lib.id !== undefined)
.map(lib => [lib.id!, lib.name])
);
const filterMap = new Map<number, Filter>();
for (const book of books) {
if (book.libraryId == null) continue;
if (!filterMap.has(book.libraryId)) {
filterMap.set(book.libraryId, {
value: {
id: book.libraryId,
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
},
bookCount: 0
});
}
filterMap.get(book.libraryId)!.bookCount++;
}
return this.sortFiltersByCount(Array.from(filterMap.values()));
});
return signals;
}
filterBooksByEntity(
books: Book[],
entity: Library | Shelf | MagicShelf | null,
entityType: EntityType
): Book[] {
if (!entity) return books;
switch (entityType) {
case EntityType.LIBRARY:
return books.filter(book => book.libraryId === (entity as Library).id);
case EntityType.SHELF: {
const shelfId = (entity as Shelf).id;
return books.filter(book => book.shelves?.some(s => s.id === shelfId));
}
case EntityType.MAGIC_SHELF:
return this.filterByMagicShelf(books, entity as MagicShelf);
default:
return books;
}
}
processFilterValue(key: string, value: unknown): unknown {
if (NUMERIC_ID_FILTER_TYPES.has(key as FilterType) && typeof value === 'string') {
return Number(value);
}
return value;
}
isNumericFilter(filterType: string): boolean {
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
}
private buildAndSortFilters(
books: Book[],
extractor: (book: Book) => FilterValue[],
sortMode: SortMode
): Filter[] {
const filterMap = new Map<unknown, Filter>();
for (const book of books) {
for (const item of extractor(book)) {
const id = item.id;
if (!filterMap.has(id)) {
filterMap.set(id, {value: item, bookCount: 0});
}
filterMap.get(id)!.bookCount++;
}
}
const filters = Array.from(filterMap.values());
const sorted = sortMode === 'sortIndex'
? this.sortFiltersBySortIndex(filters)
: this.sortFiltersByCount(filters);
return sorted.slice(0, MAX_FILTER_ITEMS);
}
private sortFiltersByCount(filters: Filter[]): Filter[] {
return filters.sort((a, b) => {
if (b.bookCount !== a.bookCount) return b.bookCount - a.bookCount;
return this.compareNames(a, b);
});
}
private sortFiltersBySortIndex(filters: Filter[]): Filter[] {
return filters.sort((a, b) => {
const aIndex = (a.value as { sortIndex?: number }).sortIndex ?? 999;
const bIndex = (b.value as { sortIndex?: number }).sortIndex ?? 999;
if (aIndex !== bIndex) return aIndex - bIndex;
return this.compareNames(a, b);
});
}
private compareNames(a: Filter, b: Filter): number {
const aName = String((a.value as { name?: string }).name ?? '');
const bName = String((b.value as { name?: string }).name ?? '');
return aName.localeCompare(bName);
}
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
if (!magicShelf.filterJson) return [];
try {
const groupRule = JSON.parse(magicShelf.filterJson) as GroupRule;
return books.filter(book => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule, books));
} catch {
console.warn('Invalid filterJson for MagicShelf');
return [];
}
}
}
@@ -0,0 +1,95 @@
import {computed, Injectable, signal} from '@angular/core';
import {Book} from '../../model/book.model';
export interface CheckboxClickEvent {
index: number;
book: Book;
selected: boolean;
shiftKey: boolean;
}
@Injectable({providedIn: 'root'})
export class BookSelectionService {
private readonly _selectedBooks = signal<Set<number>>(new Set());
readonly selectedBooks = this._selectedBooks.asReadonly();
readonly selectedCount = computed(() => this._selectedBooks().size);
private currentBooks: Book[] = [];
private lastSelectedIndex: number | null = null;
setCurrentBooks(books: Book[]): void {
this.currentBooks = books;
}
selectBook(book: Book): void {
this._selectedBooks.update(current => {
const next = new Set(current);
if (book.seriesBooks) {
book.seriesBooks.forEach(seriesBook => next.add(seriesBook.id));
} else {
next.add(book.id);
}
return next;
});
}
deselectBook(book: Book): void {
this._selectedBooks.update(current => {
const next = new Set(current);
if (book.seriesBooks) {
book.seriesBooks.forEach(seriesBook => next.delete(seriesBook.id));
} else {
next.delete(book.id);
}
return next;
});
}
handleCheckboxClick(event: CheckboxClickEvent): void {
const {index, book, selected, shiftKey} = event;
if (!shiftKey || this.lastSelectedIndex === null) {
this.handleBookSelection(book, selected);
this.lastSelectedIndex = index;
} else {
const start = Math.min(this.lastSelectedIndex, index);
const end = Math.max(this.lastSelectedIndex, index);
const isUnselectingRange = !selected;
for (let i = start; i <= end; i++) {
const rangeBook = this.currentBooks[i];
if (!rangeBook) continue;
this.handleBookSelection(rangeBook, !isUnselectingRange);
}
}
}
handleBookSelection(book: Book, selected: boolean): void {
if (selected) {
this.selectBook(book);
} else {
this.deselectBook(book);
}
}
selectAll(): void {
if (!this.currentBooks || this.currentBooks.length === 0) return;
this._selectedBooks.update(current => {
const next = new Set(current);
for (const book of this.currentBooks) {
next.add(book.id);
}
return next;
});
}
deselectAll(): void {
this._selectedBooks.set(new Set());
this.lastSelectedIndex = null;
}
setSelectedBooks(bookIds: Set<number>): void {
this._selectedBooks.set(new Set(bookIds));
}
}
@@ -0,0 +1,120 @@
<ng-container *transloco="let t; prefix: 'book.table'">
<p-table
[value]="books"
[columns]="visibleColumns"
[dataKey]="'id'"
[resizableColumns]="true"
[reorderableColumns]="true"
columnResizeMode="expand"
[rowTrackBy]="trackByBookId"
[metaKeySelection]="true"
showGridlines
stripedRows
[scrollable]="true"
[scrollHeight]="scrollHeight"
[virtualScroll]="true"
[virtualScrollItemSize]="46"
[(selection)]="selectedBooks"
(onHeaderCheckboxToggle)="onHeaderCheckboxToggle($event)"
(onRowSelect)="onRowSelect($event)"
(onRowUnselect)="onRowUnselect($event)"
>
<ng-template pTemplate="header">
<tr>
<th>
<p-tableHeaderCheckbox/>
</th>
<th></th>
<th class="cover-header-cell"></th>
@for (col of visibleColumns; track col.field) {
<th pResizableColumn>{{ col.header }}</th>
}
</tr>
</ng-template>
<ng-template pTemplate="body" let-book>
@if (book.metadata; as metadata) {
<tr style="height:46px">
<td>
<p-tableCheckbox [value]="book"/>
</td>
<td class="cell-center">
<p-button
[icon]="isMetadataFullyLocked(metadata) ? 'pi pi-lock' : 'pi pi-lock-open'"
[severity]="isMetadataFullyLocked(metadata) ? 'danger' : 'success'"
[text]="true"
[title]="isMetadataFullyLocked(metadata) ? t('locked') : t('unlocked')"
size="small"
[style]="{ width: '1.5rem', height: '1.5rem', padding: '0', fontSize: '0.75rem' }"
(click)="toggleMetadataLock(metadata)">
</p-button>
</td>
<td>
<a [routerLink]="urlHelper.getBookUrl(book)">
<img
[attr.src]="urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn)"
[alt]="t('bookCoverAlt')"
class="cover-thumbnail"
tooltipPosition="left"
[pTooltip]="tooltipContent"
tooltipStyleClass="cover-tooltip"
/>
</a>
<ng-template #tooltipContent>
<div class="tooltip-cover-container">
<img
[attr.src]="urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn)"
[alt]="t('bookCoverAlt')"
class="tooltip-cover-image"
/>
<em class="tooltip-cover-title">{{ metadata.title }}</em>
</div>
</ng-template>
</td>
@for (col of visibleColumns; track col.field) {
@if (col.field === 'readStatus') {
<td class="cell-status">
@if (shouldShowStatusIcon(book.readStatus)) {
<div class="read-status-indicator"
[ngClass]="getReadStatusClass(book.readStatus)"
[pTooltip]="t('statusPrefix') + getReadStatusTooltip(book.readStatus)"
tooltipPosition="top">
<i [class]="getReadStatusIcon(book.readStatus)"></i>
</div>
}
</td>
} @else if (col.field === 'amazonRating' || col.field === 'goodreadsRating' || col.field === 'hardcoverRating' || col.field == 'ranobedbRating') {
<td class="cell-rating">
<span class="rating-wrapper">
<p-rating
[(ngModel)]="metadata[col.field]"
readonly
stars="5"
[style.--p-rating-icon-active-color]="getStarColor(metadata[col.field])"
></p-rating>
@if (metadata[col.field] != null) {
<span>({{ metadata[col.field]?.toFixed(1) }})</span>
}
</span>
</td>
} @else {
<td
[title]="getCellValue(metadata, book, col.field)"
class="cell-text">
@if(['title', 'authors', 'publisher', 'seriesName', 'categories', 'language'].includes(col.field)) {
@for (item of getCellClickableValue(metadata, book, col.field); track $index; let isLast = $last) {
<a [routerLink]="item.url" class="cell-link">
{{ item.anchor }}</a>@if (!isLast) {<span>, </span>}
}
} @else {
{{ getCellValue(metadata, book, col.field) }}
}
</td>
}
}
</tr>
}
</ng-template>
</p-table>
</ng-container>
@@ -0,0 +1,110 @@
.read-status-indicator {
display: flex;
align-items: center;
justify-content: center;
font-size: 0.875rem;
font-weight: bold;
width: 20px;
height: 20px;
margin: 0 auto;
}
.status-read {
color: #22c55e;
}
.status-reading {
color: #3b82f6;
}
.status-re-reading {
color: #06b6d4;
}
.status-partially-read {
color: #f59e0b;
}
.status-paused {
color: #eab308;
}
.status-abandoned {
color: #ef4444;
}
.status-wont-read {
color: #ec4899;
}
.cover-header-cell {
max-width: 3.5rem;
min-width: 3.5rem;
}
.cell-center {
text-align: center;
}
.cover-thumbnail {
width: 1.75rem;
height: 1.75rem;
}
.tooltip-cover-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
}
.tooltip-cover-image {
width: 40rem;
height: auto;
}
.tooltip-cover-title {
font-size: 0.875rem;
text-wrap: balance;
text-align: center;
}
.cell-status {
text-align: center;
min-width: 4rem;
max-width: 4rem;
}
.cell-rating {
min-width: 10rem;
max-width: 10rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rating-wrapper {
display: flex;
align-items: center;
gap: 0.25rem;
}
.cell-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: right;
min-width: 6rem;
max-width: 12rem;
}
.cell-link {
&:hover {
text-decoration: underline;
color: #60a5fa;
}
}
::ng-deep .cover-tooltip > .p-tooltip-text {
padding: 0.25rem;
}
@@ -0,0 +1,348 @@
import {Component, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output} from '@angular/core';
import {TableModule} from 'primeng/table';
import {DatePipe, NgClass} from '@angular/common';
import {Rating} from 'primeng/rating';
import {FormsModule} from '@angular/forms';
import {TooltipModule} from "primeng/tooltip";
import {Book, BookMetadata, ReadStatus} from '../../../model/book.model';
import {SortOption} from '../../../model/sort.model';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {Button} from 'primeng/button';
import {BookService} from '../../../service/book.service';
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
import {MessageService} from 'primeng/api';
import {RouterLink} from '@angular/router';
import {Subject} from 'rxjs';
import {UserService} from '../../../../settings/user-management/user.service';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@Component({
selector: 'app-book-table',
standalone: true,
templateUrl: './book-table.component.html',
imports: [
TableModule,
Rating,
FormsModule,
Button,
TooltipModule,
NgClass,
RouterLink,
TranslocoDirective
],
styleUrls: ['./book-table.component.scss'],
providers: [DatePipe]
})
export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
selectedBooks: Book[] = [];
selectedBookIds = new Set<number>();
@Output() selectedBooksChange = new EventEmitter<Set<number>>();
@Input() books: Book[] = [];
@Input() sortOption: SortOption | null = null;
@Input() visibleColumns: { field: string; header: string }[] = [];
@Input() preselectedBookIds = new Set<number>();
protected urlHelper = inject(UrlHelperService);
private bookService = inject(BookService);
private bookMetadataManageService = inject(BookMetadataManageService);
private messageService = inject(MessageService);
private userService = inject(UserService);
private datePipe = inject(DatePipe);
private readStatusHelper = inject(ReadStatusHelper);
private readonly t = inject(TranslocoService);
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
private destroy$ = new Subject<void>();
readonly allColumns: { field: string; header: string }[] = [
{field: 'readStatus', header: this.t.translate('book.columnPref.columns.readStatus')},
{field: 'title', header: this.t.translate('book.columnPref.columns.title')},
{field: 'authors', header: this.t.translate('book.columnPref.columns.authors')},
{field: 'publisher', header: this.t.translate('book.columnPref.columns.publisher')},
{field: 'seriesName', header: this.t.translate('book.columnPref.columns.seriesName')},
{field: 'seriesNumber', header: this.t.translate('book.columnPref.columns.seriesNumber')},
{field: 'categories', header: this.t.translate('book.columnPref.columns.categories')},
{field: 'publishedDate', header: this.t.translate('book.columnPref.columns.publishedDate')},
{field: 'lastReadTime', header: this.t.translate('book.columnPref.columns.lastReadTime')},
{field: 'addedOn', header: this.t.translate('book.columnPref.columns.addedOn')},
{field: 'fileName', header: this.t.translate('book.columnPref.columns.fileName')},
{field: 'fileSizeKb', header: this.t.translate('book.columnPref.columns.fileSizeKb')},
{field: 'language', header: this.t.translate('book.columnPref.columns.language')},
{field: 'isbn', header: this.t.translate('book.columnPref.columns.isbn')},
{field: 'pageCount', header: this.t.translate('book.columnPref.columns.pageCount')},
{field: 'amazonRating', header: this.t.translate('book.columnPref.columns.amazonRating')},
{field: 'amazonReviewCount', header: this.t.translate('book.columnPref.columns.amazonReviewCount')},
{field: 'goodreadsRating', header: this.t.translate('book.columnPref.columns.goodreadsRating')},
{field: 'goodreadsReviewCount', header: this.t.translate('book.columnPref.columns.goodreadsReviewCount')},
{field: 'hardcoverRating', header: this.t.translate('book.columnPref.columns.hardcoverRating')},
{field: 'hardcoverReviewCount', header: this.t.translate('book.columnPref.columns.hardcoverReviewCount')},
{field: 'ranobedbRating', header: this.t.translate('book.columnPref.columns.ranobedbRating')},
];
scrollHeight = 'calc(100dvh - 160px)';
ngOnInit(): void {
const user = this.userService.currentUser();
if (user) {
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
}
this.selectedBookIds = this.preselectedBookIds;
this.selectedBooks = this.bookService.getBooksByIds([...this.selectedBookIds]);
this.setScrollHeight();
window.addEventListener('resize', this.setScrollHeight.bind(this));
}
setScrollHeight() {
const isMobile = window.innerWidth <= 768;
this.scrollHeight = isMobile
? 'calc(100dvh - 125px)'
: 'calc(100dvh - 150px)';
}
ngOnChanges() {
const wrapperElements: HTMLCollection = document.getElementsByClassName('p-virtualscroller');
Array.prototype.forEach.call(wrapperElements, function (wrapperElement) {
wrapperElement.style["height"] = 'calc(100dvh - 160px)';
});
}
selectAllBooks(): void {
this.selectedBookIds = new Set(this.books.map(book => book.id));
this.selectedBooks = [...this.books];
this.selectedBooksChange.emit(this.selectedBookIds);
}
clearSelectedBooks(): void {
this.selectedBookIds.clear();
this.selectedBooks = [];
this.selectedBooksChange.emit(this.selectedBookIds);
}
onRowSelect(event: { data?: Book | Book[] }): void {
if (event.data && !Array.isArray(event.data)) {
this.selectedBookIds.add(event.data.id);
this.selectedBooksChange.emit(this.selectedBookIds);
}
}
onRowUnselect(event: { data?: Book | Book[] }): void {
if (event.data && !Array.isArray(event.data)) {
this.selectedBookIds.delete(event.data.id);
this.selectedBooksChange.emit(this.selectedBookIds);
}
}
onHeaderCheckboxToggle(event: { checked: boolean }): void {
if (event.checked) {
this.selectedBooks = [...this.books];
this.selectedBookIds = new Set(this.books.map(book => book.id));
} else {
this.clearSelectedBooks();
}
this.selectedBooksChange.emit(this.selectedBookIds);
}
getStarColor(rating: number): string {
if (rating >= 4.5) {
return 'rgb(34, 197, 94)';
} else if (rating >= 4) {
return 'rgb(52, 211, 153)';
} else if (rating >= 3.5) {
return 'rgb(234, 179, 8)';
} else if (rating >= 2.5) {
return 'rgb(249, 115, 22)';
} else {
return 'rgb(239, 68, 68)';
}
}
getAuthorNames(authors: string[]): string {
return authors?.join(', ') || '';
}
getGenres(genres: string[]) {
return genres?.join(', ') || '';
}
trackByBookId(index: number, book: Book): number {
return book.id;
}
isMetadataFullyLocked(metadata: BookMetadata): boolean {
const lockedKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
if (lockedKeys.length === 0) return false;
return lockedKeys.every(key => metadata[key] === true);
}
formatFileSize(kb?: number): string {
if (kb == null || isNaN(kb)) return '-';
const mb = kb / 1024;
return mb >= 1 ? `${mb.toFixed(1)} MB` : `${mb.toFixed(2)} MB`;
}
getReadStatusIcon(readStatus: ReadStatus | undefined): string {
return this.readStatusHelper.getReadStatusIcon(readStatus);
}
getReadStatusClass(readStatus: ReadStatus | undefined): string {
return this.readStatusHelper.getReadStatusClass(readStatus);
}
getReadStatusTooltip(readStatus: ReadStatus | undefined): string {
return this.readStatusHelper.getReadStatusTooltip(readStatus);
}
shouldShowStatusIcon(readStatus: ReadStatus | undefined): boolean {
return this.readStatusHelper.shouldShowStatusIcon(readStatus);
}
getCellClickableValue(metadata: BookMetadata, book: Book, field: string) {
const filterKeys: Record<string, string> = {
'authors': 'author',
'publisher': 'publisher',
'categories': 'category',
'language': 'language',
'title': 'title',
'isbn': 'isbn'
} as const;
let data: string[] = [metadata[field] as string];
switch (field) {
case 'title':
return [
{
url: this.urlHelper.getBookUrl(book),
anchor: metadata.title ?? book.fileName
}
];
case 'categories':
data = metadata.categories ?? [];
break;
case 'authors':
data = metadata.authors ?? [];
break;
case 'seriesName':
return [
{
url: this.urlHelper.filterBooksBy('series', metadata.seriesName ?? ''),
anchor: metadata.seriesName
}
]
case 'isbn':
return [
{
url: '',
anchor: this.getCellValue(metadata, book, 'isbn')
}
];
}
return data.map(item => {
return {
url: this.urlHelper.filterBooksBy(filterKeys[field] ?? field, item),
anchor: item
}
});
}
getCellValue(metadata: BookMetadata, book: Book, field: string): string | number {
switch (field) {
case 'readStatus':
return this.readStatusHelper.getReadStatusTooltip(book?.readStatus);
case 'title':
return metadata.title ?? '';
case 'authors':
return this.getAuthorNames(metadata.authors!);
case 'publisher':
return metadata.publisher ?? '';
case 'seriesName':
return metadata.seriesName ?? '';
case 'seriesNumber':
return metadata.seriesNumber ?? '';
case 'categories':
return this.getGenres(metadata.categories!);
case 'publishedDate':
return metadata.publishedDate ? this.datePipe.transform(metadata.publishedDate, 'dd-MMM-yyyy') ?? '' : '';
case 'lastReadTime':
return book.lastReadTime ? this.datePipe.transform(book.lastReadTime, 'dd-MMM-yyyy') ?? '' : '';
case 'addedOn':
return book.addedOn ? this.datePipe.transform(book.addedOn, 'dd-MMM-yyyy') ?? '' : '';
case 'fileName':
return book.primaryFile?.fileName ?? '';
case 'fileSizeKb':
return this.formatFileSize(book.fileSizeKb);
case 'language':
return metadata.language ?? '';
case 'pageCount':
return metadata.pageCount ?? '';
case 'amazonRating':
case 'goodreadsRating':
case 'hardcoverRating':
case 'ranobedbRating': {
const rating = metadata[field];
return typeof rating === 'number' ? rating.toFixed(1) : '';
}
case 'amazonReviewCount':
case 'goodreadsReviewCount':
case 'hardcoverReviewCount':
return metadata[field] ?? '';
case 'isbn':
return metadata.isbn13 || metadata.isbn10 || '';
default:
return '';
}
}
toggleMetadataLock(metadata: BookMetadata): void {
const lockKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
const allLocked = lockKeys.every(key => metadata[key] === true);
const lockAction = allLocked ? 'UNLOCK' : 'LOCK';
this.bookMetadataManageService.toggleAllLock(new Set([metadata.bookId]), lockAction).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedSummary') : this.t.translate('book.table.toast.metadataUnlockedSummary'),
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedDetail') : this.t.translate('book.table.toast.metadataUnlockedDetail'),
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedSummary') : this.t.translate('book.table.toast.unlockFailedSummary'),
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedDetail') : this.t.translate('book.table.toast.unlockFailedDetail'),
});
}
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
window.removeEventListener('resize', this.setScrollHeight.bind(this));
}
}
@@ -0,0 +1,92 @@
import {computed, inject, Injectable, signal} from '@angular/core';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
import {Book} from '../../model/book.model';
@Injectable({
providedIn: 'root'
})
export class CoverScalePreferenceService {
private readonly BASE_WIDTH = 135;
private readonly BASE_HEIGHT = 220;
private readonly TITLE_BAR_HEIGHT = 31;
private readonly DEBOUNCE_MS = 1000;
private readonly STORAGE_KEY = 'coverScalePreference';
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private readonly localStorageService = inject(LocalStorageService);
private readonly _scaleFactor = signal(1.0);
readonly scaleFactor = this._scaleFactor.asReadonly();
readonly currentCardSize = computed(() => ({
width: Math.round(this.BASE_WIDTH * this.scaleFactor()),
height: Math.round(this.BASE_HEIGHT * this.scaleFactor()),
}));
readonly gridColumnMinWidth = computed(() => `${this.currentCardSize().width}px`);
private saveTimeout: ReturnType<typeof setTimeout> | null = null;
private lastPersistedScale = 1.0;
constructor() {
const initialScale = this.loadScaleFromStorage();
this._scaleFactor.set(initialScale);
this.lastPersistedScale = initialScale;
}
setScale(scale: number): void {
this._scaleFactor.set(scale);
if (scale === this.lastPersistedScale) {
return;
}
this.scheduleSave(scale);
}
getCardHeight(_book: Book): number {
// Use uniform height for all book types to ensure smooth virtual scrolling.
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
// cannot accurately estimate positions when item heights vary.
return this.currentCardSize().height;
}
private scheduleSave(scale: number): void {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout);
}
this.saveTimeout = setTimeout(() => {
this.saveScalePreference(scale);
}, this.DEBOUNCE_MS);
}
private saveScalePreference(scale: number): void {
try {
this.localStorageService.set(this.STORAGE_KEY, scale);
this.lastPersistedScale = scale;
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.coverPref.toast.savedSummary'),
detail: this.t.translate('book.coverPref.toast.savedDetail', {scale: scale.toFixed(2)}),
life: 1500
});
} catch (e) {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.coverPref.toast.saveFailedSummary'),
detail: this.t.translate('book.coverPref.toast.saveFailedDetail'),
life: 3000
});
}
}
private loadScaleFromStorage(): number {
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
if (saved !== null && !isNaN(saved)) {
return saved;
}
return 1.0;
}
}
@@ -0,0 +1,74 @@
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingOptions10, ratingRanges} from './book-filter/book-filter.config';
export class FilterLabelHelper {
private static readonly FILTER_TYPE_MAP: Record<string, string> = {
author: 'Author',
category: 'Genre',
series: 'Series',
publisher: 'Publisher',
readStatus: 'Read Status',
personalRating: 'Personal Rating',
publishedDate: 'Year Published',
matchScore: 'Metadata Match Score',
language: 'Language',
bookType: 'Book Type',
shelfStatus: 'Shelf Status',
fileSize: 'File Size',
pageCount: 'Page Count',
amazonRating: 'Amazon Rating',
goodreadsRating: 'Goodreads Rating',
hardcoverRating: 'Hardcover Rating',
ranobedbRating: 'Ranobedb Rating',
mood: 'Mood',
tag: 'Tag',
};
static getFilterTypeName(filterType: string): string {
return this.FILTER_TYPE_MAP[filterType] || this.capitalize(filterType);
}
static getFilterDisplayValue(filterType: string, value: string | number): string {
const numericValue = typeof value === 'string' ? Number(value) : value;
switch (filterType.toLowerCase()) {
case 'filesize': {
const fileSizeRange = fileSizeRanges.find(r => r.id === numericValue);
if (fileSizeRange) return fileSizeRange.label;
return String(value);
}
case 'pagecount': {
const pageCountRange = pageCountRanges.find(r => r.id === numericValue);
if (pageCountRange) return pageCountRange.label;
return String(value);
}
case 'matchscore': {
const matchScoreRange = matchScoreRanges.find(r => r.id === numericValue);
if (matchScoreRange) return matchScoreRange.label;
return String(value);
}
case 'personalrating': {
const personalRating = ratingOptions10.find(r => r.id === numericValue);
if (personalRating) return personalRating.label;
return String(value);
}
case 'amazonrating':
case 'goodreadsrating':
case 'hardcoverrating': {
const ratingRange = ratingRanges.find(r => r.id === numericValue);
if (ratingRange) return ratingRange.label;
return String(value);
}
default:
return String(value);
}
}
private static capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}
@@ -0,0 +1,42 @@
import {Book} from '../../../model/book.model';
export function normalizeSearchTerm(str: string): string {
if (!str) return '';
// Normalize Unicode combining characters (e.g., é -> e)
let s = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
s = s.replace(/ø/gi, 'o')
.replace(/ł/gi, 'l')
.replace(/æ/gi, 'ae')
.replace(/œ/gi, 'oe')
.replace(/ß/g, 'ss');
s = s.replace(/[!@$%^&*_=|~`<>?/";']/g, '');
s = s.replace(/\s+/g, ' ').trim();
return s.toLowerCase();
}
export function filterBooksBySearchTerm(books: Book[], term: string): Book[] {
const normalizedTerm = normalizeSearchTerm(term || '').trim();
if (normalizedTerm.length < 2) {
return books;
}
return books.filter(book => {
const title = book.metadata?.title || '';
const series = book.metadata?.seriesName || '';
const authors = book.metadata?.authors || [];
const categories = book.metadata?.categories || [];
const isbn = book.metadata?.isbn10 || '';
const isbn13 = book.metadata?.isbn13 || '';
const fileName = book.primaryFile?.fileName || '';
const matchesTitle = normalizeSearchTerm(title).includes(normalizedTerm);
const matchesSeries = normalizeSearchTerm(series).includes(normalizedTerm);
const matchesAuthor = authors.some(author => normalizeSearchTerm(author).includes(normalizedTerm));
const matchesCategory = categories.some(category => normalizeSearchTerm(category).includes(normalizedTerm));
const matchesIsbn = normalizeSearchTerm(isbn).includes(normalizedTerm) || normalizeSearchTerm(isbn13).includes(normalizedTerm);
const matchesFileName = normalizeSearchTerm(fileName).includes(normalizedTerm);
return matchesTitle || matchesSeries || matchesAuthor || matchesCategory || matchesIsbn || matchesFileName;
});
}
@@ -0,0 +1,169 @@
import {effect, inject, Injectable, signal} from '@angular/core';
import {Book} from '../../../model/book.model';
import {MessageService} from 'primeng/api';
import {UserService} from '../../../../settings/user-management/user.service';
@Injectable({providedIn: 'root'})
export class SeriesCollapseFilter {
private static readonly PERSIST_DELAY_MS = 500;
private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService);
private readonly _seriesCollapsed = signal(false);
readonly seriesCollapsed = this._seriesCollapsed.asReadonly();
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
private persistTimeout: ReturnType<typeof setTimeout> | null = null;
constructor() {
effect(() => {
const user = this.userService.currentUser();
if (user) {
this.applyPreference();
}
});
}
setContext(type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF' | null, id: number | null): void {
if (type && id) {
this.currentContext = {type, id};
} else {
this.currentContext = null;
}
this.applyPreference();
}
setCollapsed(value: boolean): void {
this._seriesCollapsed.set(value);
this.schedulePersist(value);
}
private applyPreference(): void {
const user = this.userService.getCurrentUser();
const prefs = user?.userSettings?.entityViewPreferences;
let collapsed = false;
if (prefs) {
// Backward compatibility: check for old 'seriesCollapse' field
const legacyGlobalSeriesCollapse = (prefs.global as { seriesCollapse?: boolean }).seriesCollapse;
collapsed = prefs.global?.seriesCollapsed ?? legacyGlobalSeriesCollapse ?? false;
if (this.currentContext) {
const override = prefs.overrides?.find(o =>
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
);
if (override) {
const legacyOverrideSeriesCollapse = (override.preferences as { seriesCollapse?: boolean }).seriesCollapse;
if (override.preferences.seriesCollapsed !== undefined) {
collapsed = override.preferences.seriesCollapsed;
} else if (legacyOverrideSeriesCollapse !== undefined) {
collapsed = legacyOverrideSeriesCollapse;
}
}
}
}
if (this._seriesCollapsed() !== collapsed) {
this._seriesCollapsed.set(collapsed);
}
}
collapseBooks(books: Book[], forceExpandSeries?: boolean, isSeriesCollapsed: boolean = this.seriesCollapsed()): Book[] {
const shouldCollapse = forceExpandSeries ? false : isSeriesCollapsed;
if (!shouldCollapse || books.length === 0) return books;
const sourceBooks = [...books];
const seriesMap = new Map<string, Book[]>();
const collapsedBooks: Book[] = [];
for (const book of sourceBooks) {
const seriesName = book.metadata?.seriesName?.trim();
if (seriesName) {
if (!seriesMap.has(seriesName)) {
seriesMap.set(seriesName, []);
}
seriesMap.get(seriesName)!.push(book);
} else {
collapsedBooks.push(book);
}
}
for (const group of seriesMap.values()) {
const sortedGroup = group.slice().sort((a, b) => {
const aNum = a.metadata?.seriesNumber ?? Number.MAX_VALUE;
const bNum = b.metadata?.seriesNumber ?? Number.MAX_VALUE;
return aNum - bNum;
});
const firstBook = sortedGroup[0];
collapsedBooks.push({
...firstBook,
seriesBooks: group,
seriesCount: group.length
});
}
return collapsedBooks;
}
private schedulePersist(isCollapsed: boolean): void {
if (this.persistTimeout) {
clearTimeout(this.persistTimeout);
}
this.persistTimeout = setTimeout(() => {
this.persistCollapsePreference(isCollapsed);
}, SeriesCollapseFilter.PERSIST_DELAY_MS);
}
private persistCollapsePreference(isCollapsed: boolean): void {
const user = this.userService.getCurrentUser();
if (!user) return;
const prefs = structuredClone(user.userSettings.entityViewPreferences ?? {
global: {
sortKey: 'addedOn',
sortDir: 'DESC',
view: 'GRID',
coverSize: 1.0,
seriesCollapsed: false
},
overrides: []
});
if (!prefs.overrides) {
prefs.overrides = [];
}
if (this.currentContext) {
let override = prefs.overrides.find(o =>
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
);
if (!override) {
override = {
entityType: this.currentContext.type,
entityId: this.currentContext.id,
preferences: {
...prefs.global,
seriesCollapsed: isCollapsed
}
};
prefs.overrides.push(override);
} else {
override.preferences.seriesCollapsed = isCollapsed;
}
} else {
prefs.global.seriesCollapsed = isCollapsed;
}
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
this.messageService.add({
severity: 'success',
summary: 'Preference Saved',
detail: `Series collapse set to ${isCollapsed ? 'enabled' : 'disabled'}${this.currentContext ? ' for this view' : ' globally'}.`,
life: 1500
});
}
}
@@ -0,0 +1,58 @@
import {inject, Injectable, signal} from '@angular/core';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
@Injectable({
providedIn: 'root'
})
export class SidebarFilterTogglePrefService {
private readonly STORAGE_KEY = 'showSidebarFilter';
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private readonly localStorageService = inject(LocalStorageService);
private readonly _showFilter = signal(true);
readonly showFilter = this._showFilter.asReadonly();
constructor() {
const isNarrow = window.innerWidth <= 768;
this._showFilter.set(!isNarrow);
this.loadFromStorage();
}
toggle(): void {
this.setShowFilter(!this.showFilter());
}
setShowFilter(value: boolean): void {
if (this._showFilter() !== value) {
this._showFilter.set(value);
this.savePreference(value);
}
}
private savePreference(value: boolean): void {
try {
this.localStorageService.set(this.STORAGE_KEY, value);
} catch (e) {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.filterPref.toast.saveFailedSummary'),
detail: this.t.translate('book.filterPref.toast.saveFailedDetail'),
life: 3000
});
}
}
private loadFromStorage(): void {
const isNarrow = window.innerWidth <= 768;
if (isNarrow) {
this._showFilter.set(false);
} else {
const saved = this.localStorageService.get<boolean>(this.STORAGE_KEY);
this._showFilter.set(saved !== null ? saved : true);
}
}
}
@@ -0,0 +1,194 @@
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.config';
import {Book, ReadStatus} from '../../../model/book.model';
import {BookFilterMode} from '../../../../settings/user-management/user.service';
export function isRatingInRange(rating: number | undefined | null, rangeId: string | number): boolean {
if (rating == null) return false;
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
const range = ratingRanges.find(r => r.id === numericId);
if (!range) return false;
return rating >= range.min && rating < range.max;
}
export function isRatingInRange10(rating: number | undefined | null, rangeId: string | number): boolean {
if (rating == null) return false;
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
return Math.round(rating) === numericId;
}
export function isFileSizeInRange(fileSizeKb: number | undefined, rangeId: string | number): boolean {
if (fileSizeKb == null) return false;
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
const range = fileSizeRanges.find(r => r.id === numericId);
if (!range) return false;
return fileSizeKb >= range.min && fileSizeKb < range.max;
}
export function isPageCountInRange(pageCount: number | undefined, rangeId: string | number): boolean {
if (pageCount == null) return false;
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
const range = pageCountRanges.find(r => r.id === numericId);
if (!range) return false;
return pageCount >= range.min && pageCount < range.max;
}
export function isMatchScoreInRange(score: number | undefined | null, rangeId: string | number): boolean {
if (score == null) return false;
const normalizedScore = score > 1 ? score / 100 : score;
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
const range = matchScoreRanges.find(r => r.id === numericId);
if (!range) return false;
return normalizedScore >= range.min && normalizedScore < range.max;
}
export function doesBookMatchReadStatus(book: Book, selected: unknown[]): boolean {
const status = book.readStatus ?? ReadStatus.UNSET;
return selected.includes(status);
}
export function doesBookMatchFilter(
book: Book,
filterType: string,
filterValues: unknown[],
mode: BookFilterMode
): boolean {
if (!Array.isArray(filterValues) || filterValues.length === 0) {
return mode === 'or';
}
const effectiveMode = mode === 'not' ? 'or' : mode;
switch (filterType) {
case 'author':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.authors?.includes(val as string))
: filterValues.every(val => book.metadata?.authors?.includes(val as string));
case 'category':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.categories?.includes(val as string))
: filterValues.every(val => book.metadata?.categories?.includes(val as string));
case 'series':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.seriesName?.trim() === val)
: filterValues.every(val => book.metadata?.seriesName?.trim() === val);
case 'bookType':
return book.isPhysical ? filterValues.includes('PHYSICAL') : filterValues.includes(book.primaryFile?.bookType);
case 'readStatus':
return doesBookMatchReadStatus(book, filterValues);
case 'personalRating':
return filterValues.some(range => isRatingInRange10(book.personalRating, range as string | number));
case 'publisher':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.publisher === val)
: filterValues.every(val => book.metadata?.publisher === val);
case 'matchScore':
return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range as string | number));
case 'library':
return effectiveMode === 'or'
? filterValues.some(val => val == book.libraryId)
: filterValues.every(val => val == book.libraryId);
case 'shelf':
return effectiveMode === 'or'
? filterValues.some(val => book.shelves?.some(s => s.id == val))
: filterValues.every(val => book.shelves?.some(s => s.id == val));
case 'shelfStatus': {
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
return filterValues.includes(shelved);
}
case 'tag':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.tags?.includes(val as string))
: filterValues.every(val => book.metadata?.tags?.includes(val as string));
case 'publishedDate': {
const bookYear = book.metadata?.publishedDate
? new Date(book.metadata.publishedDate).getFullYear()
: null;
return bookYear ? filterValues.some(val => val == bookYear || val == bookYear.toString()) : false;
}
case 'fileSize':
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range as string | number));
case 'amazonRating':
return filterValues.some(range => isRatingInRange(book.metadata?.amazonRating, range as string | number));
case 'goodreadsRating':
return filterValues.some(range => isRatingInRange(book.metadata?.goodreadsRating, range as string | number));
case 'hardcoverRating':
return filterValues.some(range => isRatingInRange(book.metadata?.hardcoverRating, range as string | number));
case 'language':
return filterValues.includes(book.metadata?.language);
case 'pageCount':
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount ?? undefined, range as string | number));
case 'mood':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.moods?.includes(val as string))
: filterValues.every(val => book.metadata?.moods?.includes(val as string));
case 'ageRating':
return filterValues.some(val => {
const numVal = typeof val === 'string' ? Number(val) : val;
return book.metadata?.ageRating === numVal;
});
case 'contentRating':
return filterValues.includes(book.metadata?.contentRating);
case 'narrator':
return filterValues.includes(book.metadata?.narrator);
case 'comicCharacter':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.comicMetadata?.characters?.includes(val as string))
: filterValues.every(val => book.metadata?.comicMetadata?.characters?.includes(val as string));
case 'comicTeam':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.comicMetadata?.teams?.includes(val as string))
: filterValues.every(val => book.metadata?.comicMetadata?.teams?.includes(val as string));
case 'comicLocation':
return effectiveMode === 'or'
? filterValues.some(val => book.metadata?.comicMetadata?.locations?.includes(val as string))
: filterValues.every(val => book.metadata?.comicMetadata?.locations?.includes(val as string));
case 'comicCreator': {
const comic = book.metadata?.comicMetadata;
if (!comic) return false;
const allCreators: string[] = [];
const roles: [string[] | undefined, string][] = [
[comic.pencillers, 'penciller'],
[comic.inkers, 'inker'],
[comic.colorists, 'colorist'],
[comic.letterers, 'letterer'],
[comic.coverArtists, 'coverArtist'],
[comic.editors, 'editor']
];
for (const [names, role] of roles) {
if (names) {
for (const name of names) {
allCreators.push(`${name}:${role}`);
}
}
}
return effectiveMode === 'or'
? filterValues.some(val => allCreators.includes(val as string))
: filterValues.every(val => allCreators.includes(val as string));
}
default:
return false;
}
}
export function filterBooksByFilters(
books: Book[],
activeFilters: Record<string, unknown[]> | null,
mode: BookFilterMode,
excludeFilterType?: string
): Book[] {
if (!activeFilters) return books;
const filterEntries = Object.entries(activeFilters)
.filter(([type]) => type !== excludeFilterType);
if (filterEntries.length === 0) return books;
return books.filter(book => {
const matches = filterEntries.map(([filterType, filterValues]) =>
doesBookMatchFilter(book, filterType, filterValues, mode)
);
if (mode === 'not') return matches.every(m => !m);
return mode === 'or' ? matches.some(m => m) : matches.every(m => m);
});
}
@@ -0,0 +1,50 @@
<ng-container *transloco="let t; prefix: 'book.lockUnlockDialog'">
<div class="lock-unlock-container">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-lock header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">{{ t('title') }}</h2>
<p class="panel-description">{{ t('selectedCount', { count: bookIds.size }) }}</p>
</div>
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="secondary"
(click)="dialogRef.close()"
class="close-button">
</p-button>
</div>
<div class="dialog-content">
<div class="fields-grid">
@for (field of lockableFields; track field) {
<div class="field-row">
<label class="field-label">{{ fieldLabels[field] || field }}</label>
<p-button
[outlined]="true"
[label]="getLockLabel(field)"
[icon]="getLockIcon(field)"
[severity]="fieldLocks[field] === true ? 'danger' : fieldLocks[field] === false ? 'success' : 'secondary'"
(click)="cycleLockState(field)"
></p-button>
</div>
}
</div>
</div>
<div class="dialog-footer">
<div class="footer-actions">
<p-button icon="pi pi-refresh" [label]="t('reset')" outlined="true" severity="warn" (onClick)="resetFieldLocks()"></p-button>
</div>
<div class="footer-actions">
<p-button icon="pi pi-lock" [label]="t('lockAll')" outlined="true" severity="danger" (onClick)="toggleLockAll('LOCK')"></p-button>
<p-button icon="pi pi-lock-open" [label]="t('unlockAll')" outlined="true" severity="success" (onClick)="toggleLockAll('UNLOCK')"></p-button>
<p-divider layout="vertical"></p-divider>
<p-button [label]="isSaving ? t('saving') : t('save')" [outlined]="true" icon="pi pi-check" severity="info" (onClick)="applyFieldLocks()" [disabled]="bookIds.size === 0 || isSaving"></p-button>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,53 @@
@use '../../../../../shared/styles/panel-shared' as panel;
.lock-unlock-container {
display: flex;
flex-direction: column;
}
.panel-header {
@include panel.panel-header;
}
.dialog-content {
padding: 1.5rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
border-bottom: none;
}
.dialog-footer {
@include panel.dialog-footer;
}
.footer-actions {
display: flex;
gap: 0.5rem;
align-items: center;
}
.fields-grid {
display: grid;
grid-template-columns: repeat(1, minmax(0, 1fr));
column-gap: 6rem;
row-gap: 1rem;
@media (min-width: 576px) {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (min-width: 768px) {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
.field-row {
display: flex;
align-items: center;
justify-content: space-between;
}
.field-label {
text-transform: capitalize;
}
@@ -0,0 +1,155 @@
import {Component, inject, OnInit} from '@angular/core';
import {Button} from 'primeng/button';
import {FormsModule} from '@angular/forms';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {MessageService} from 'primeng/api';
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
import {Divider} from 'primeng/divider';
import {LoadingService} from '../../../../../core/services/loading.service';
import {finalize} from 'rxjs';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@Component({
selector: 'app-lock-unlock-metadata-dialog',
standalone: true,
imports: [
Button,
FormsModule,
Divider,
TranslocoDirective
],
templateUrl: './lock-unlock-metadata-dialog.component.html',
styleUrl: './lock-unlock-metadata-dialog.component.scss'
})
export class LockUnlockMetadataDialogComponent implements OnInit {
private bookMetadataManageService = inject(BookMetadataManageService);
private dynamicDialogConfig = inject(DynamicDialogConfig);
dialogRef = inject(DynamicDialogRef);
private messageService = inject(MessageService);
private loadingService = inject(LoadingService);
private readonly t = inject(TranslocoService);
fieldLocks: Record<string, boolean | undefined> = {};
bookIds: Set<number> = this.dynamicDialogConfig.data.bookIds;
lockableFields: string[] = [
'titleLocked', 'subtitleLocked', 'publisherLocked', 'publishedDateLocked', 'descriptionLocked',
'isbn13Locked', 'isbn10Locked', 'asinLocked', 'pageCountLocked', 'thumbnailLocked', 'languageLocked', 'coverLocked',
'seriesNameLocked', 'seriesNumberLocked', 'seriesTotalLocked', 'authorsLocked', 'categoriesLocked', 'moodsLocked', 'tagsLocked',
'amazonRatingLocked', 'amazonReviewCountLocked', 'goodreadsRatingLocked', 'goodreadsReviewCountLocked',
'hardcoverRatingLocked', 'hardcoverReviewCountLocked', 'goodreadsIdLocked', 'hardcoverIdLocked', 'hardcoverBookIdLocked', 'googleIdLocked', 'comicvineIdLocked',
'ranobedbIdLocked', 'ranobedbRatingLocked'
];
fieldLabels: Record<string, string> = {
titleLocked: 'Title',
subtitleLocked: 'Subtitle',
publisherLocked: 'Publisher',
publishedDateLocked: 'Date',
descriptionLocked: 'Description',
isbn13Locked: 'ISBN-13',
isbn10Locked: 'ISBN-10',
asinLocked: 'ASIN',
pageCountLocked: 'Page Count',
thumbnailLocked: 'Thumbnail',
languageLocked: 'Language',
coverLocked: 'Cover',
seriesNameLocked: 'Series',
seriesNumberLocked: 'Series #',
seriesTotalLocked: 'Series Total #',
authorsLocked: 'Authors',
categoriesLocked: 'Genres',
moodsLocked: 'Moods',
tagsLocked: 'Tags',
amazonRatingLocked: 'Amazon ★',
amazonReviewCountLocked: 'Amazon Reviews',
goodreadsRatingLocked: 'Goodreads ★',
goodreadsReviewCountLocked: 'Goodreads Reviews',
hardcoverRatingLocked: 'Hardcover ★',
hardcoverReviewCountLocked: 'Hardcover Reviews',
goodreadsIdLocked: 'Goodreads ID',
hardcoverIdLocked: 'Hardcover ID',
hardcoverBookIdLocked: 'Hardcover Book ID',
googleIdLocked: 'Google ID',
comicvineIdLocked: 'Comicvine ID',
ranobedbIdLocked: 'Ranobedb ID',
ranobedbRatingLocked: 'Ranobedb ★',
};
isSaving = false;
ngOnInit(): void {
this.lockableFields.forEach(field => this.fieldLocks[field] = undefined);
}
toggleLockAll(action: 'LOCK' | 'UNLOCK'): void {
const lockState = action === 'LOCK' ? true : false;
this.lockableFields.forEach(field => {
this.fieldLocks[field] = lockState;
});
}
getLockLabel(field: string): string {
const state = this.fieldLocks[field];
if (state === undefined) return this.t.translate('book.lockUnlockDialog.unselected');
return state ? this.t.translate('book.lockUnlockDialog.locked') : this.t.translate('book.lockUnlockDialog.unlocked');
}
getLockIcon(field: string): string {
const state = this.fieldLocks[field];
return state === undefined ? '' : state ? 'pi pi-lock' : 'pi pi-lock-open';
}
resetFieldLocks(): void {
this.lockableFields.forEach(field => {
this.fieldLocks[field] = undefined;
});
}
cycleLockState(field: string): void {
const current = this.fieldLocks[field];
if (current === undefined) {
this.fieldLocks[field] = true;
} else if (current) {
this.fieldLocks[field] = false;
} else {
this.fieldLocks[field] = undefined;
}
}
applyFieldLocks(): void {
const fieldActions: Record<string, 'LOCK' | 'UNLOCK'> = {};
for (const [field, locked] of Object.entries(this.fieldLocks)) {
if (locked !== undefined) {
fieldActions[field] = locked ? 'LOCK' : 'UNLOCK';
}
}
this.isSaving = true;
const loader = this.loadingService.show(this.t.translate('book.lockUnlockDialog.toast.updatingFieldLocks'));
this.bookMetadataManageService.toggleFieldLocks(this.bookIds, fieldActions)
.pipe(finalize(() => {
this.isSaving = false;
this.loadingService.hide(loader);
}))
.subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.lockUnlockDialog.toast.updatedSummary'),
detail: this.t.translate('book.lockUnlockDialog.toast.updatedDetail')
});
this.dialogRef.close('fields-updated');
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.lockUnlockDialog.toast.failedSummary'),
detail: this.t.translate('book.lockUnlockDialog.toast.failedDetail')
});
}
});
}
}
@@ -0,0 +1,187 @@
import {SortDirection, SortOption} from '../../../model/sort.model';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
import {TranslocoService} from '@jsverse/transloco';
export const SORT_OPTION_LABEL_KEYS: Readonly<Record<string, string>> = {
title: 'book.sorting.options.title',
fileName: 'book.sorting.options.fileName',
filePath: 'book.sorting.options.filePath',
author: 'book.sorting.options.author',
authorSurnameVorname: 'book.sorting.options.authorSurnameVorname',
seriesName: 'book.sorting.options.seriesName',
seriesNumber: 'book.sorting.options.seriesNumber',
lastReadTime: 'book.sorting.options.lastReadTime',
personalRating: 'book.sorting.options.personalRating',
addedOn: 'book.sorting.options.addedOn',
fileSizeKb: 'book.sorting.options.fileSizeKb',
locked: 'book.sorting.options.locked',
publisher: 'book.sorting.options.publisher',
publishedDate: 'book.sorting.options.publishedDate',
readStatus: 'book.sorting.options.readStatus',
dateFinished: 'book.sorting.options.dateFinished',
readingProgress: 'book.sorting.options.readingProgress',
bookType: 'book.sorting.options.bookType',
amazonRating: 'book.sorting.options.amazonRating',
amazonReviewCount: 'book.sorting.options.amazonReviewCount',
goodreadsRating: 'book.sorting.options.goodreadsRating',
goodreadsReviewCount: 'book.sorting.options.goodreadsReviewCount',
hardcoverRating: 'book.sorting.options.hardcoverRating',
hardcoverReviewCount: 'book.sorting.options.hardcoverReviewCount',
ranobedbRating: 'book.sorting.options.ranobedbRating',
narrator: 'book.sorting.options.narrator',
pageCount: 'book.sorting.options.pageCount',
random: 'book.sorting.options.random'
};
const SORT_FIELDS: { field: string; defaultLabel: string }[] = [
{field: 'title', defaultLabel: 'Title'},
{field: 'fileName', defaultLabel: 'File Name'},
{field: 'filePath', defaultLabel: 'File Path'},
{field: 'author', defaultLabel: 'Author'},
{field: 'authorSurnameVorname', defaultLabel: 'Author (Surname)'},
{field: 'seriesName', defaultLabel: 'Series Name'},
{field: 'seriesNumber', defaultLabel: 'Series Number'},
{field: 'lastReadTime', defaultLabel: 'Last Read'},
{field: 'personalRating', defaultLabel: 'Personal Rating'},
{field: 'addedOn', defaultLabel: 'Added On'},
{field: 'fileSizeKb', defaultLabel: 'File Size'},
{field: 'locked', defaultLabel: 'Locked'},
{field: 'publisher', defaultLabel: 'Publisher'},
{field: 'publishedDate', defaultLabel: 'Published Date'},
{field: 'readStatus', defaultLabel: 'Read Status'},
{field: 'dateFinished', defaultLabel: 'Date Finished'},
{field: 'readingProgress', defaultLabel: 'Reading Progress'},
{field: 'bookType', defaultLabel: 'Book Type'},
{field: 'amazonRating', defaultLabel: 'Amazon Rating'},
{field: 'amazonReviewCount', defaultLabel: 'Amazon #'},
{field: 'goodreadsRating', defaultLabel: 'Goodreads Rating'},
{field: 'goodreadsReviewCount', defaultLabel: 'Goodreads #'},
{field: 'hardcoverRating', defaultLabel: 'Hardcover Rating'},
{field: 'hardcoverReviewCount', defaultLabel: 'Hardcover #'},
{field: 'ranobedbRating', defaultLabel: 'Ranobedb Rating'},
{field: 'narrator', defaultLabel: 'Narrator'},
{field: 'pageCount', defaultLabel: 'Pages'},
{field: 'random', defaultLabel: 'Random'},
];
export class BookSorter {
selectedSortCriteria: SortOption[] = [];
sortOptions: SortOption[];
constructor(private onSortChange: (criteria: SortOption[]) => void, translocoService?: TranslocoService) {
this.sortOptions = SORT_FIELDS.map(({field, defaultLabel}) => {
const key = SORT_OPTION_LABEL_KEYS[field];
const label = key && translocoService ? translocoService.translate(key) : defaultLabel;
return {label, field, direction: SortDirection.ASCENDING};
});
}
// For backward compatibility - get first sort option
get selectedSort(): SortOption | undefined {
return this.selectedSortCriteria[0];
}
// For backward compatibility - set from single sort option
set selectedSort(sort: SortOption | undefined) {
if (sort) {
this.selectedSortCriteria = [sort];
} else {
this.selectedSortCriteria = [];
}
}
setSortCriteria(criteria: SortOption[]): void {
this.selectedSortCriteria = [...criteria];
this.updateSortOptions();
}
// Quick sort by field - toggles direction if already selected as primary sort
sortBooks(field: string): void {
const existingSort = this.sortOptions.find(opt => opt.field === field);
if (!existingSort) return;
// If this field is the first (primary) sort, toggle its direction
if (this.selectedSortCriteria.length > 0 && this.selectedSortCriteria[0].field === field) {
this.selectedSortCriteria[0] = {
...this.selectedSortCriteria[0],
direction: this.selectedSortCriteria[0].direction === SortDirection.ASCENDING
? SortDirection.DESCENDING
: SortDirection.ASCENDING
};
} else {
// Set as the only sort criterion (single click behavior)
this.selectedSortCriteria = [{
label: existingSort.label,
field: existingSort.field,
direction: SortDirection.ASCENDING
}];
}
this.updateSortOptions();
this.onSortChange(this.selectedSortCriteria);
}
addSortCriterion(field: string): void {
// Don't add if already exists
if (this.selectedSortCriteria.some(c => c.field === field)) return;
const option = this.sortOptions.find(opt => opt.field === field);
if (!option) return;
this.selectedSortCriteria.push({
label: option.label,
field: option.field,
direction: SortDirection.ASCENDING
});
this.updateSortOptions();
this.onSortChange(this.selectedSortCriteria);
}
removeSortCriterion(index: number): void {
if (index < 0 || index >= this.selectedSortCriteria.length) return;
this.selectedSortCriteria.splice(index, 1);
this.updateSortOptions();
this.onSortChange(this.selectedSortCriteria);
}
toggleCriterionDirection(index: number): void {
if (index < 0 || index >= this.selectedSortCriteria.length) return;
const criterion = this.selectedSortCriteria[index];
this.selectedSortCriteria[index] = {
...criterion,
direction: criterion.direction === SortDirection.ASCENDING
? SortDirection.DESCENDING
: SortDirection.ASCENDING
};
this.updateSortOptions();
this.onSortChange(this.selectedSortCriteria);
}
reorderCriteria(event: CdkDragDrop<SortOption[]>): void {
moveItemInArray(this.selectedSortCriteria, event.previousIndex, event.currentIndex);
this.updateSortOptions();
this.onSortChange(this.selectedSortCriteria);
}
getAvailableSortOptions(): SortOption[] {
const usedFields = new Set(this.selectedSortCriteria.map(c => c.field));
return this.sortOptions.filter(opt => !usedFields.has(opt.field));
}
updateSortOptions(): void {
const primaryField = this.selectedSortCriteria[0]?.field;
const primaryDirection = this.selectedSortCriteria[0]?.direction;
const directionIcon = primaryDirection === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
this.sortOptions = this.sortOptions.map((option) => ({
...option,
icon: option.field === primaryField ? directionIcon : '',
}));
}
}
@@ -0,0 +1,71 @@
<ng-container *transloco="let t; prefix: 'book.sorting'">
<div class="multi-sort-container">
<div class="multi-sort-header">
<span class="header-title">{{ t('sortOrder') }}</span>
</div>
<div
class="sort-criteria-list"
cdkDropList
[cdkDropListData]="sortCriteria"
(cdkDropListDropped)="onDrop($event)">
@for (criterion of sortCriteria; track criterion.field; let i = $index) {
<div class="sort-criterion" cdkDrag>
<div class="criterion-drag-handle" cdkDragHandle>
<i class="pi pi-bars"></i>
</div>
<span class="criterion-rank">{{ i + 1 }}.</span>
<span class="criterion-label">{{ criterion.label }}</span>
<div class="criterion-actions">
<button
type="button"
class="direction-btn"
(click)="onToggleDirection(i)"
[pTooltip]="getDirectionTooltip(criterion.direction)"
tooltipPosition="top">
<i [class]="getDirectionIcon(criterion.direction)"></i>
</button>
<button
type="button"
class="remove-btn"
(click)="onRemove(i)"
[pTooltip]="t('removeTooltip')"
tooltipPosition="top"
[disabled]="sortCriteria.length === 1">
<i class="pi pi-times"></i>
</button>
</div>
</div>
}
</div>
@if (unusedOptions.length > 0) {
<div class="add-sort-section">
<p-select
[options]="unusedOptions"
[(ngModel)]="selectedField"
optionLabel="label"
optionValue="field"
[placeholder]="t('addSortFieldPlaceholder')"
[style]="{ width: '100%' }"
size="small"
appendTo="body"
(onChange)="onAddField()">
</p-select>
</div>
}
@if (showSaveButton) {
<div class="save-sort-section">
<p-button
icon="pi pi-save"
[label]="t('saveAsDefault')"
size="small"
[outlined]="true"
[style]="{ width: '100%' }"
(onClick)="onSave()">
</p-button>
</div>
}
</div>
</ng-container>
@@ -0,0 +1,150 @@
.multi-sort-container {
width: 280px;
padding: 0.5rem;
}
.multi-sort-header {
display: flex;
justify-content: space-between;
align-items: center;
padding-bottom: 0.75rem;
border-bottom: 1px solid var(--border-color);
margin-bottom: 0.75rem;
}
.header-title {
font-weight: 600;
font-size: 0.9rem;
color: var(--text-color);
}
.sort-criteria-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-height: 40px;
}
.sort-criterion {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
background-color: var(--overlay-background);
border: 1px solid var(--border-color);
border-radius: 6px;
cursor: move;
transition: background-color 0.15s ease, box-shadow 0.15s ease;
&:hover {
background-color: var(--ground-background);
}
}
.cdk-drag-preview {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
background-color: var(--card-background);
border: 1px solid var(--primary-color);
border-radius: 6px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.25);
}
.cdk-drag-placeholder {
opacity: 0.3;
}
.cdk-drag-animating {
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
.sort-criteria-list.cdk-drop-list-dragging .sort-criterion:not(.cdk-drag-placeholder) {
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
.criterion-drag-handle {
display: flex;
align-items: center;
justify-content: center;
color: var(--text-secondary-color);
cursor: grab;
&:active {
cursor: grabbing;
}
i {
font-size: 0.85rem;
}
}
.criterion-rank {
font-weight: 600;
color: var(--primary-color);
min-width: 1.25rem;
}
.criterion-label {
flex: 1;
font-size: 0.875rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: var(--text-color);
}
.criterion-actions {
display: flex;
align-items: center;
gap: 0.25rem;
}
.direction-btn,
.remove-btn {
display: flex;
align-items: center;
justify-content: center;
width: 1.75rem;
height: 1.75rem;
padding: 0;
border: none;
border-radius: 4px;
background-color: transparent;
cursor: pointer;
transition: background-color 0.15s ease;
i {
font-size: 0.85rem;
}
&:hover:not(:disabled) {
background-color: var(--ground-background);
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
}
}
.direction-btn {
color: var(--primary-color);
}
.remove-btn {
color: var(--p-red-500);
}
.add-sort-section {
margin-top: 0.75rem;
padding-top: 0.75rem;
border-top: 1px solid var(--border-color);
}
.save-sort-section {
margin-top: 0.75rem;
padding-top: 0.75rem;
border-top: 1px solid var(--border-color);
}
@@ -0,0 +1,92 @@
import {ChangeDetectionStrategy, Component, EventEmitter, inject, Input, Output} from '@angular/core';
import {SortDirection, SortOption} from '../../../../model/sort.model';
import {CdkDrag, CdkDragDrop, CdkDragHandle, CdkDropList, moveItemInArray} from '@angular/cdk/drag-drop';
import {Select} from 'primeng/select';
import {FormsModule} from '@angular/forms';
import {Tooltip} from 'primeng/tooltip';
import {Button} from 'primeng/button';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@Component({
selector: 'app-multi-sort-popover',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
CdkDropList,
CdkDrag,
CdkDragHandle,
Select,
FormsModule,
Tooltip,
Button,
TranslocoDirective
],
templateUrl: './multi-sort-popover.component.html',
styleUrl: './multi-sort-popover.component.scss'
})
export class MultiSortPopoverComponent {
private readonly t = inject(TranslocoService);
@Input() sortCriteria: SortOption[] = [];
@Input() availableSortOptions: SortOption[] = [];
@Input() showSaveButton = false;
@Output() criteriaChange = new EventEmitter<SortOption[]>();
@Output() saveSortConfig = new EventEmitter<SortOption[]>();
selectedField: string | null = null;
get unusedOptions(): SortOption[] {
const usedFields = new Set(this.sortCriteria.map(c => c.field));
return this.availableSortOptions.filter(opt => !usedFields.has(opt.field));
}
onDrop(event: CdkDragDrop<SortOption[]>): void {
const criteria = [...this.sortCriteria];
moveItemInArray(criteria, event.previousIndex, event.currentIndex);
this.sortCriteria = criteria;
this.criteriaChange.emit(this.sortCriteria);
}
onToggleDirection(index: number): void {
this.sortCriteria = this.sortCriteria.map((c, i) =>
i === index
? {...c, direction: c.direction === SortDirection.ASCENDING ? SortDirection.DESCENDING : SortDirection.ASCENDING}
: c
);
this.criteriaChange.emit(this.sortCriteria);
}
onRemove(index: number): void {
this.sortCriteria = this.sortCriteria.filter((_, i) => i !== index);
this.criteriaChange.emit(this.sortCriteria);
}
onAddField(): void {
if (!this.selectedField) return;
const option = this.availableSortOptions.find(o => o.field === this.selectedField);
if (!option) return;
this.sortCriteria = [...this.sortCriteria, {
label: option.label,
field: option.field,
direction: SortDirection.ASCENDING
}];
this.selectedField = null;
this.criteriaChange.emit(this.sortCriteria);
}
onSave(): void {
this.saveSortConfig.emit(this.sortCriteria);
}
getDirectionIcon(direction: SortDirection): string {
return direction === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
}
getDirectionTooltip(direction: SortDirection): string {
return direction === SortDirection.ASCENDING
? this.t.translate('book.sorting.ascendingTooltip')
: this.t.translate('book.sorting.descendingTooltip');
}
protected readonly SortDirection = SortDirection;
}
@@ -0,0 +1,92 @@
import {inject, Injectable, signal} from '@angular/core';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
@Injectable({
providedIn: 'root'
})
export class TableColumnPreferenceService {
private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private readonly _preferences = signal<TableColumnPreference[]>([]);
readonly preferences = this._preferences.asReadonly();
private readonly allAvailableFields = [
'readStatus', 'title', 'authors', 'publisher', 'seriesName', 'seriesNumber',
'categories', 'publishedDate', 'lastReadTime', 'addedOn', 'fileName', 'fileSizeKb',
'language', 'isbn', 'pageCount', 'amazonRating', 'amazonReviewCount',
'goodreadsRating', 'goodreadsReviewCount', 'hardcoverRating', 'hardcoverReviewCount',
'ranobedbRating',
];
private readonly fallbackPreferences: TableColumnPreference[] = this.allAvailableFields.map((field, index) => ({
field,
visible: true,
order: index
}));
initPreferences(savedPrefs: TableColumnPreference[] | undefined): void {
const effectivePrefs = savedPrefs?.length ? savedPrefs : this.fallbackPreferences;
this._preferences.set(this.mergeWithAllColumns(effectivePrefs));
}
get allColumns(): { field: string; header: string }[] {
return this.allAvailableFields.map(field => ({
field,
header: this.t.translate(`book.columnPref.columns.${field}`)
}));
}
get visibleColumns(): { field: string; header: string }[] {
return this.preferences()
.filter(pref => pref.visible)
.sort((a, b) => a.order - b.order)
.map(pref => ({
field: pref.field,
header: this.t.translate(`book.columnPref.columns.${pref.field}`)
}));
}
saveVisibleColumns(selectedColumns: { field: string }[]): void {
const selectedFieldSet = new Set(selectedColumns.map(c => c.field));
const updatedPreferences: TableColumnPreference[] = this.allAvailableFields.map((field, index) => {
const selectionIndex = selectedColumns.findIndex(c => c.field === field);
return {
field,
visible: selectedFieldSet.has(field),
order: selectionIndex >= 0 ? selectionIndex : index
};
});
this._preferences.set(updatedPreferences);
const currentUser = this.userService.getCurrentUser();
if (!currentUser) return;
this.userService.updateUserSetting(currentUser.id, 'tableColumnPreference', updatedPreferences);
this.messageService.add({
severity: 'success',
summary: this.t.translate('book.columnPref.toast.savedSummary'),
detail: this.t.translate('book.columnPref.toast.savedDetail'),
life: 1500
});
}
private mergeWithAllColumns(savedPrefs: TableColumnPreference[]): TableColumnPreference[] {
const savedPrefMap = new Map(savedPrefs.map(p => [p.field, p]));
return this.allAvailableFields.map((field, index) => {
const saved = savedPrefMap.get(field);
return {
field,
visible: saved?.visible ?? true,
order: saved?.order ?? index
};
});
}
}