diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser-entity.service.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser-entity.service.ts new file mode 100644 index 000000000..b8b402907 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser-entity.service.ts @@ -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 { + 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 { + 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 { + 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 { + return this.bookService.bookState$.pipe( + map(bookState => this.processBookState(bookState, sortOption)) + ); + } + + fetchUnshelvedBooks(sortOption: SortOption): Observable { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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; + } +} diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser-query-params.service.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser-query-params.service.ts new file mode 100644 index 000000000..625d02ba2 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser-query-params.service.ts @@ -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; + filterMode: BookFilterMode; +} + +export interface QueryParseResult { + viewMode: string; + sortOption: SortOption; + filters: Record; + 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 | 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): void { + const params: Record = {[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 { + return Object.entries(filters) + .map(([k, v]) => `${k}:${v.join('|')}`) + .join(','); + } + + deserializeFilters(filterParam: string | null): Record { + const parsedFilters: Record = {}; + + 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 + ): void { + const queryParams: Record = { + [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:')) + ); + } +} diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html index 8daf99681..f70364cb0 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.html @@ -1,11 +1,11 @@ -
-
+
+
-
-
+
+
@if (entityType$ | async; as entityType) { -
-

+

+

@if (entityType === EntityType.ALL_BOOKS) { @if (currentFilterLabel && rawFilterParamFromUrl) { {{ currentFilterLabel }} @@ -21,7 +21,7 @@ }

@if (seriesCollapseFilter.isSeriesCollapsed && (bookState$ | async)?.books; as books) { -

+

Showing {{ books.length }} {{ books.length === 1 ? 'item' : 'items' }} (series collapsed)

} @@ -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)) { -
+
-
-
+
+
@if (isFilterActive) { + tooltipPosition="top"> } @@ -67,7 +66,7 @@ -
+
-
+