Refactor the Book Browser to simplify and streamline the implementation (#2317)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-17 23:07:39 -07:00
committed by GitHub
co-authored by acx10
parent cb85604863
commit 890d7cc230
8 changed files with 1126 additions and 582 deletions
@@ -0,0 +1,197 @@
import {Injectable, inject} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Observable, of, combineLatest} from 'rxjs';
import {map, switchMap, take, catchError} from 'rxjs/operators';
import {Library} from '../../model/library.model';
import {Shelf} from '../../model/shelf.model';
import {Book} from '../../model/book.model';
import {BookState} from '../../model/state/book-state.model';
import {SortOption} from '../../model/sort.model';
import {LibraryService} from '../../service/library.service';
import {BookService} from '../../service/book.service';
import {ShelfService} from '../../service/shelf.service';
import {SortService} from '../../service/sort.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 bookService = inject(BookService);
private shelfService = inject(ShelfService);
private sortService = inject(SortService);
private magicShelfService = inject(MagicShelfService);
private bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
getEntityInfoFromRoute(activatedRoute: ActivatedRoute): Observable<EntityInfo> {
return activatedRoute.paramMap.pipe(
map(params => {
const libraryId = Number(params.get('libraryId') || NaN);
const shelfId = Number(params.get('shelfId') || NaN);
const magicShelfId = Number(params.get('magicShelfId') || NaN);
if (!isNaN(libraryId)) {
return {entityId: libraryId, entityType: EntityType.LIBRARY};
} else if (!isNaN(shelfId)) {
return {entityId: shelfId, entityType: EntityType.SHELF};
} else if (!isNaN(magicShelfId)) {
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
} else {
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
})
);
}
fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | MagicShelf | null> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchLibrary(entityId);
case EntityType.SHELF:
return this.fetchShelf(entityId);
case EntityType.MAGIC_SHELF:
return this.fetchMagicShelf(entityId);
default:
return of(null);
}
}
fetchBooksByEntity(
entityId: number,
entityType: EntityType,
sortOption: SortOption
): Observable<BookState> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchBooks(book => book.libraryId === entityId, sortOption);
case EntityType.SHELF:
return this.fetchShelfBooks(entityId, sortOption);
case EntityType.MAGIC_SHELF:
return this.fetchMagicShelfBooks(entityId, sortOption);
case EntityType.ALL_BOOKS:
default:
return this.fetchAllBooks(sortOption);
}
}
fetchAllBooks(sortOption: SortOption): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => this.processBookState(bookState, sortOption))
);
}
fetchUnshelvedBooks(sortOption: SortOption): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => ({
...bookState,
books: (bookState.books || []).filter(book => !book.shelves || book.shelves.length === 0)
})),
map(bookState => this.processBookState(bookState, sortOption))
);
}
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 fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraryState$.pipe(
map(libraryState => {
if (libraryState.libraries) {
return libraryState.libraries.find(lib => lib.id === libraryId) || null;
}
return null;
})
);
}
private fetchShelf(shelfId: number): Observable<Shelf | null> {
return this.shelfService.shelfState$.pipe(
map(shelfState => {
if (shelfState.shelves) {
return shelfState.shelves.find(shelf => shelf.id === shelfId) || null;
}
return null;
})
);
}
private fetchMagicShelf(magicShelfId: number): Observable<MagicShelf | null> {
return this.magicShelfService.shelvesState$.pipe(
take(1),
switchMap((state) => {
const cached = state.shelves?.find(s => s.id === magicShelfId) ?? null;
if (cached) {
return of(cached);
}
return this.magicShelfService.getShelf(magicShelfId).pipe(
map(shelf => shelf ?? null),
catchError(() => of(null))
);
})
);
}
private fetchShelfBooks(shelfId: number, sortOption: SortOption): Observable<BookState> {
return this.shelfService.getBooksOnShelf(shelfId).pipe(
map(books => {
const sortedBooks = this.sortService.applySort(books, sortOption);
return {
books: sortedBooks,
loaded: true,
error: null
};
})
);
}
private fetchMagicShelfBooks(magicShelfId: number, sortOption: SortOption): Observable<BookState> {
return combineLatest([
this.bookService.bookState$,
this.magicShelfService.getShelf(magicShelfId)
]).pipe(
map(([bookState, magicShelf]) => {
if (!bookState.loaded || bookState.error || !magicShelf?.filterJson) {
return bookState;
}
const filteredBooks: Book[] | undefined = bookState.books?.filter(book =>
this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule)
);
const sortedBooks = this.sortService.applySort(filteredBooks ?? [], sortOption);
return {...bookState, books: sortedBooks};
})
);
}
private fetchBooks(bookFilter: (book: Book) => boolean, sortOption: SortOption): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
if (bookState.loaded && !bookState.error) {
const filteredBooks = bookState.books?.filter(bookFilter) || [];
const sortedBooks = this.sortService.applySort(filteredBooks, sortOption);
return {...bookState, books: sortedBooks};
}
return bookState;
})
);
}
private processBookState(bookState: BookState, sortOption: SortOption): BookState {
if (bookState.loaded && !bookState.error) {
const sortedBooks = this.sortService.applySort(bookState.books || [], sortOption);
return {...bookState, books: sortedBooks};
}
return bookState;
}
}
@@ -0,0 +1,242 @@
import {Injectable, inject} from '@angular/core';
import {ActivatedRoute, ParamMap, Router} from '@angular/router';
import {SortDirection, SortOption} from '../../model/sort.model';
import {BookFilterMode, EntityViewPreferences} 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;
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 = override?.preferences ?? globalPrefs ?? {
sortKey: 'addedOn',
sortDir: 'ASC',
view: 'GRID'
};
const userSortKey = effectivePrefs.sortKey;
const userSortDir = effectivePrefs.sortDir?.toUpperCase() === 'DESC'
? SortDirection.DESCENDING
: SortDirection.ASCENDING;
const effectiveSortKey = sortParam || userSortKey;
const effectiveSortDir = directionParam
? (directionParam.toLowerCase() === SORT_DIRECTION.DESCENDING ? SortDirection.DESCENDING : SortDirection.ASCENDING)
: userSortDir;
const matchedSort = sortOptions.find(opt => opt.field === effectiveSortKey);
const sortOption: SortOption = matchedSort ? {
label: matchedSort.label,
field: matchedSort.field,
direction: effectiveSortDir
} : {
label: 'Added On',
field: 'addedOn',
direction: SortDirection.DESCENDING
};
// 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,
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 {
const currentParams = this.activatedRoute.snapshot.queryParams;
const newParams = {
...currentParams,
[QUERY_PARAMS.SORT]: sortOption.field,
[QUERY_PARAMS.DIRECTION]: sortOption.direction === SortDirection.ASCENDING
? SORT_DIRECTION.ASCENDING
: SORT_DIRECTION.DESCENDING
};
this.router.navigate([], {
queryParams: newParams,
replaceUrl: true
});
}
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.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 => v.trim()).filter(Boolean);
}
});
return parsedFilters;
}
syncQueryParams(
viewMode: string,
sortOption: SortOption,
filterMode: BookFilterMode,
filters: Record<string, string[]>
): void {
const queryParams: Record<string, string | number | null | undefined> = {
[QUERY_PARAMS.VIEW]: viewMode,
[QUERY_PARAMS.SORT]: sortOption.field,
[QUERY_PARAMS.DIRECTION]: sortOption.direction === SortDirection.ASCENDING
? SORT_DIRECTION.ASCENDING
: SORT_DIRECTION.DESCENDING,
[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 => currentParams[k] !== queryParams[k]);
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:'))
);
}
}
@@ -1,11 +1,11 @@
<div class="relative flex flex-row">
<div class="flex flex-col w-full">
<div class="book-browser-container">
<div class="book-browser-main">
<div class="flex items-center justify-between w-full gap-4 py-2 px-2 md:px-4 rounded-t-xl md:mb-4 mb-2 bg-[var(--card-background)] border-[1px] border-solid border-[var(--p-content-border-color)]">
<div class="flex items-center min-w-0 max-w-full flex-shrink">
<div class="book-browser-header">
<div class="entity-info-wrapper">
@if (entityType$ | async; as entityType) {
<div class="flex flex-col gap-0.5">
<p class="text-xl whitespace-nowrap overflow-hidden text-ellipsis w-full">
<div class="entity-info">
<p class="entity-title">
@if (entityType === EntityType.ALL_BOOKS) {
@if (currentFilterLabel && rawFilterParamFromUrl) {
{{ currentFilterLabel }}
@@ -21,7 +21,7 @@
}
</p>
@if (seriesCollapseFilter.isSeriesCollapsed && (bookState$ | async)?.books; as books) {
<p class="text-sm text-gray-500">
<p class="series-collapsed-info">
Showing {{ books.length }} {{ books.length === 1 ? 'item' : 'items' }} (series collapsed)
</p>
}
@@ -30,7 +30,7 @@
@if (userService.userState$ | async; as userState) {
@if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED &&
(userState.user!.permissions.admin || userState.user!.permissions.canManageLibrary)) {
<div class="ml-2 flex-shrink-0">
<div class="entity-menu-wrapper">
<p-button
icon="pi pi-ellipsis-v"
[rounded]="true"
@@ -44,15 +44,14 @@
}
}
</div>
<div class="flex flex-wrap items-center gap-4 flex-shrink-0">
<div class="flex flex-wrap items-center gap-4 md:gap-6">
<div class="toolbar-actions">
<div class="toolbar-icons">
@if (isFilterActive) {
<a class="topbar-items topbar-item" (click)="clearFilter()">
<i
class="pi pi-filter-slash"
class="pi pi-filter-slash filter-clear-icon"
pTooltip="Clear applied filters"
tooltipPosition="top"
style="color: orange;">
tooltipPosition="top">
</i>
</a>
}
@@ -67,7 +66,7 @@
</i>
</a>
<p-popover #columnPopover [dismissable]="true" appendTo="body">
<div class="w-[200px]">
<div class="column-popover-content">
<p-multiSelect
optionLabel="header"
[options]="columnPreferenceService.allColumns"
@@ -80,7 +79,7 @@
[showClear]="true"
></p-multiSelect>
</div>
<div class="flex items-center gap-2 pt-4 pl-1">
<div class="column-popover-footer">
<p>Set as default?</p>
<p-button
label="Save"
@@ -100,9 +99,9 @@
<i class="pi pi-cog"></i>
</a>
<p-popover #seriesCollapseOverlay [dismissable]="true" appendTo="body">
<div class="w-[220px] p-2 space-y-4 text-sm">
<div class="flex flex-col gap-2">
<label for="collapse-series-checkbox" class="font-medium">Collapse series</label>
<div class="display-settings-popover">
<div class="display-settings-section">
<label for="collapse-series-checkbox" class="display-settings-label">Collapse series</label>
<p-checkbox
inputId="collapse-series-checkbox"
[binary]="true"
@@ -110,8 +109,8 @@
(onChange)="onSeriesCollapseCheckboxChange($event.checked)">
</p-checkbox>
</div>
<div class="flex flex-col gap-2">
<label class="font-medium text-sm">Grid item size</label>
<div class="display-settings-section">
<label class="display-settings-label">Grid item size</label>
<p-slider
[(ngModel)]="coverScalePreferenceService.scaleFactor"
[min]="0.5"
@@ -120,13 +119,12 @@
[style]="{ width: '100%' }"
(onChange)="updateScale()">
</p-slider>
<div class="text-center">
<div class="scale-value-display">
{{ coverScalePreferenceService.scaleFactor.toFixed(2) }}x
</div>
</div>
<!-- Book type pill toggle control -->
<div class="flex flex-col gap-2">
<label for="show-book-type-pill-checkbox" class="font-medium">Show book type pill</label>
<div class="display-settings-section">
<label for="show-book-type-pill-checkbox" class="display-settings-label">Show book type pill</label>
<p-checkbox
inputId="show-book-type-pill-checkbox"
[binary]="true"
@@ -148,7 +146,7 @@
</a>
<p-menu #sortMenu [popup]="true" [model]="this.bookSorter.sortOptions" appendTo="body">
<ng-template pTemplate="item" let-item>
<div class="flex justify-between items-center px-4 py-2 cursor-pointer" (click)="this.bookSorter.sortBooks(item.field)">
<div class="sort-menu-item" (click)="this.bookSorter.sortBooks(item.field)">
<span>{{ item.label }}</span>
@if (item.icon) {
<i [class]="item.icon"></i>
@@ -168,7 +166,7 @@
</div>
<!-- MOBILE SEARCH (only visible below md) -->
<div class="relative md:hidden">
<div class="mobile-search-wrapper">
<button
type="button"
class="topbar-items topbar-item"
@@ -180,28 +178,28 @@
</button>
<p-popover #searchDropdown [dismissable]="true" appendTo="body" [style]="{ width: '24rem' }">
<div class="relative w-full">
<div class="search-popover-content">
<input
type="text"
pInputText
placeholder="Title, Author, Series, Genre, or ISBN..."
[(ngModel)]="bookTitle"
(ngModelChange)="onSearchTermChange($event)"
class="w-full"
class="search-input-full"
/>
<p-button
icon="pi pi-times"
[text]="true"
size="small"
[rounded]="true"
class="absolute right-2 top-1/2 -translate-y-1/2"
class="search-clear-btn"
(click)="clearSearch(); searchDropdown.hide()"
></p-button>
</div>
</p-popover>
</div>
<div class="hidden md:block relative">
<div class="desktop-search-wrapper">
<i class="pi pi-search search-icon"></i>
<input
type="text"
@@ -217,7 +215,7 @@
[text]="true"
size="small"
[rounded]="true"
class="absolute right-2 top-1/2 -translate-y-1/2"
class="search-clear-btn"
(click)="clearSearch()"
></p-button>
}
@@ -240,7 +238,7 @@
<p-progressSpinner></p-progressSpinner>
</div>
}
<div class="relative">
<div class="book-state-wrapper">
@if (bookState?.error) {
<div class="no-books-container">
<p class="no-books-text">
@@ -273,7 +271,7 @@
[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 relative"
class="virtual-scroller-item"
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
<app-book-card
[index]="books.indexOf(book)"
@@ -294,18 +292,18 @@
}
@if (selectedBooks.size > 0) {
@if (userService.userState$ | async; as userState) {
<div class="book-browser-footer bg-[var(--card-background)] bg-opacity-10" [@slideInOut]>
<div class="flex items-center">
<div class="flex items-center pl-2 w-1/4">
<div class="selected-count-badge text-zinc-200">
<i class="pi pi-check-circle mr-2"></i>
<span class="font-bold text-base" style="color: var(--primary-color)">{{ selectedBooks.size }}</span>
<span class="ml-1">selected</span>
<div class="book-browser-footer" [@slideInOut]>
<div class="footer-content">
<div class="footer-left">
<div class="selected-count-badge">
<i class="pi pi-check-circle"></i>
<span class="selected-count">{{ selectedBooks.size }}</span>
<span class="selected-label">selected</span>
</div>
</div>
<div class="flex justify-center w-2/4">
<div class="footer-center">
@if (entityType$ | async; as entityType) {
<div class="flex gap-2 md:gap-6">
<div class="action-buttons-group">
@if (hasMetadataMenuItems) {
<p-tieredMenu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body"/>
<p-button
@@ -356,7 +354,7 @@
</p-button>
}
@if (hasBulkReadActionsItems) {
<div class="card flex justify-center">
<div class="more-actions-wrapper">
<p-button
(click)="menu.toggle($event)"
pTooltip="More actions"
@@ -371,7 +369,7 @@
</div>
}
<p-divider layout="vertical"></p-divider>
<div class="flex gap-2 md:gap-6">
<div class="action-buttons-group">
<p-button
outlined="true"
icon="pi pi-check-square"
@@ -401,7 +399,7 @@
</p-button>
}
</div>
<div class="w-1/4"></div>
<div class="footer-right"></div>
</div>
</div>
}
@@ -418,8 +416,8 @@
</div>
<app-book-filter
[showFilter]="showFilter"
class="filter-overlay-container z-50 flex-shrink-0"
[ngClass]="{ 'active': showFilter, 'ml-4': showFilter }"
class="filter-overlay-container"
[ngClass]="{ 'active': showFilter }"
[entity$]="entity$"
[entityType$]="entityType$"
[resetFilter$]="resetFilterSubject"
@@ -1,29 +1,274 @@
.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;
// Layout containers
.book-browser-container {
position: relative;
display: flex;
flex-direction: row;
}
.no-books-container {
padding-top: 3rem;
.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: 1rem;
padding: 0.5rem 0.5rem;
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) {
padding: 0.5rem 1rem;
margin-bottom: 1rem;
}
}
// Entity info section
.entity-info-wrapper {
display: flex;
align-items: center;
min-width: 0;
max-width: 100%;
flex-shrink: 1;
}
.entity-info {
display: flex;
flex-direction: column;
gap: 0.125rem;
}
.entity-title {
font-size: 1.25rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 100%;
}
.series-collapsed-info {
font-size: 0.875rem;
color: #6b7280;
}
.entity-menu-wrapper {
margin-left: 0.5rem;
flex-shrink: 0;
}
// Toolbar actions
.toolbar-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 1rem;
flex-shrink: 0;
}
.toolbar-icons {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 1rem;
@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-label {
font-weight: 500;
}
.scale-value-display {
text-align: center;
}
// Sort menu item
.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;
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);
> .footer-content {
width: 100%;
}
@media (max-width: 768px) {
left: 0;
right: 0;
}
}
.footer-content {
display: flex;
justify-content: center;
align-items: center;
}
.footer-left {
display: flex;
align-items: center;
padding-left: 0.5rem;
width: 25%;
}
.footer-center {
display: flex;
justify-content: center;
width: 50%;
}
.footer-right {
width: 25%;
}
.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;
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) {
.virtual-scroller {
@media (max-width: 768px) {
height: calc(100dvh - 9rem);
}
}
@@ -37,54 +282,28 @@
}
.virtual-scroller-item {
position: relative;
transition: width 0.2s ease, height 0.2s ease;
}
.book-browser-footer {
position: absolute;
bottom: 0;
left: 10%;
right: 10%;
// No books state
.no-books-container {
padding-top: 3rem;
display: flex;
justify-content: center;
align-items: center;
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 0px 1px;
> .flex {
width: 100%;
}
}
.selected-count-badge {
display: inline-flex;
align-items: center;
padding: 0.5rem 1rem;
font-size: 0.9rem;
i {
font-size: 1rem;
}
}
@media (max-width: 768px) {
.book-browser-footer {
left: 0%;
right: 0%;
}
.selected-count-badge {
padding: 0.4rem 0.8rem;
font-size: 0.85rem;
i {
font-size: 0.9rem;
}
}
.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;
@@ -94,7 +313,7 @@
border: 1px solid var(--border-color);
width: 2.5rem;
height: 2.5rem;
transition: outline-color .2s, border-color .2s;
transition: outline-color 0.2s, border-color 0.2s;
border-radius: 6px;
margin: 0;
padding: 0;
@@ -113,13 +332,14 @@
}
}
// Search input styling
.search-icon {
position: absolute;
top: 50%;
left: 10px;
transform: translateY(-50%);
color: var(--text-secondary-color);
font-size: 1.0rem;
font-size: 1rem;
pointer-events: none;
}
@@ -132,6 +352,7 @@
box-sizing: border-box;
}
// Filter overlay (mobile sidebar)
.mobile-filter-mask {
@media (max-width: 991px) {
position: absolute;
@@ -145,6 +366,8 @@
}
.filter-overlay-container {
flex-shrink: 0;
z-index: 50;
@media (max-width: 991px) {
width: 225px;
@@ -161,6 +384,7 @@
&.active {
transform: translateX(0);
margin-left: 0;
}
}
@@ -173,12 +397,19 @@
width: 0 !important;
opacity: 0;
pointer-events: none;
margin-left: 0;
}
&.active {
width: 225px;
opacity: 1;
pointer-events: auto;
margin-left: 1rem;
}
}
}
// Book state container
.book-state-wrapper {
position: relative;
}
@@ -1,22 +1,19 @@
import {Component, inject, OnInit, ViewChild, AfterViewInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AfterViewInit, Component, inject, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {ConfirmationService, MenuItem, MessageService, PrimeTemplate} from 'primeng/api';
import {PageTitleService} from "../../../../shared/service/page-title.service";
import {LibraryService} from '../../service/library.service';
import {PageTitleService} from '../../../../shared/service/page-title.service';
import {BookService} from '../../service/book.service';
import {catchError, debounceTime, filter, map, switchMap, take} from 'rxjs/operators';
import {debounceTime, filter, map, switchMap} from 'rxjs/operators';
import {BehaviorSubject, combineLatest, finalize, Observable, of, Subject} from 'rxjs';
import {ShelfService} from '../../service/shelf.service';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Library} from '../../model/library.model';
import {Shelf} from '../../model/shelf.model';
import {SortService} from '../../service/sort.service';
import {SortDirection, SortOption} from '../../model/sort.model';
import {SortOption} from '../../model/sort.model';
import {BookState} from '../../model/state/book-state.model';
import {Book} from '../../model/book.model';
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
import {BookTableComponent} from './book-table/book-table.component';
import {animate, state, style, transition, trigger} from '@angular/animations';
import {animate, style, transition, trigger} from '@angular/animations';
import {Button} from 'primeng/button';
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
@@ -42,16 +39,18 @@ import {MultiSelect} from 'primeng/multiselect';
import {TableColumnPreferenceService} from './table-column-preference.service';
import {TieredMenu} from 'primeng/tieredmenu';
import {BookMenuService} from '../../service/book-menu.service';
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
import {MagicShelf} from '../../../magic-shelf/service/magic-shelf.service';
import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref.service';
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
import {TaskHelperService} from '../../../settings/task-management/task-helper.service';
import {FilterLabelHelper} from './filter-label.helper';
import {LoadingService} from '../../../../core/services/loading.service';
import {BookNavigationService} from '../../service/book-navigation.service';
import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.service';
import {BookSelectionService, CheckboxClickEvent} from './book-selection.service';
import {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-params.service';
import {BookBrowserEntityService} from './book-browser-entity.service';
import {BookFilterOrchestrationService} from './book-filter-orchestration.service';
export enum EntityType {
LIBRARY = 'Library',
@@ -61,26 +60,6 @@ export enum EntityType {
UNSHELVED = 'Unshelved Books',
}
const QUERY_PARAMS = {
VIEW: 'view',
SORT: 'sort',
DIRECTION: 'direction',
FILTER: 'filter',
FMODE: 'fmode',
SIDEBAR: 'sidebar',
FROM: 'from',
};
const VIEW_MODES = {
GRID: 'grid',
TABLE: 'table',
};
const SORT_DIRECTION = {
ASCENDING: 'asc',
DESCENDING: 'desc',
};
@Component({
selector: 'app-book-browser',
standalone: true,
@@ -94,51 +73,58 @@ const SORT_DIRECTION = {
providers: [SeriesCollapseFilter],
animations: [
trigger('slideInOut', [
state('void', style({transform: 'translateY(100%)'})),
state('*', style({transform: 'translateY(0)'})),
transition(':enter', [animate('0.1s ease-in')]),
transition(':leave', [animate('0.1s ease-out')])
transition(':enter', [
style({transform: 'translateY(100%)'}),
animate('0.1s ease-in', style({transform: 'translateY(0)'}))
]),
transition(':leave', [
style({transform: 'translateY(0)'}),
animate('0.1s ease-out', style({transform: 'translateY(100%)'}))
])
])
]
})
export class BookBrowserComponent implements OnInit, AfterViewInit {
// Public injected services (used in template)
protected userService = inject(UserService);
protected coverScalePreferenceService = inject(CoverScalePreferenceService);
protected columnPreferenceService = inject(TableColumnPreferenceService);
protected sidebarFilterTogglePrefService = inject(SidebarFilterTogglePrefService);
private activatedRoute = inject(ActivatedRoute);
private messageService = inject(MessageService);
private libraryService = inject(LibraryService);
private bookService = inject(BookService);
private shelfService = inject(ShelfService);
private dialogHelperService = inject(BookDialogHelperService);
private bookMenuService = inject(BookMenuService);
private sortService = inject(SortService);
private router = inject(Router);
private libraryShelfMenuService = inject(LibraryShelfMenuService);
protected seriesCollapseFilter = inject(SeriesCollapseFilter);
protected confirmationService = inject(ConfirmationService);
protected magicShelfService = inject(MagicShelfService);
protected bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
protected taskHelperService = inject(TaskHelperService);
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
protected bookSelectionService = inject(BookSelectionService);
// Private injected services
private activatedRoute = inject(ActivatedRoute);
private messageService = inject(MessageService);
private bookService = inject(BookService);
private dialogHelperService = inject(BookDialogHelperService);
private bookMenuService = inject(BookMenuService);
private libraryShelfMenuService = inject(LibraryShelfMenuService);
private pageTitle = inject(PageTitleService);
private loadingService = inject(LoadingService);
private bookNavigationService = inject(BookNavigationService);
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
private queryParamsService = inject(BookBrowserQueryParamsService);
private entityService = inject(BookBrowserEntityService);
private filterOrchestrationService = inject(BookFilterOrchestrationService);
// Observables
bookState$: Observable<BookState> | undefined;
entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
entityType$: Observable<EntityType> | undefined;
searchTerm$ = new BehaviorSubject<string>('');
parsedFilters: Record<string, string[]> = {};
selectedFilter = new BehaviorSubject<Record<string, string[]> | null>(null);
selectedFilterMode = new BehaviorSubject<BookFilterMode>('and');
protected resetFilterSubject = new Subject<void>();
// State
parsedFilters: Record<string, string[]> = {};
entity: Library | Shelf | MagicShelf | null = null;
entityType: EntityType | undefined;
bookTitle = '';
entityOptions: MenuItem[] | undefined;
selectedBooks = new Set<number>();
isDrawerVisible = false;
dynamicDialogRef: DynamicDialogRef | undefined | null;
EntityType = EntityType;
@@ -149,12 +135,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
entityViewPreferences: EntityViewPreferences | undefined;
currentViewMode: string | undefined;
lastAppliedSort: SortOption | null = null;
showFilter = false;
private settingFiltersFromUrl = false;
protected metadataMenuItems: MenuItem[] | undefined;
protected bulkReadActionsMenuItems: MenuItem[] | undefined;
currentBooks: Book[] = [];
lastSelectedIndex: number | null = null;
showFilter = false;
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
private headerFilter = new HeaderFilter(this.searchTerm$);
@@ -167,6 +152,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
@ViewChild(BookFilterComponent, {static: false})
bookFilterComponent!: BookFilterComponent;
get selectedBooks(): Set<number> {
return this.bookSelectionService.selectedBooks;
}
get currentCardSize() {
return this.coverScalePreferenceService.currentCardSize;
}
@@ -213,49 +202,85 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
: filterSummary;
}
get seriesViewEnabled(): boolean {
return Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView);
}
get hasMetadataMenuItems(): boolean {
return this.metadataMenuItems!.length > 0;
}
get hasBulkReadActionsItems(): boolean {
return this.bulkReadActionsMenuItems!.length > 0;
}
ngOnInit(): void {
this.pageTitle.setPageTitle('')
this.pageTitle.setPageTitle('');
this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000)).subscribe();
this.initializeEntityRouting();
this.setupRouteChangeHandlers();
this.setupUserStateSubscription();
this.setupQueryParamSubscription();
this.setupSearchTermSubscription();
}
ngAfterViewInit(): void {
if (this.bookFilterComponent) {
this.bookFilterComponent.setFilters?.(this.parsedFilters);
this.bookFilterComponent.onFiltersChanged?.();
this.bookFilterComponent.selectedFilterMode = this.selectedFilterMode.getValue();
}
}
private initializeEntityRouting(): void {
const currentPath = this.activatedRoute.snapshot.routeConfig?.path;
if (currentPath === 'all-books' || currentPath === 'unshelved-books') {
const entityType = currentPath === 'all-books' ? EntityType.ALL_BOOKS : EntityType.UNSHELVED;
this.entityType = entityType;
this.entityType$ = of(entityType);
this.entity$ = of(null);
this.seriesCollapseFilter.setContext(null, null);
this.pageTitle.setPageTitle(currentPath === 'all-books' ? 'All Books' : 'Unshelved Books');
} else {
const routeEntityInfo$ = this.getEntityInfoFromRoute();
this.entityType$ = routeEntityInfo$.pipe(map(info => info.entityType));
const routeEntityInfo$ = this.entityService.getEntityInfoFromRoute(this.activatedRoute);
this.entityType$ = routeEntityInfo$.pipe(map(info => {
this.entityType = info.entityType;
return info.entityType;
}));
this.entity$ = routeEntityInfo$.pipe(
switchMap(({entityId, entityType}) => this.fetchEntity(entityId, entityType))
switchMap(({entityId, entityType}) => this.entityService.fetchEntity(entityId, entityType))
);
this.entity$.subscribe(entity => {
if (entity) {
this.pageTitle.setPageTitle(entity.name);
}
this.entity = entity ?? null;
this.updateSeriesCollapseContext();
this.entityOptions = entity
? this.isLibrary(entity)
? this.libraryShelfMenuService.initializeLibraryMenuItems(entity)
: this.isMagicShelf(entity)
? this.libraryShelfMenuService.initializeMagicShelfMenuItems(entity)
: this.libraryShelfMenuService.initializeShelfMenuItems(entity)
: [];
});
this.entity$.subscribe(entity => this.handleEntityLoaded(entity));
}
}
private handleEntityLoaded(entity: Library | Shelf | MagicShelf | null): void {
if (entity) {
this.pageTitle.setPageTitle(entity.name);
}
this.entity = entity ?? null;
this.updateSeriesCollapseContext();
this.entityOptions = entity
? this.entityService.isLibrary(entity)
? this.libraryShelfMenuService.initializeLibraryMenuItems(entity)
: this.entityService.isMagicShelf(entity)
? this.libraryShelfMenuService.initializeMagicShelfMenuItems(entity)
: this.libraryShelfMenuService.initializeShelfMenuItems(entity)
: [];
}
private setupRouteChangeHandlers(): void {
this.activatedRoute.paramMap.subscribe(() => {
this.searchTerm$.next('');
this.bookTitle = '';
this.deselectAllBooks();
this.bookSelectionService.deselectAll();
this.clearFilter();
});
}
private setupUserStateSubscription(): void {
this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded))
.subscribe(userState => {
this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems(
@@ -269,23 +294,28 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
});
this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user());
}
private setupQueryParamSubscription(): void {
combineLatest([
this.activatedRoute.paramMap,
this.activatedRoute.queryParamMap,
this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded))
]).subscribe(([_, queryParamMap, user]) => {
const parseResult = this.queryParamsService.parseQueryParams(
queryParamMap,
user.user?.userSettings?.entityViewPreferences,
this.entityType,
this.entity?.id ?? undefined,
this.bookSorter.sortOptions,
user.user?.userSettings?.filterMode ?? 'and'
);
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 filterMode = queryParamMap.get(QUERY_PARAMS.FMODE) || user.user?.userSettings?.filterMode;
if (filterMode && filterMode !== this.selectedFilterMode.getValue()) {
this.selectedFilterMode.next((filterMode as BookFilterMode));
// Apply filter mode
if (parseResult.filterMode !== this.selectedFilterMode.getValue()) {
this.selectedFilterMode.next(parseResult.filterMode);
if (this.bookFilterComponent) {
this.bookFilterComponent.selectedFilterMode = filterMode as BookFilterMode;
this.bookFilterComponent.selectedFilterMode = parseResult.filterMode;
}
}
@@ -293,28 +323,20 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.showFilter = value;
});
const parsedFilters: Record<string, string[]> = {};
// Apply filters
this.currentFilterLabel = 'All Books';
const filterParams = queryParamMap.get('filter');
if (filterParams) {
this.settingFiltersFromUrl = true;
this.selectedFilter.next(parseResult.filters);
filterParams.split(',').forEach(pair => {
const [key, ...valueParts] = pair.split(':');
const value = valueParts.join(':');
if (key && value) {
parsedFilters[key] = value.split('|').map(v => v.trim()).filter(Boolean);
}
});
this.selectedFilter.next(parsedFilters);
if (this.bookFilterComponent) {
this.bookFilterComponent.setFilters?.(parsedFilters);
this.bookFilterComponent.setFilters?.(parseResult.filters);
this.bookFilterComponent.onFiltersChanged?.();
}
if (Object.keys(parsedFilters).length > 0) {
if (Object.keys(parseResult.filters).length > 0) {
this.currentFilterLabel = this.computedFilterLabel;
}
@@ -325,95 +347,39 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.rawFilterParamFromUrl = null;
}
this.parsedFilters = parsedFilters;
this.parsedFilters = parseResult.filters;
// Apply preferences
this.entityViewPreferences = user.user?.userSettings?.entityViewPreferences;
const globalPrefs = this.entityViewPreferences?.global;
const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase().replaceAll(' ', '_') : undefined;
this.coverScalePreferenceService.initScaleValue(this.coverScalePreferenceService.scaleFactor);
this.columnPreferenceService.initPreferences(user.user?.userSettings?.tableColumnPreference);
this.visibleColumns = this.columnPreferenceService.visibleColumns;
const override = this.entityViewPreferences?.overrides?.find(o =>
o.entityType?.toUpperCase() === currentEntityTypeStr &&
o.entityId === this.entity?.id
);
const effectivePrefs = override?.preferences ?? globalPrefs ?? {
sortKey: 'addedOn',
sortDir: 'ASC',
view: 'GRID'
};
const userSortKey = effectivePrefs.sortKey;
const userSortDir = effectivePrefs.sortDir?.toUpperCase() === 'DESC'
? SortDirection.DESCENDING
: SortDirection.ASCENDING;
const effectiveSortKey = sortParam || userSortKey;
const effectiveSortDir = directionParam
? (directionParam.toLowerCase() === SORT_DIRECTION.DESCENDING ? SortDirection.DESCENDING : SortDirection.ASCENDING)
: userSortDir;
const matchedSort = this.bookSorter.sortOptions.find(opt => opt.field === effectiveSortKey);
this.bookSorter.selectedSort = matchedSort ? {
label: matchedSort.label,
field: matchedSort.field,
direction: effectiveSortDir
} : {
label: 'Added On',
field: 'addedOn',
direction: SortDirection.DESCENDING
};
const fromParam = queryParamMap.get(QUERY_PARAMS.FROM);
this.currentViewMode = fromParam === 'toggle'
? (viewParam === VIEW_MODES.TABLE || viewParam === VIEW_MODES.GRID
? viewParam
: VIEW_MODES.GRID)
: (effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID);
// Apply sort
this.bookSorter.selectedSort = parseResult.sortOption;
this.currentViewMode = parseResult.viewMode;
this.bookSorter.updateSortOptions();
if (this.lastAppliedSort?.field !== this.bookSorter.selectedSort.field || this.lastAppliedSort?.direction !== this.bookSorter.selectedSort.direction) {
if (this.lastAppliedSort?.field !== this.bookSorter.selectedSort.field ||
this.lastAppliedSort?.direction !== this.bookSorter.selectedSort.direction) {
this.lastAppliedSort = {...this.bookSorter.selectedSort};
this.applySortOption(this.bookSorter.selectedSort);
}
const queryParams: Record<string, string | number | null | undefined> = {
[QUERY_PARAMS.VIEW]: this.currentViewMode,
[QUERY_PARAMS.SORT]: this.bookSorter.selectedSort.field,
[QUERY_PARAMS.DIRECTION]: this.bookSorter.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING,
[QUERY_PARAMS.FMODE]: this.selectedFilterMode.getValue(),
};
if (Object.keys(parsedFilters).length > 0) {
queryParams[QUERY_PARAMS.FILTER] = Object.entries(parsedFilters).map(([k, v]) => `${k}:${v.join('|')}`).join(',');
}
const currentParams = this.activatedRoute.snapshot.queryParams;
const changed = Object.keys(queryParams).some(k => currentParams[k] !== queryParams[k]);
if (changed) {
const mergedParams = {...currentParams, ...queryParams};
this.router.navigate([], {
queryParams: mergedParams,
replaceUrl: true
});
}
});
this.searchTerm$.subscribe(term => {
this.hasSearchTerm = !!term && term.trim().length > 0;
// Sync query params
this.queryParamsService.syncQueryParams(
this.currentViewMode!,
this.bookSorter.selectedSort,
this.selectedFilterMode.getValue(),
this.parsedFilters
);
});
}
ngAfterViewInit() {
if (this.bookFilterComponent) {
this.bookFilterComponent.setFilters?.(this.parsedFilters);
this.bookFilterComponent.onFiltersChanged?.();
this.bookFilterComponent.selectedFilterMode = this.selectedFilterMode.getValue();
}
private setupSearchTermSubscription(): void {
this.searchTerm$.subscribe(term => {
this.hasSearchTerm = !!term && term.trim().length > 0;
});
}
onFilterSelected(filters: Record<string, any> | null): void {
@@ -425,37 +391,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
const hasSidebarFilters = !!filters && Object.keys(filters).length > 0;
this.currentFilterLabel = hasSidebarFilters ? this.computedFilterLabel : 'All Books';
const queryParam = hasSidebarFilters ? Object.entries(filters).map(([k, v]) => `${k}:${v.join('|')}`).join(',') : 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
});
}
this.queryParamsService.updateFilters(filters);
}
onFilterModeChanged(mode: BookFilterMode): void {
if (this.settingFiltersFromUrl || mode === this.selectedFilterMode.getValue()) return;
this.selectedFilterMode.next(mode);
// Clear filters if switching from multiple selected to single mode
const params: any = {[QUERY_PARAMS.FMODE]: mode};
if (mode === 'single') {
const categories = Object.keys(this.parsedFilters);
if (categories.length > 1 || (categories.length == 1 && this.parsedFilters[categories[0]].length > 1)) {
params[QUERY_PARAMS.FILTER] = null;
}
}
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: params,
queryParamsHandling: 'merge',
replaceUrl: false
});
this.queryParamsService.updateFilterMode(mode, this.parsedFilters);
}
toggleSidebar(): void {
@@ -467,68 +410,32 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.coverScalePreferenceService.setScale(this.coverScalePreferenceService.scaleFactor);
}
onVisibleColumnsChange(selected: { field: string; header: string }[]) {
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
const allFields = this.bookTableComponent.allColumns.map(col => col.field);
this.visibleColumns = selected.sort(
(a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field)
);
}
handleBookSelection(book: Book, selected: boolean) {
if (selected) {
if (book.seriesBooks) {
//it is a series
this.selectedBooks = new Set([...this.selectedBooks, ...book.seriesBooks.map(book => book.id)]);
} else {
this.selectedBooks.add(book.id);
}
} else {
if (book.seriesBooks) {
//it is a series
book.seriesBooks.forEach(book => {
this.selectedBooks.delete(book.id);
});
} else {
this.selectedBooks.delete(book.id);
}
}
}
onCheckboxClicked(event: { index: number; book: Book; selected: boolean; shiftKey: boolean }) {
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 book = this.currentBooks[i];
if (!book) continue;
this.handleBookSelection(book, !isUnselectingRange);
}
}
onCheckboxClicked(event: CheckboxClickEvent): void {
this.bookSelectionService.handleCheckboxClick(event);
this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user());
}
handleBookSelect(book: Book, selected: boolean): void {
this.handleBookSelection(book, selected);
this.isDrawerVisible = this.selectedBooks.size > 0;
this.bookSelectionService.handleBookSelection(book, selected);
this.isDrawerVisible = this.bookSelectionService.hasSelection();
this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user());
}
onSelectedBooksChange(selectedBookIds: Set<number>): void {
this.selectedBooks = new Set(selectedBookIds);
this.isDrawerVisible = this.selectedBooks.size > 0;
this.bookSelectionService.setSelectedBooks(selectedBookIds);
this.isDrawerVisible = this.bookSelectionService.hasSelection();
this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user());
}
selectAllBooks(): void {
if (!this.currentBooks) return;
for (const book of this.currentBooks) {
this.selectedBooks.add(book.id);
}
this.bookSelectionService.selectAll();
if (this.bookTableComponent) {
this.bookTableComponent.selectAllBooks();
}
@@ -536,7 +443,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
}
deselectAllBooks(): void {
this.selectedBooks.clear();
this.bookSelectionService.deselectAll();
this.isDrawerVisible = false;
if (this.bookTableComponent) {
this.bookTableComponent.clearSelectedBooks();
@@ -556,7 +463,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.bookService.deleteBooks(this.selectedBooks)
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe(() => {
this.selectedBooks.clear();
this.bookSelectionService.deselectAll();
});
}
});
@@ -568,38 +475,35 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
onManualSortChange(sortOption: SortOption): void {
this.applySortOption(sortOption);
const currentParams = this.activatedRoute.snapshot.queryParams;
const newParams = {
...currentParams,
sort: sortOption.field,
direction: sortOption.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING
};
this.router.navigate([], {
queryParams: newParams,
replaceUrl: true
});
this.queryParamsService.updateSort(sortOption);
}
applySortOption(sortOption: SortOption): void {
if (this.entityType === EntityType.ALL_BOOKS) {
this.bookState$ = this.fetchAllBooks();
this.bookState$ = this.entityService.fetchAllBooks(sortOption).pipe(
switchMap(bookState => this.applyBookFilters(bookState))
);
} else if (this.entityType === EntityType.UNSHELVED) {
this.bookState$ = this.fetchUnshelvedBooks();
this.bookState$ = this.entityService.fetchUnshelvedBooks(sortOption).pipe(
switchMap(bookState => this.applyBookFilters(bookState))
);
} else {
const routeParam$ = this.getEntityInfoFromRoute();
const routeParam$ = this.entityService.getEntityInfoFromRoute(this.activatedRoute);
this.bookState$ = routeParam$.pipe(
switchMap(({entityId, entityType}) => this.fetchBooksByEntity(entityId, entityType))
switchMap(({entityId, entityType}) =>
this.entityService.fetchBooksByEntity(entityId, entityType, sortOption)
),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
this.bookState$
.pipe(
filter(state => state.loaded && !state.error),
map(state => state.books || [])
)
.subscribe(books => {
this.currentBooks = books;
this.bookSelectionService.setCurrentBooks(books);
this.bookNavigationService.setAvailableBookIds(books.map(book => book.id));
});
}
@@ -614,11 +518,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.resetFilters();
}
resetFilters() {
resetFilters(): void {
this.resetFilterSubject.next();
}
clearFilter() {
clearFilter(): void {
if (this.selectedFilter.value !== null) {
this.selectedFilter.next(null);
}
@@ -627,27 +531,20 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
toggleTableGrid(): void {
this.currentViewMode = this.currentViewMode === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
this.router.navigate([], {
queryParams: {
view: this.currentViewMode,
[QUERY_PARAMS.FROM]: 'toggle'
},
queryParamsHandling: 'merge',
replaceUrl: true
});
this.queryParamsService.updateViewMode(this.currentViewMode as 'grid' | 'table');
}
unshelfBooks() {
unshelfBooks(): void {
if (!this.entity) return;
const count = this.selectedBooks.size;
const loader = this.loadingService.show(`Unshelving ${count} book(s)...`);
this.bookService.updateBookShelves(this.selectedBooks, new Set(), new Set([this.entity.id]))
this.bookService.updateBookShelves(this.selectedBooks, new Set(), new Set([this.entity.id!]))
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
next: () => {
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Books shelves updated'});
this.selectedBooks.clear();
this.bookSelectionService.deselectAll();
},
error: () => {
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update books shelves'});
@@ -660,7 +557,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(result => {
if (result.assigned) {
this.selectedBooks.clear();
this.bookSelectionService.deselectAll();
}
});
}
@@ -722,11 +619,15 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
});
}
moveFiles() {
moveFiles(): void {
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
}
private updateSeriesCollapseContext() {
user() {
return this.userService.getCurrentUser();
}
private updateSeriesCollapseContext(): void {
let type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF' | null = null;
let id: number | null = null;
@@ -750,211 +651,18 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.seriesCollapseFilter.setContext(type, id);
}
private isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
return (entity as Library).paths !== undefined;
}
private isMagicShelf(entity: Library | Shelf | MagicShelf | null): entity is MagicShelf {
return !!entity && 'filterJson' in entity;
}
private getEntityInfoFromRoute(): Observable<{ entityId: number; entityType: EntityType }> {
return this.activatedRoute.paramMap.pipe(
map(params => {
const libraryId = Number(params.get('libraryId') || NaN);
const shelfId = Number(params.get('shelfId') || NaN);
const magicShelfId = Number(params.get('magicShelfId') || NaN);
if (!isNaN(libraryId)) {
this.entityType = EntityType.LIBRARY;
return {entityId: libraryId, entityType: EntityType.LIBRARY};
} else if (!isNaN(shelfId)) {
this.entityType = EntityType.SHELF;
return {entityId: shelfId, entityType: EntityType.SHELF};
} else if (!isNaN(magicShelfId)) {
this.entityType = EntityType.MAGIC_SHELF;
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
} else {
this.entityType = EntityType.ALL_BOOKS;
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
})
);
}
private fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | MagicShelf | null> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchLibrary(entityId);
case EntityType.SHELF:
return this.fetchShelf(entityId);
case EntityType.MAGIC_SHELF:
return this.fetchMagicShelf(entityId);
default:
return of(null);
}
}
private fetchBooksByEntity(entityId: number, entityType: EntityType): Observable<BookState> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchBooks(book => book.libraryId === entityId);
case EntityType.SHELF:
return this.shelfService.getBooksOnShelf(entityId).pipe(
map(books => {
const sortedBooks = this.sortService.applySort(books, this.bookSorter.selectedSort!);
return {
books: sortedBooks,
loaded: true,
error: null
};
}),
switchMap(bookState => this.applyBookFilters(bookState))
);
case EntityType.MAGIC_SHELF:
return this.fetchBooksMagicShelfBooks(entityId);
case EntityType.ALL_BOOKS:
default:
return this.fetchAllBooks();
}
}
private fetchAllBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchUnshelvedBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => ({
...bookState,
books: (bookState.books || []).filter(book => !book.shelves || book.shelves.length === 0)
})),
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchBooksMagicShelfBooks(magicShelfId: number): Observable<BookState> {
return combineLatest([
this.bookService.bookState$,
this.magicShelfService.getShelf(magicShelfId)
]).pipe(
map(([bookState, magicShelf]) => {
if (!bookState.loaded || bookState.error || !magicShelf?.filterJson) {
return bookState;
}
const filteredBooks: Book[] | undefined = bookState.books?.filter(book =>
this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule)
);
const sortedBooks = this.sortService.applySort(filteredBooks ?? [], this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchBooks(bookFilter: (book: Book) => boolean): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
if (bookState.loaded && !bookState.error) {
const filteredBooks = bookState.books?.filter(bookFilter) || [];
const sortedBooks = this.sortService.applySort(filteredBooks, this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private shouldForceExpandSeries(): boolean {
const queryParams = this.activatedRoute.snapshot.queryParams;
const filterParam = queryParams[QUERY_PARAMS.FILTER];
return (
filterParam &&
typeof filterParam === 'string' &&
filterParam.split(',').some(pair => pair.trim().startsWith('series:'))
);
}
private applyBookFilters(bookState: BookState): Observable<BookState> {
const forceExpandSeries = this.shouldForceExpandSeries();
return this.headerFilter.filter(bookState).pipe(
switchMap(filtered => this.sideBarFilter.filter(filtered)),
switchMap(filtered => this.seriesCollapseFilter.filter(filtered, forceExpandSeries)),
map(filtered =>
(filtered.loaded && !filtered.error)
? ({
...filtered,
books: this.sortService.applySort(filtered.books || [], this.bookSorter.selectedSort!)
})
: filtered
)
const forceExpandSeries = this.filterOrchestrationService.shouldForceExpandSeries(
this.activatedRoute.snapshot.queryParamMap
);
}
private processBookState(bookState: BookState): BookState {
if (bookState.loaded && !bookState.error) {
const sortedBooks = this.sortService.applySort(bookState.books || [], this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}
private fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraryState$.pipe(
map(libraryState => {
if (libraryState.libraries) {
return libraryState.libraries.find(lib => lib.id === libraryId) || null;
}
return null;
})
return this.filterOrchestrationService.applyFilters(
bookState,
this.headerFilter,
this.sideBarFilter,
this.seriesCollapseFilter,
forceExpandSeries,
this.bookSorter.selectedSort!
);
}
private fetchShelf(shelfId: number): Observable<Shelf | null> {
return this.shelfService.shelfState$.pipe(
map(shelfState => {
if (shelfState.shelves) {
return shelfState.shelves.find(shelf => shelf.id === shelfId) || null;
}
return null;
})
);
}
private fetchMagicShelf(magicShelfId: number): Observable<MagicShelf | null> {
return this.magicShelfService.shelvesState$.pipe(
take(1),
switchMap((state) => {
const cached = state.shelves?.find(s => s.id === magicShelfId) ?? null;
if (cached) {
return of(cached);
}
return this.magicShelfService.getShelf(magicShelfId).pipe(
map(shelf => shelf ?? null),
catchError(() => of(null))
);
})
);
}
get seriesViewEnabled(): boolean {
return Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView);
}
get hasMetadataMenuItems(): boolean {
return this.metadataMenuItems!.length > 0;
}
get hasBulkReadActionsItems(): boolean {
return this.bulkReadActionsMenuItems!.length > 0;
}
user() {
return this.userService.getCurrentUser();
}
}
@@ -0,0 +1,59 @@
import {Injectable, inject} from '@angular/core';
import {Observable, BehaviorSubject} from 'rxjs';
import {map, switchMap} from 'rxjs/operators';
import {BookState} from '../../model/state/book-state.model';
import {SortOption} from '../../model/sort.model';
import {SortService} from '../../service/sort.service';
import {HeaderFilter} from './filters/HeaderFilter';
import {SideBarFilter} from './filters/SidebarFilter';
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
import {BookFilterMode} from '../../../settings/user-management/user.service';
import {ParamMap} from '@angular/router';
import {QUERY_PARAMS} from './book-browser-query-params.service';
@Injectable({providedIn: 'root'})
export class BookFilterOrchestrationService {
private sortService = inject(SortService);
applyFilters(
bookState: BookState,
headerFilter: HeaderFilter,
sideBarFilter: SideBarFilter,
seriesCollapseFilter: SeriesCollapseFilter,
forceExpandSeries: boolean,
sortOption: SortOption
): Observable<BookState> {
return headerFilter.filter(bookState).pipe(
switchMap(filtered => sideBarFilter.filter(filtered)),
switchMap(filtered => seriesCollapseFilter.filter(filtered, forceExpandSeries)),
map(filtered =>
(filtered.loaded && !filtered.error)
? ({
...filtered,
books: this.sortService.applySort(filtered.books || [], sortOption)
})
: filtered
)
);
}
shouldForceExpandSeries(queryParamMap: ParamMap): boolean {
const filterParam = queryParamMap.get(QUERY_PARAMS.FILTER);
return (
!!filterParam &&
typeof filterParam === 'string' &&
filterParam.split(',').some(pair => pair.trim().startsWith('series:'))
);
}
createHeaderFilter(searchTerm$: BehaviorSubject<string>): HeaderFilter {
return new HeaderFilter(searchTerm$);
}
createSideBarFilter(
selectedFilter$: BehaviorSubject<Record<string, string[]> | null>,
selectedFilterMode$: BehaviorSubject<BookFilterMode>
): SideBarFilter {
return new SideBarFilter(selectedFilter$, selectedFilterMode$);
}
}
@@ -0,0 +1,105 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {Book} from '../../model/book.model';
export interface CheckboxClickEvent {
index: number;
book: Book;
selected: boolean;
shiftKey: boolean;
}
@Injectable({providedIn: 'root'})
export class BookSelectionService {
private selectedBooksSubject = new BehaviorSubject<Set<number>>(new Set());
private currentBooks: Book[] = [];
private lastSelectedIndex: number | null = null;
selectedBooks$: Observable<Set<number>> = this.selectedBooksSubject.asObservable();
get selectedBooks(): Set<number> {
return this.selectedBooksSubject.value;
}
get selectedCount(): number {
return this.selectedBooksSubject.value.size;
}
setCurrentBooks(books: Book[]): void {
this.currentBooks = books;
}
getCurrentBooks(): Book[] {
return this.currentBooks;
}
selectBook(book: Book): void {
const current = new Set(this.selectedBooksSubject.value);
if (book.seriesBooks) {
book.seriesBooks.forEach(b => current.add(b.id));
} else {
current.add(book.id);
}
this.selectedBooksSubject.next(current);
}
deselectBook(book: Book): void {
const current = new Set(this.selectedBooksSubject.value);
if (book.seriesBooks) {
book.seriesBooks.forEach(b => current.delete(b.id));
} else {
current.delete(book.id);
}
this.selectedBooksSubject.next(current);
}
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;
const current = new Set(this.selectedBooksSubject.value);
for (const book of this.currentBooks) {
current.add(book.id);
}
this.selectedBooksSubject.next(current);
}
deselectAll(): void {
this.selectedBooksSubject.next(new Set());
this.lastSelectedIndex = null;
}
setSelectedBooks(bookIds: Set<number>): void {
this.selectedBooksSubject.next(new Set(bookIds));
}
hasSelection(): boolean {
return this.selectedBooksSubject.value.size > 0;
}
}
@@ -23,7 +23,7 @@ import {MetadataRefreshType} from "../../../metadata/model/request/metadata-refr
import {TieredMenu} from "primeng/tieredmenu";
import {Tooltip} from "primeng/tooltip";
import {Divider} from "primeng/divider";
import {animate, state, style, transition, trigger} from "@angular/animations";
import {animate, style, transition, trigger} from "@angular/animations";
import {Component, inject, OnDestroy} from '@angular/core';
@Component({
@@ -52,10 +52,14 @@ import {Component, inject, OnDestroy} from '@angular/core';
],
animations: [
trigger('slideInOut', [
state('void', style({transform: 'translateY(100%)'})),
state('*', style({transform: 'translateY(0)'})),
transition(':enter', [animate('0.1s ease-in')]),
transition(':leave', [animate('0.1s ease-out')])
transition(':enter', [
style({transform: 'translateY(100%)'}),
animate('0.1s ease-in', style({transform: 'translateY(0)'}))
]),
transition(':leave', [
style({transform: 'translateY(0)'}),
animate('0.1s ease-out', style({transform: 'translateY(100%)'}))
])
])
]
})