feat(ui): New sidebar & search UI (#831)

This commit is contained in:
Alex
2026-05-04 09:46:48 +01:00
committed by GitHub
parent c9b2a5734e
commit f3138a88c5
182 changed files with 8318 additions and 4660 deletions
@@ -47,7 +47,7 @@
<div class="toolbar-actions">
<div class="toolbar-icons">
@if (isFilterActive()) {
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="clearFilter()" (keydown.enter)="clearFilter()">
<a class="toolbar-item" role="button" tabindex="0" (click)="clearFilter()" (keydown.enter)="clearFilter()">
<i
class="pi pi-filter-slash filter-clear-icon"
[pTooltip]="t('tooltip.clearFilters')"
@@ -58,7 +58,7 @@
@if (currentViewMode() === 'table') {
<div>
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="columnPopover.toggle($event)" (keydown.enter)="columnPopover.toggle($event)">
<a class="toolbar-item" role="button" tabindex="0" (click)="columnPopover.toggle($event)" (keydown.enter)="columnPopover.toggle($event)">
<i
class="pi pi-eye"
[pTooltip]="t('tooltip.visibleColumns')"
@@ -90,7 +90,7 @@
</p-popover>
</div>
}
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
<a class="toolbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
<i
[class]="viewIcon()"
[pTooltip]="t('tooltip.toggleView')"
@@ -99,7 +99,7 @@
</a>
<div>
<a
class="topbar-items topbar-item"
class="toolbar-item"
role="button"
tabindex="0"
(click)="seriesCollapseOverlay.toggle($event)"
@@ -164,7 +164,7 @@
</div>
<div class="sort-button-wrapper">
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="sortPopover.toggle($event)" (keydown.enter)="sortPopover.toggle($event)">
<a class="toolbar-item" role="button" tabindex="0" (click)="sortPopover.toggle($event)" (keydown.enter)="sortPopover.toggle($event)">
<i
class="pi pi-sort"
[pTooltip]="t('tooltip.selectSorting')"
@@ -191,7 +191,7 @@
<div class="mobile-search-wrapper">
<button
type="button"
class="topbar-items topbar-item"
class="toolbar-item"
(click)="searchDropdown.toggle($event)"
[pTooltip]="t('tooltip.search')"
tooltipPosition="top"
@@ -243,7 +243,7 @@
}
</div>
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="toggleSidebar()" (keydown.enter)="toggleSidebar()">
<a class="toolbar-item" role="button" tabindex="0" (click)="toggleSidebar()" (keydown.enter)="toggleSidebar()">
<i
[ngClass]="showFilter() ? 'pi pi-filter-fill' : 'pi pi-filter'"
[pTooltip]="t('tooltip.toggleSidebar')"
@@ -270,62 +270,63 @@
</p>
</div>
} @else {
@let visibleBooks = books();
@if (visibleBooks.length === 0 && !isBooksLoading()) {
<div class="no-books-container">
<p class="no-books-text">
{{ t('labels.noBooks') }}
</p>
</div>
}
@if (currentViewMode() === 'table' && (visibleBooks.length > 0 || showTableLoadingPlaceholder())) {
<app-book-table
[books]="visibleBooks"
[virtualRowCount]="virtualRowCount()"
[loadedBookCount]="loadedBookCount()"
[isFetchingNextPage]="isFetchingNextBooksPage()"
[bookQueryToken]="bookQueryToken()"
(selectAllRequested)="selectAllBooks()"
(loadNextPage)="loadNextBooksPage()"
[visibleColumns]="visibleColumns()"
[useSquareCovers]="isAudiobookOnlyLibrary()"
></app-book-table>
}
@if (currentViewMode() === 'grid') {
<div #scrollElement class="virtual-scroller">
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
@if (visibleBooks[virtualItem.index]; as book) {
<div
class="virtual-cell"
[style.width.px]="virtualGrid.itemWidth()"
[style.height.px]="virtualItem.size"
[style.transform]="virtualGrid.itemTransform(virtualItem)">
<app-book-card
[index]="virtualItem.index"
[book]="book"
[isCheckboxEnabled]="true"
[seriesViewEnabled]="seriesViewEnabled()"
[onBookSelect]="onBookCardSelect"
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="bookSelectionService.isBookSelected(book)"
[useSquareCovers]="isAudiobookOnlyLibrary()"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
} @else {
<div
class="virtual-cell virtual-loader-cell"
[style.width.px]="virtualGrid.itemWidth()"
[style.height.px]="virtualItem.size"
[style.transform]="virtualGrid.itemTransform(virtualItem)"></div>
}
}
<div class="book-browser-content">
@let visibleBooks = books();
@if (visibleBooks.length === 0 && !isBooksLoading()) {
<div class="no-books-container">
<p class="no-books-text">
{{ t('labels.noBooks') }}
</p>
</div>
</div>
}
@if (userService.currentUser(); as currentUser) {
}
@if (currentViewMode() === 'table' && (visibleBooks.length > 0 || showTableLoadingPlaceholder())) {
<app-book-table
[books]="visibleBooks"
[virtualRowCount]="virtualRowCount()"
[loadedBookCount]="loadedBookCount()"
[isFetchingNextPage]="isFetchingNextBooksPage()"
[bookQueryToken]="bookQueryToken()"
(selectAllRequested)="selectAllBooks()"
(loadNextPage)="loadNextBooksPage()"
[visibleColumns]="visibleColumns()"
[useSquareCovers]="isAudiobookOnlyLibrary()"
></app-book-table>
}
@if (currentViewMode() === 'grid') {
<div #scrollElement class="virtual-scroller">
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
@if (visibleBooks[virtualItem.index]; as book) {
<div
class="virtual-cell"
[style.width.px]="virtualGrid.itemWidth()"
[style.height.px]="virtualItem.size"
[style.transform]="virtualGrid.itemTransform(virtualItem)">
<app-book-card
[index]="virtualItem.index"
[book]="book"
[isCheckboxEnabled]="true"
[seriesViewEnabled]="seriesViewEnabled()"
[onBookSelect]="onBookCardSelect"
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="bookSelectionService.isBookSelected(book)"
[useSquareCovers]="isAudiobookOnlyLibrary()"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
} @else {
<div
class="virtual-cell virtual-loader-cell"
[style.width.px]="virtualGrid.itemWidth()"
[style.height.px]="virtualItem.size"
[style.transform]="virtualGrid.itemTransform(virtualItem)"></div>
}
}
</div>
</div>
}
@if (userService.currentUser(); as currentUser) {
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
<div class="footer-content">
<div class="footer-left">
@@ -448,6 +449,7 @@
</div>
</div>
}
</div>
}
</div>
@@ -5,6 +5,8 @@
flex-direction: row;
min-width: 0;
width: 100%;
height: 100%;
min-height: 0;
}
.book-browser-main {
@@ -13,6 +15,16 @@
flex: 1 1 0;
min-width: 0;
width: auto;
min-height: 0;
}
.book-browser-content {
position: relative;
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-width: 0;
min-height: 0;
}
// Header bar
@@ -22,16 +34,13 @@
justify-content: space-between;
gap: 0.25rem;
padding: 0.35rem;
border-radius: 0.75rem 0.75rem 0 0;
margin-bottom: 0.5rem;
margin-right: 2px;
background-color: var(--card-background);
border: 1px solid var(--p-content-border-color);
border-bottom: 1px solid var(--p-content-border-color);
@media (width >= 768px) {
gap: 1rem;
padding: 0.5rem 1rem;
margin-bottom: 1rem;
}
}
@@ -337,15 +346,10 @@
// Virtual scroller and grid
.virtual-scroller {
width: 100%;
height: calc(100dvh - 10.9rem);
padding: 1rem 0;
height: 100%;
padding: 1rem;
box-sizing: border-box;
overflow-y: auto;
@media (width <= 768px) {
height: calc(100dvh - 9rem);
padding: 0.75rem;
}
}
.virtual-loader-cell {
@@ -385,8 +389,8 @@
border-radius: 0.5rem;
}
// Topbar items (icon buttons)
.topbar-item {
// Toolbar actions (icon buttons)
.toolbar-item {
display: inline-flex;
align-items: center;
justify-content: center;
@@ -33,6 +33,8 @@ import {SortService} from '../../service/sort.service';
import {TranslocoService} from '@jsverse/transloco';
import {AppBooksApiService} from '../../service/app-books-api.service';
import {AppBookFilters, AppBookSort} from '../../model/app-book.model';
import {LayoutService} from '../../../../shared/layout/layout.service';
import {type VirtualGridMetrics} from '../../../../shared/util/virtual-grid.util';
function makeBook(id: number, libraryId: number, title: string, addedOn: string): Book {
return {
@@ -261,6 +263,7 @@ function createHarness(options?: {
},
},
{provide: AppSettingsService, useValue: {appSettings: vi.fn(() => null)}},
{provide: LayoutService, useValue: {sidebarTransitioning: signal(false)}},
{
provide: ActivatedRoute,
useValue: {
@@ -470,6 +473,23 @@ describe('BookBrowserComponent', () => {
expect(component.showTableLoadingPlaceholder()).toBe(false);
});
it('sizes grid loading placeholders to fill the viewport', () => {
const {component} = createHarness({books: [], isBooksLoading: true});
const loadingGrid = component as unknown as {
minimumLoadingGridItemCount(metrics: VirtualGridMetrics): number;
};
component.currentViewMode.set(VIEW_MODES.GRID);
expect(loadingGrid.minimumLoadingGridItemCount({
viewportWidth: 960,
viewportHeight: 900,
columns: 6,
itemHeight: 200,
gap: 20,
})).toBe(36);
});
it('calls SeriesCollapseFilter.collapseBooks when computing books', () => {
createHarness();
const filter = TestBed.inject(SeriesCollapseFilter);
@@ -54,8 +54,9 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {SortService} from '../../service/sort.service';
import {AppBooksApiService} from '../../service/app-books-api.service';
import {AppBookFilters} from '../../model/app-book.model';
import {createVirtualGrid, scaleForGridColumns} from '../../../../shared/util/virtual-grid.util';
import {createVirtualGrid, scaleForGridColumns, type VirtualGridMetrics} from '../../../../shared/util/virtual-grid.util';
import {GridDensityButtonsComponent} from '../../../../shared/components/grid-density-buttons/grid-density-buttons.component';
import {LayoutService} from '../../../../shared/layout/layout.service';
export enum EntityType {
LIBRARY = 'Library',
@@ -111,6 +112,7 @@ export class BookBrowserComponent implements AfterViewInit {
private appBooksApi = inject(AppBooksApiService);
private localStorageService = inject(LocalStorageService);
private scrollService = inject(RouteScrollPositionService);
private layoutService = inject(LayoutService);
private readonly t = inject(TranslocoService);
private readonly destroyRef = inject(DestroyRef);
@@ -322,8 +324,10 @@ export class BookBrowserComponent implements AfterViewInit {
gap: this.virtualGridGap,
columns: this.virtualGridColumns,
count: this.virtualRowCount,
minimumCount: metrics => this.minimumLoadingGridItemCount(metrics),
initialOffset: this.initialScrollOffset,
fillItemWidth: true,
deferViewportUpdates: this.layoutService.sidebarTransitioning,
estimateItemHeight: itemWidth => this.isMobile()
? this.mobileCardSizeForWidth(itemWidth).height
: this.cardSizeForWidth(itemWidth).height,
@@ -515,6 +519,18 @@ export class BookBrowserComponent implements AfterViewInit {
return renderedBookCount + 1;
}
private minimumLoadingGridItemCount({viewportHeight, columns, itemHeight, gap}: VirtualGridMetrics): number {
if (!this.showBooksLoadingPlaceholder() || this.currentViewMode() !== VIEW_MODES.GRID) {
return 0;
}
if (viewportHeight <= 0 || itemHeight <= 0) {
return INITIAL_LOADING_ROW_COUNT;
}
const visibleRows = Math.ceil((viewportHeight + gap) / (itemHeight + gap));
return Math.max(INITIAL_LOADING_ROW_COUNT, (visibleRows + 1) * columns);
}
readonly viewIcon = computed(() =>
this.currentViewMode() === VIEW_MODES.TABLE ? 'pi pi-table' : 'pi pi-objects-column'
);
@@ -1,5 +1,14 @@
:host ::ng-deep p-accordion-header {
:host ::ng-deep p-accordion {
--p-accordion-header-padding: 0.6rem 1rem;
--p-accordion-header-background: var(--card-background);
--p-accordion-header-active-background: var(--card-background);
--p-accordion-header-hover-background: var(--surface-hover);
--p-accordion-header-active-hover-background: var(--surface-hover);
--p-accordion-content-background: var(--card-background);
}
:host ::ng-deep .p-accordionpanel {
background: var(--card-background);
}
:host ::ng-deep .p-togglebutton {
@@ -12,7 +21,7 @@
}
.book-filter-container {
height: calc(100dvh - 6.1rem);
height: 100%;
border-radius: 0.75rem;
overflow: hidden;
background: var(--card-background);
@@ -79,7 +88,6 @@
.filter-row {
cursor: pointer;
transition: colors 200ms ease-in-out;
height: 26px;
display: flex;
flex-direction: row;
@@ -87,6 +95,7 @@
justify-content: space-between;
gap: 0.5rem;
max-width: 97%;
transition: color var(--transition-base);
&.active {
color: var(--primary-color);
@@ -1,5 +1,8 @@
:host {
display: block;
display: flex;
flex-direction: column;
flex: 1 1 auto;
width: 100%;
min-height: 0;
--book-table-border-color: var(--p-datatable-border-color, color-mix(in srgb, var(--p-content-border-color) 82%, black));
@@ -28,14 +31,10 @@
.book-table-scroll {
box-sizing: border-box;
height: calc(100dvh - 150px);
border: 1px solid var(--book-table-border-color);
flex: 1 1 auto;
min-height: 0;
overflow: auto;
background: var(--book-table-row-background);
@media (width <= 768px) {
height: calc(100dvh - 125px);
}
}
.book-table {
@@ -1,92 +0,0 @@
<ng-container *transloco="let t; prefix: 'book.searcher'">
<div class="book-searcher-container">
<p-iconfield class="search-iconfield" [class.focused]="isSearchFocused" [class.has-results]="isDropdownOpen">
<p-inputicon class="pi pi-search"/>
<input
type="text"
pInputText
[(ngModel)]="searchQuery"
(input)="onSearchInputChange()"
(focus)="isSearchFocused = true"
(keydown)="onKeydown($event)"
[placeholder]="t('placeholder')"
class="search-input"
/>
@if (searchQuery) {
<p-button
icon="pi pi-times"
(click)="clearSearch()"
[text]="true"
[rounded]="true"
class="clear-search-btn"
[attr.aria-label]="t('clearSearch')">
</p-button>
}
</p-iconfield>
<p-popover #resultsPopover [appendTo]="'body'" [styleClass]="'search-results-popover'">
<div
class="search-dropdown layout-menu show"
>
@if (isLoading) {
@for (i of [1,2,3]; track i) {
<div class="search-skeleton-item">
<p-skeleton width="50px" height="67px" borderRadius="4px"/>
<div class="search-skeleton-details">
<p-skeleton width="80%" height="1rem"/>
<p-skeleton width="60%" height="0.8rem"/>
</div>
</div>
}
} @else if (books.length > 0) {
@for (book of books; track book; let idx = $index) {
<div
class="search-dropdown-item"
[class.active]="activeIndex === idx"
role="button"
tabindex="0"
(click)="onBookClick(book)"
(keydown.enter)="onBookClick(book)">
<div class="search-item-content">
@if (urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn); as coverUrl) {
<img
[attr.src]="coverUrl"
[alt]="t('bookCoverAlt')"
class="search-book-cover"
/>
} @else {
<app-cover-placeholder class="search-book-cover" [title]="book.metadata?.title ?? ''" [author]="(book.metadata?.authors ?? []).join(', ')" size="sm" />
}
<div class="search-book-details">
<div class="search-book-title-container">
<p class="search-book-name">
{{ book.metadata?.title | slice: 0:70 }}
</p>
</div>
<div class="search-book-meta-line">
@if (book.metadata?.authors?.length ?? 0 > 0) {
<p class="search-book-authors">{{ t('byPrefix') }} {{ getAuthorNames(book.metadata?.authors) }}</p>
}
@if (getPublishedYear(book.metadata?.publishedDate)) {
<span class="metadata-badge year-badge">{{ getPublishedYear(book.metadata?.publishedDate) }}</span>
}
</div>
@if (getSeriesInfo(book.metadata?.seriesName, book.metadata?.seriesNumber)) {
<div class="search-book-series metadata-badge series-badge">
<i class="pi pi-book"></i>
<span>{{ getSeriesInfo(book.metadata?.seriesName, book.metadata?.seriesNumber) }}</span>
</div>
}
</div>
</div>
</div>
}
} @else {
<div class="search-dropdown-item no-results">
<span>{{ t('noResults') }}</span>
</div>
}
</div>
</p-popover>
</div>
</ng-container>
@@ -1,241 +0,0 @@
.book-searcher-container {
margin-left: 0.5rem;
position: relative;
width: 100%;
min-width: 0;
@media (width >= 768px) {
margin-left: 1.25rem;
width: var(--app-search-width-desktop);
max-width: 100%;
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
}
// Popover styles moved to global src/styles.scss due to appendTo="body"
.search-iconfield {
width: 100%;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 8px;
@media (width >= 640px) {
display: flex;
}
&.focused {
background: color-mix(in srgb, var(--primary-color) 5%, transparent);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--primary-color) 20%, transparent);
.search-input {
border-color: var(--primary-color);
}
}
}
.search-input {
width: 100%;
padding-right: 2.5rem;
height: 2.5rem;
line-height: 2.5rem;
font-size: 1rem;
background: var(--surface-800) !important;
border: 1px solid var(--surface-600);
transition: all 0.2s ease;
&:hover {
border-color: var(--surface-500);
background: var(--surface-700) !important;
}
}
.clear-search-btn {
position: absolute;
right: 0.5rem;
top: 50%;
transform: translateY(-50%);
display: none;
@media (width >= 640px) {
display: inline-flex;
}
}
.search-dropdown {
width: 100%;
background: transparent; // Glassmorphism handled by parent .search-results-popover
border: none;
border-radius: 8px;
max-height: min(70vh, calc(100dvh - 4rem));
overflow-y: auto;
// Desktop width constraints moved to src/styles.scss for body-appended elements
}
// .show class no longer needed as popover handles visibility
.search-dropdown-item {
display: flex;
flex-direction: column;
cursor: pointer;
transition: background-color 0.2s ease;
border-bottom: 1px solid color-mix(in srgb, var(--border-color) 50%, transparent);
&:first-child {
border-radius: 8px 8px 0 0;
}
&:last-child {
border-radius: 0 0 8px 8px;
border-bottom: none;
}
&:hover,
&.active {
background-color: var(--surface-hover);
}
&.no-results {
padding: 2rem 1rem;
text-align: center;
color: var(--text-secondary-color);
font-style: italic;
}
}
.search-item-content {
display: flex;
flex-direction: row;
align-items: flex-start;
gap: 1rem;
width: 100%;
padding: 0.75rem 1rem;
}
.search-book-cover {
width: 50px;
height: 67px;
min-width: 50px;
object-fit: cover;
border-radius: 4px;
box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
background-color: var(--ground-background);
aspect-ratio: 2/3;
}
.search-book-details {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.search-book-title-container {
display: flex;
align-items: flex-start;
}
.search-book-name {
font-weight: 600;
font-size: 0.95rem;
line-height: 1.4;
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
overflow-wrap: anywhere;
margin: 0;
}
.search-book-meta-line {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.search-book-authors {
font-size: 0.9rem;
font-style: italic;
color: var(--text-secondary-color);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin: 0;
flex: 1;
min-width: 0;
}
.search-book-year {
font-size: 0.8rem;
color: var(--text-secondary-color);
background-color: var(--ground-background);
padding: 0.125rem 0.5rem;
border-radius: 4px;
white-space: nowrap;
font-weight: 500;
}
.search-book-series {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.8rem;
color: var(--primary-color);
padding: 0.075rem 0.125rem;
border-radius: 4px;
width: fit-content;
i {
font-size: 0.75rem;
}
span {
font-weight: 500;
}
}
.search-book-metadata {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
}
.metadata-badge {
display: inline-flex;
align-items: center;
gap: 0.25rem;
font-size: 0.8rem;
padding: 0.1rem 0.25rem;
border-radius: 4px;
background-color: var(--surface-hover);
color: var(--text-secondary-color);
white-space: nowrap;
i {
font-size: 0.7rem;
}
&.series-badge {
background-color: color-mix(in srgb, var(--p-primary-color) 10%, transparent);
color: var(--p-primary-color);
}
}
.search-skeleton-item {
display: flex;
flex-direction: row;
gap: 1rem;
padding: 0.75rem 1rem;
}
.search-skeleton-details {
display: flex;
flex-direction: column;
gap: 0.5rem;
flex: 1;
}
@@ -1,14 +0,0 @@
import {describe, it} from 'vitest';
// NOTE(frontend-seam): Real coverage here needs seams around debounced signal-to-observable
// search state, global document click listeners, and router navigation so search dropdown behavior
// can be tested without a browser-event harness.
describe.skip('BookSearcherComponent', () => {
it('needs debounce seams to verify filtered-book output, loading state, and active-index reset behavior', () => {
// TODO(seam): Cover the debounced search signal and filteredBooks computed state once timing concerns are extracted for direct control.
});
it('needs event seams to verify keyboard navigation, outside-click clearing, and routed book selection', () => {
// TODO(seam): Cover onKeydown and onDocumentClick after isolating host listeners and router side effects behind adapters.
});
});
@@ -1,162 +0,0 @@
import {Component, ElementRef, HostListener, computed, inject, signal, ViewChild} from '@angular/core';
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';
import {Book} from '../../model/book.model';
import {FormsModule} from '@angular/forms';
import {InputText} from 'primeng/inputtext';
import {BookService} from '../../service/book.service';
import {Button} from 'primeng/button';
import {SlicePipe} from '@angular/common';
import {Skeleton} from 'primeng/skeleton';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
import {Router} from '@angular/router';
import {IconField} from 'primeng/iconfield';
import {InputIcon} from 'primeng/inputicon';
import {filterBooksBySearchTerm} from '../book-browser/filters/HeaderFilter';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Popover} from 'primeng/popover';
@Component({
selector: 'app-book-searcher',
templateUrl: './book-searcher.component.html',
imports: [
FormsModule,
InputText,
Button,
SlicePipe,
Skeleton,
IconField,
InputIcon,
TranslocoDirective,
CoverPlaceholderComponent,
Popover,
],
styleUrls: ['./book-searcher.component.scss'],
standalone: true
})
export class BookSearcherComponent {
searchQuery = '';
activeIndex = -1;
isSearchFocused = false;
private readonly searchTerm = signal('');
private readonly debouncedSearchTerm = toSignal(
toObservable(this.searchTerm).pipe(
debounceTime(200),
distinctUntilChanged()
),
{initialValue: ''}
);
private readonly filteredBooks = computed(() => {
const term = this.debouncedSearchTerm().trim();
if (term.length < 2) {
return [];
}
return filterBooksBySearchTerm(this.bookService.books(), term).slice(0, 50);
});
private bookService = inject(BookService);
private router = inject(Router);
protected urlHelper = inject(UrlHelperService);
private readonly t = inject(TranslocoService);
private elRef = inject(ElementRef);
@ViewChild('resultsPopover') resultsPopover?: Popover;
get books(): Book[] {
return this.filteredBooks();
}
get isLoading(): boolean {
const rawTerm = this.searchTerm().trim();
return rawTerm.length >= 2 && rawTerm !== this.debouncedSearchTerm().trim();
}
getAuthorNames(authors: string[] | undefined): string {
return authors?.join(', ') || this.t.translate('book.searcher.unknownAuthor');
}
getPublishedYear(publishedDate: string | undefined): string | null {
if (!publishedDate) return null;
const year = publishedDate.split('-')[0];
return year && year.length === 4 ? year : null;
}
getSeriesInfo(seriesName: string | undefined, seriesNumber: number | null | undefined): string | null {
if (!seriesName) return null;
if (seriesNumber) {
return `${seriesName} #${seriesNumber}`;
}
return seriesName;
}
onSearchInputChange(): void {
this.searchTerm.set(this.searchQuery.trim());
this.activeIndex = -1;
if (this.isDropdownOpen) {
setTimeout(() => this.showPopover());
} else {
this.resultsPopover?.hide();
}
}
private showPopover(): void {
if (this.resultsPopover) {
const inputElement = this.elRef.nativeElement.querySelector('.search-input');
this.resultsPopover.show(null, inputElement);
}
}
onBookClick(book: Book): void {
this.clearSearch();
this.router.navigate(['/book', book.id], {
queryParams: {tab: 'view'}
});
}
clearSearch(): void {
this.searchQuery = '';
this.searchTerm.set('');
this.activeIndex = -1;
this.resultsPopover?.hide();
}
get isDropdownOpen(): boolean {
return this.books.length > 0 || this.isLoading;
}
@HostListener('document:click', ['$event'])
onDocumentClick(event: Event): void {
if (!this.elRef.nativeElement.contains(event.target)) {
this.clearSearch();
this.isSearchFocused = false;
}
}
onKeydown(event: KeyboardEvent): void {
if (!this.isDropdownOpen) return;
switch (event.key) {
case 'ArrowDown':
this.activeIndex = Math.min(this.activeIndex + 1, this.books.length - 1);
event.preventDefault();
break;
case 'ArrowUp':
this.activeIndex = Math.max(this.activeIndex - 1, 0);
event.preventDefault();
break;
case 'Enter':
if (this.activeIndex >= 0 && this.activeIndex < this.books.length) {
this.onBookClick(this.books[this.activeIndex]);
}
break;
case 'Escape':
this.clearSearch();
(event.target as HTMLElement).blur();
break;
}
}
}
@@ -1,19 +1,22 @@
.tabpanels-responsive {
height: calc(100dvh - 9.7rem);
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
@media (width <= 768px) {
.tabpanels-responsive {
height: calc(100dvh - 8.5rem);
}
.series-wrapper {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
position: relative;
}
.series-wrapper {
position: relative;
border-radius: 0.75rem;
overflow: hidden;
border: 1px solid var(--p-content-border-color);
.series-wrapper > p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.series-main {
@@ -1,5 +1,7 @@
import {SortOption} from './sort.model';
export type ShelfSystemKey = 'kobo';
export interface Shelf {
id?: number;
name: string;
@@ -9,4 +11,5 @@ export interface Shelf {
publicShelf?: boolean;
userId?: number;
bookCount?: number;
systemKey?: ShelfSystemKey | null;
}
@@ -136,6 +136,15 @@ export class AppBooksApiService {
}
}
searchBooks(query: string, size = 20): Observable<AppPageResponse<AppBookSummary>> {
const params = new HttpParams()
.set('q', query.trim())
.set('page', '0')
.set('size', Math.max(1, size).toString());
return this.http.get<AppPageResponse<AppBookSummary>>(`${this.booksUrl}/search`, {params});
}
fetchNextPage(): void {
this.booksQuery.fetchNextPage();
}
@@ -1,14 +1,243 @@
import {describe, it} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {of} from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import type {MenuItem, MenuItemCommandEvent} from 'primeng/api';
import {ConfirmationService, MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
// NOTE(frontend-seam): Real coverage here needs a seam around nested Prime confirmation payloads,
// router/navigation side effects, clipboard writes, and multiple dialog/task services so menu-item
// command wiring can be asserted without turning the spec into a brittle integration harness.
describe.skip('LibraryShelfMenuService', () => {
it('needs a menu-command seam to verify library, shelf, and magic-shelf action wiring deterministically', () => {
// TODO(seam): Cover confirmation payloads, delete/refresh commands, and dialog launches after introducing a thin menu-action adapter.
import {LibraryShelfMenuService} from './library-shelf-menu.service';
import {LibraryService} from './library.service';
import {ShelfService} from './shelf.service';
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
import {UserService} from '../../settings/user-management/user.service';
import {LoadingService} from '../../../core/services/loading.service';
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
import {MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import type {Library} from '../model/library.model';
import type {Shelf} from '../model/shelf.model';
import type {MagicShelf} from '../../magic-shelf/service/magic-shelf.service';
function buildLibrary(overrides: Partial<Library> = {}): Library {
return {
id: 7,
name: 'Main Library',
watch: true,
paths: [],
...overrides,
};
}
function buildShelf(overrides: Partial<Shelf> = {}): Shelf {
return {
id: 11,
name: 'Favorites',
userId: 3,
publicShelf: false,
...overrides,
};
}
function buildMagicShelf(overrides: Partial<MagicShelf> = {}): MagicShelf {
return {
id: 13,
name: 'Magic Shelf',
filterJson: '{}',
isPublic: false,
...overrides,
};
}
function findMenuItem(items: MenuItem[], label: string): MenuItem {
const item = items
.flatMap(candidate => candidate.items ?? [candidate])
.find(candidate => candidate.label === label);
expect(item).toBeDefined();
return item!;
}
function runCommand(item: MenuItem): void {
item.command?.({ item } as MenuItemCommandEvent);
}
describe('LibraryShelfMenuService', () => {
let service: LibraryShelfMenuService;
const confirmationService = {
confirm: vi.fn(),
};
const messageService = {
add: vi.fn(),
};
const libraryService = {
refreshLibrary: vi.fn(() => of(undefined)),
deleteLibrary: vi.fn(() => of(undefined)),
};
const shelfService = {
deleteShelf: vi.fn(() => of(undefined)),
};
const taskHelperService = {
refreshMetadataTask: vi.fn(() => of(undefined)),
};
const userService = {
getCurrentUser: vi.fn(() => ({id: 3, permissions: {admin: false}})),
};
const router = {
navigate: vi.fn(),
};
const dialogLauncherService = {
openLibraryEditDialog: vi.fn(),
openLibraryMetadataFetchDialog: vi.fn(),
openShelfEditDialog: vi.fn(),
openMagicShelfEditDialog: vi.fn(),
};
const magicShelfService = {
deleteShelf: vi.fn(() => of(undefined)),
};
const loadingService = {
show: vi.fn(() => 'loader-token'),
hide: vi.fn(),
};
const bookDialogHelperService = {
openAddPhysicalBookDialog: vi.fn(),
openBulkIsbnImportDialog: vi.fn(),
openDuplicateMergerDialog: vi.fn(),
};
const translocoService = {
translate: vi.fn((key: string) => key),
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
LibraryShelfMenuService,
{provide: ConfirmationService, useValue: confirmationService},
{provide: MessageService, useValue: messageService},
{provide: LibraryService, useValue: libraryService},
{provide: ShelfService, useValue: shelfService},
{provide: TaskHelperService, useValue: taskHelperService},
{provide: UserService, useValue: userService},
{provide: Router, useValue: router},
{provide: DialogLauncherService, useValue: dialogLauncherService},
{provide: MagicShelfService, useValue: magicShelfService},
{provide: LoadingService, useValue: loadingService},
{provide: BookDialogHelperService, useValue: bookDialogHelperService},
{provide: TranslocoService, useValue: translocoService},
],
});
service = TestBed.inject(LibraryShelfMenuService);
});
it('needs a browser-side seam to verify clipboard and navigation behavior without relying on global runtime objects', () => {
// TODO(seam): Cover magic-shelf export and post-delete navigation once clipboard/router effects are injectable.
afterEach(() => {
TestBed.resetTestingModule();
vi.restoreAllMocks();
confirmationService.confirm.mockClear();
messageService.add.mockClear();
libraryService.refreshLibrary.mockClear();
libraryService.deleteLibrary.mockClear();
shelfService.deleteShelf.mockClear();
taskHelperService.refreshMetadataTask.mockClear();
userService.getCurrentUser.mockClear();
router.navigate.mockClear();
dialogLauncherService.openLibraryEditDialog.mockClear();
dialogLauncherService.openLibraryMetadataFetchDialog.mockClear();
dialogLauncherService.openShelfEditDialog.mockClear();
dialogLauncherService.openMagicShelfEditDialog.mockClear();
magicShelfService.deleteShelf.mockClear();
loadingService.show.mockClear();
loadingService.hide.mockClear();
bookDialogHelperService.openAddPhysicalBookDialog.mockClear();
bookDialogHelperService.openBulkIsbnImportDialog.mockClear();
bookDialogHelperService.openDuplicateMergerDialog.mockClear();
translocoService.translate.mockClear();
});
it('disables and guards library actions when the library id is missing', () => {
const items = service.initializeLibraryMenuItems(buildLibrary({id: undefined}));
const actionLabels = [
'book.shelfMenuService.library.addPhysicalBook',
'book.shelfMenuService.library.bulkIsbnImport',
'book.shelfMenuService.library.editLibrary',
'book.shelfMenuService.library.rescanLibrary',
'book.shelfMenuService.library.customFetchMetadata',
'book.shelfMenuService.library.autoFetchMetadata',
'book.shelfMenuService.library.findDuplicates',
'book.shelfMenuService.library.deleteLibrary',
];
for (const label of actionLabels) {
const item = findMenuItem(items, label);
expect(item.disabled).toBe(true);
runCommand(item);
}
expect(bookDialogHelperService.openAddPhysicalBookDialog).not.toHaveBeenCalled();
expect(bookDialogHelperService.openBulkIsbnImportDialog).not.toHaveBeenCalled();
expect(bookDialogHelperService.openDuplicateMergerDialog).not.toHaveBeenCalled();
expect(dialogLauncherService.openLibraryEditDialog).not.toHaveBeenCalled();
expect(dialogLauncherService.openLibraryMetadataFetchDialog).not.toHaveBeenCalled();
expect(taskHelperService.refreshMetadataTask).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
});
it('passes the concrete library id into library actions when available', () => {
const items = service.initializeLibraryMenuItems(buildLibrary({id: 42}));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.addPhysicalBook'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.bulkIsbnImport'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.editLibrary'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.customFetchMetadata'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.autoFetchMetadata'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.findDuplicates'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.rescanLibrary'));
runCommand(findMenuItem(items, 'book.shelfMenuService.library.deleteLibrary'));
expect(bookDialogHelperService.openAddPhysicalBookDialog).toHaveBeenCalledWith(42);
expect(bookDialogHelperService.openBulkIsbnImportDialog).toHaveBeenCalledWith(42);
expect(dialogLauncherService.openLibraryEditDialog).toHaveBeenCalledWith(42);
expect(dialogLauncherService.openLibraryMetadataFetchDialog).toHaveBeenCalledWith(42);
expect(taskHelperService.refreshMetadataTask).toHaveBeenCalledWith({
refreshType: MetadataRefreshType.LIBRARY,
libraryId: 42,
});
expect(bookDialogHelperService.openDuplicateMergerDialog).toHaveBeenCalledWith(42);
expect(confirmationService.confirm).toHaveBeenCalledTimes(2);
});
it('guards shelf actions when the shelf id is missing even for the owner', () => {
userService.getCurrentUser.mockReturnValue({id: 3, permissions: {admin: false}});
const items = service.initializeShelfMenuItems(buildShelf({id: undefined, userId: 3}));
const editItem = findMenuItem(items, 'book.shelfMenuService.shelf.editShelf');
const deleteItem = findMenuItem(items, 'book.shelfMenuService.shelf.deleteShelf');
expect(editItem.disabled).toBe(true);
expect(deleteItem.disabled).toBe(true);
runCommand(editItem);
runCommand(deleteItem);
expect(dialogLauncherService.openShelfEditDialog).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
});
it('guards magic shelf actions when the shelf id is missing', () => {
const items = service.initializeMagicShelfMenuItems(buildMagicShelf({id: null}));
const editItem = findMenuItem(items, 'book.shelfMenuService.magicShelf.editMagicShelf');
const deleteItem = findMenuItem(items, 'book.shelfMenuService.magicShelf.deleteMagicShelf');
expect(editItem.disabled).toBe(true);
expect(deleteItem.disabled).toBe(true);
runCommand(editItem);
runCommand(deleteItem);
expect(dialogLauncherService.openMagicShelfEditDialog).not.toHaveBeenCalled();
expect(confirmationService.confirm).not.toHaveBeenCalled();
});
});
@@ -35,295 +35,331 @@ export class LibraryShelfMenuService {
private readonly t = inject(TranslocoService);
initializeLibraryMenuItems(entity: Library | null): MenuItem[] {
const libraryId = entity?.id;
const disableLibraryActions = libraryId == null;
return [
{
label: this.t.translate('book.shelfMenuService.library.optionsLabel'),
items: [
{
label: this.t.translate('book.shelfMenuService.library.addPhysicalBook'),
icon: 'pi pi-book',
command: () => {
this.bookDialogHelperService.openAddPhysicalBookDialog(entity?.id as number);
}
},
{
label: this.t.translate('book.shelfMenuService.library.bulkIsbnImport'),
icon: 'pi pi-barcode',
command: () => {
this.bookDialogHelperService.openBulkIsbnImportDialog(entity?.id as number);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.editLibrary'),
icon: 'pi pi-pen-to-square',
command: () => {
this.dialogLauncherService.openLibraryEditDialog((entity?.id as number));
}
},
{
label: this.t.translate('book.shelfMenuService.library.rescanLibrary'),
icon: 'pi pi-refresh',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.rescanLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
icon: undefined,
acceptLabel: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
rejectLabel: this.t.translate('common.cancel'),
acceptIcon: undefined,
rejectIcon: undefined,
acceptButtonStyleClass: undefined,
rejectButtonStyleClass: undefined,
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
severity: 'success',
},
accept: () => {
const libraryId = entity?.id;
if (libraryId == null) {
return;
}
label: this.t.translate('book.shelfMenuService.library.addPhysicalBook'),
icon: 'pi pi-book',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.libraryService.refreshLibrary(libraryId).subscribe({
complete: () => {
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshSuccessDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshFailedDetail'),
});
}
this.bookDialogHelperService.openAddPhysicalBookDialog(libraryId);
}
},
{
label: this.t.translate('book.shelfMenuService.library.bulkIsbnImport'),
icon: 'pi pi-barcode',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.bookDialogHelperService.openBulkIsbnImportDialog(libraryId);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.editLibrary'),
icon: 'pi pi-pen-to-square',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.dialogLauncherService.openLibraryEditDialog(libraryId);
}
},
{
label: this.t.translate('book.shelfMenuService.library.rescanLibrary'),
icon: 'pi pi-refresh',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.rescanLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
icon: undefined,
acceptLabel: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
rejectLabel: this.t.translate('common.cancel'),
acceptIcon: undefined,
rejectIcon: undefined,
acceptButtonStyleClass: undefined,
rejectButtonStyleClass: undefined,
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
severity: 'success',
},
accept: () => {
this.libraryService.refreshLibrary(libraryId).subscribe({
complete: () => {
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshSuccessDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshFailedDetail'),
});
}
});
}
},
{
label: this.t.translate('book.shelfMenuService.library.customFetchMetadata'),
icon: 'pi pi-sync',
command: () => {
this.dialogLauncherService.openLibraryMetadataFetchDialog((entity?.id as number));
}
},
{
label: this.t.translate('book.shelfMenuService.library.autoFetchMetadata'),
icon: 'pi pi-bolt',
command: () => {
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.LIBRARY,
libraryId: entity?.id ?? undefined
}).subscribe();
}
},
{
label: this.t.translate('book.shelfMenuService.library.findDuplicates'),
icon: 'pi pi-copy',
command: () => {
this.bookDialogHelperService.openDuplicateMergerDialog(entity?.id as number);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.deleteLibrary'),
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger',
},
accept: () => {
const loader = this.loadingService.show(this.t.translate('book.shelfMenuService.loading.deletingLibrary', {name: entity?.name}));
const libraryId = entity?.id;
if (libraryId == null) {
this.loadingService.hide(loader);
return;
}
this.libraryService.deleteLibrary(libraryId)
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryDeleteFailedDetail'),
});
}
});
}
});
}
});
}
},
{
label: this.t.translate('book.shelfMenuService.library.customFetchMetadata'),
icon: 'pi pi-sync',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
]
this.dialogLauncherService.openLibraryMetadataFetchDialog(libraryId);
}
},
{
label: this.t.translate('book.shelfMenuService.library.autoFetchMetadata'),
icon: 'pi pi-bolt',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.LIBRARY,
libraryId
}).subscribe();
}
},
{
label: this.t.translate('book.shelfMenuService.library.findDuplicates'),
icon: 'pi pi-copy',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.bookDialogHelperService.openDuplicateMergerDialog(libraryId);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.library.deleteLibrary'),
icon: 'pi pi-trash',
disabled: disableLibraryActions,
command: () => {
if (libraryId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteLibraryMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary',
},
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger',
},
accept: () => {
const loader = this.loadingService.show(this.t.translate('book.shelfMenuService.loading.deletingLibrary', {name: entity?.name}));
this.libraryService.deleteLibrary(libraryId)
.pipe(finalize(() => this.loadingService.hide(loader)))
.subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.libraryDeleteFailedDetail'),
});
}
});
}
});
}
}
];
}
initializeShelfMenuItems(entity: Shelf | null): MenuItem[] {
const user = this.userService.getCurrentUser();
const shelfId = entity?.id;
const isOwner = entity?.userId === user?.id;
const isPublicShelf = entity?.publicShelf ?? false;
const disableOptions = !isOwner;
const disableOptions = !isOwner || shelfId == null;
return [
const items: MenuItem[] = [
{
label: (isPublicShelf ? this.t.translate('book.shelfMenuService.shelf.publicShelfPrefix') : '') + (disableOptions ? this.t.translate('book.shelfMenuService.shelf.readOnly') : this.t.translate('book.shelfMenuService.shelf.optionsLabel')),
items: [
{
label: this.t.translate('book.shelfMenuService.shelf.editShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
this.dialogLauncherService.openShelfEditDialog((entity?.id as number));
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.shelf.deleteShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
const shelfId = entity?.id;
if (shelfId == null) {
return;
}
label: this.t.translate('book.shelfMenuService.shelf.editShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
if (shelfId == null) {
return;
}
this.shelfService.deleteShelf(shelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.shelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.shelfDeleteFailedDetail'),
});
}
this.dialogLauncherService.openShelfEditDialog(shelfId);
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.shelf.deleteShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
if (shelfId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
this.shelfService.deleteShelf(shelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.shelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.shelfDeleteFailedDetail'),
});
}
});
}
}
]
});
}
}
];
/* Keep the grouped label only when it conveys state (public/read-only). */
if (isPublicShelf || disableOptions) {
const prefix = isPublicShelf ? this.t.translate('book.shelfMenuService.shelf.publicShelfPrefix') : '';
const suffix = disableOptions
? this.t.translate('book.shelfMenuService.shelf.readOnly')
: this.t.translate('book.shelfMenuService.shelf.optionsLabel');
return [{ label: prefix + suffix, items }];
}
return items;
}
initializeMagicShelfMenuItems(entity: MagicShelf | null): MenuItem[] {
const isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
const magicShelfId = entity?.id;
const isPublicShelf = entity?.isPublic ?? false;
const disableOptions = isPublicShelf && !isAdmin;
const disableOptions = magicShelfId == null || (isPublicShelf && !isAdmin);
return [
{
label: this.t.translate('book.shelfMenuService.magicShelf.optionsLabel'),
items: [
{
label: this.t.translate('book.shelfMenuService.magicShelf.editMagicShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
this.dialogLauncherService.openMagicShelfEditDialog((entity?.id as number));
}
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.exportJson'),
icon: 'pi pi-copy',
command: () => {
if (entity?.filterJson) {
navigator.clipboard.writeText(entity.filterJson).then(() => {
this.messageService.add({severity: 'success', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfJsonCopiedDetail')});
});
}
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.deleteMagicShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteMagicShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
const shelfId = entity?.id;
if (shelfId == null) {
return;
}
label: this.t.translate('book.shelfMenuService.magicShelf.editMagicShelf'),
icon: 'pi pi-pen-to-square',
disabled: disableOptions,
command: () => {
if (magicShelfId == null) {
return;
}
this.magicShelfService.deleteShelf(shelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeleteFailedDetail'),
});
}
this.dialogLauncherService.openMagicShelfEditDialog(magicShelfId);
}
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.exportJson'),
icon: 'pi pi-copy',
command: () => {
if (entity?.filterJson) {
navigator.clipboard.writeText(entity.filterJson).then(() => {
this.messageService.add({severity: 'success', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfJsonCopiedDetail')});
});
}
}
},
{
separator: true
},
{
label: this.t.translate('book.shelfMenuService.magicShelf.deleteMagicShelf'),
icon: 'pi pi-trash',
disabled: disableOptions,
command: () => {
if (magicShelfId == null) {
return;
}
this.confirmationService.confirm({
message: this.t.translate('book.shelfMenuService.confirm.deleteMagicShelfMessage', {name: entity?.name}),
header: this.t.translate('book.shelfMenuService.confirm.header'),
acceptLabel: this.t.translate('common.yes'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {
label: this.t.translate('common.yes'),
severity: 'danger'
},
rejectButtonProps: {
label: this.t.translate('common.cancel'),
severity: 'secondary'
},
accept: () => {
this.magicShelfService.deleteShelf(magicShelfId).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeletedDetail')});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeleteFailedDetail'),
});
}
});
}
}
]
});
}
}
];
}
@@ -130,6 +130,16 @@ export class LibraryService {
return this.bookService.books().filter(book => book.libraryId === libraryId).length;
}
readonly bookCountByLibraryId = computed(() => {
const counts = new Map<number, number>();
for (const book of this.bookService.books()) {
if (book.libraryId != null) {
counts.set(book.libraryId, (counts.get(book.libraryId) ?? 0) + 1);
}
}
return counts;
});
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
this.largeLibraryLoading.set({ isLoading, expectedCount });
}
@@ -1,8 +1,9 @@
import {HttpTestingController} from '@angular/common/http/testing';
import {signal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
import {createAuthServiceStub, createQueryClientHarness, flushQueryAsync, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
import type {Book} from '../model/book.model';
import type {Shelf} from '../model/shelf.model';
import {AuthService} from '../../../shared/service/auth.service';
@@ -41,6 +42,7 @@ describe('ShelfService', () => {
let userService: {
getCurrentUser: ReturnType<typeof vi.fn>;
};
let currentUser: ReturnType<typeof signal<{id: number} | null>>;
beforeEach(() => {
authService = createAuthServiceStub();
@@ -49,8 +51,9 @@ describe('ShelfService', () => {
books: vi.fn(() => []),
removeBooksFromShelf: vi.fn(),
};
currentUser = signal<{id: number} | null>(null);
userService = {
getCurrentUser: vi.fn(() => null),
getCurrentUser: vi.fn(() => currentUser()),
};
vi.spyOn(queryClientHarness.queryClient, 'invalidateQueries').mockResolvedValue(undefined);
@@ -79,8 +82,7 @@ describe('ShelfService', () => {
});
async function flushShelvesQueryResult(): Promise<void> {
await Promise.resolve();
flushSignalAndQueryEffects();
await flushQueryAsync();
}
it('eagerly fetches shelves and hydrates the computed shelves signal', async () => {
@@ -94,10 +96,26 @@ describe('ShelfService', () => {
request.flush(response);
await flushShelvesQueryResult();
expect(service.shelves()).toEqual(response);
expect(service.shelves()).toEqual([
expect.objectContaining({id: 1, name: 'Reading', systemKey: null}),
expect.objectContaining({id: 2, name: 'Archive', systemKey: null}),
]);
expect(service.shelvesError()).toBeNull();
});
it('marks the Kobo system shelf when the backend returns the known Kobo shelf shape', async () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([
buildShelf({id: 1, name: 'Kobo', icon: 'pi pi-tablet'}),
buildShelf({id: 2, name: 'Archive', icon: 'pi pi-folder'}),
]);
await flushShelvesQueryResult();
expect(service.shelves()).toEqual([
expect.objectContaining({id: 1, name: 'Kobo', systemKey: 'kobo'}),
expect.objectContaining({id: 2, name: 'Archive', systemKey: null}),
]);
});
it('removes shelf queries when the auth token is cleared', () => {
const removeQueriesSpy = vi.spyOn(queryClientHarness.queryClient, 'removeQueries').mockImplementation(() => undefined);
@@ -149,14 +167,36 @@ describe('ShelfService', () => {
buildBook(3, {shelves: [buildShelf({id: 2, name: 'Archive'})]}),
]);
userService.getCurrentUser.mockReturnValue({id: 7});
currentUser.set({id: 7});
expect(service.getBookCountValue(1)).toBe(2);
userService.getCurrentUser.mockReturnValue({id: 42});
currentUser.set({id: 42});
expect(service.getBookCountValue(2)).toBe(6);
expect(service.getBookCountValue(999)).toBe(0);
});
it('builds shelf count maps with local counts for the owner and persisted counts for shared shelves', async () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([
buildShelf({id: 1, userId: 7, bookCount: 99}),
buildShelf({id: 2, userId: 10, bookCount: 6}),
]);
await flushShelvesQueryResult();
bookService.books.mockReturnValue([
buildBook(1, {shelves: [buildShelf({id: 1, name: 'Reading'})]}),
buildBook(2, {shelves: [buildShelf({id: 1, name: 'Reading'})]}),
buildBook(3, {shelves: [buildShelf({id: 2, name: 'Archive'})]}),
]);
currentUser.set({id: 7});
flushSignalAndQueryEffects();
const counts = service.bookCountByShelfId();
expect(counts.get(1)).toBe(2);
expect(counts.get(2)).toBe(6);
});
it('counts unshelved books from the current book cache snapshot', () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/shelves')).flush([]);
@@ -12,6 +12,8 @@ import {UserService} from '../../settings/user-management/user.service';
import {AuthService} from '../../../shared/service/auth.service';
const SHELVES_QUERY_KEY = ['shelves'] as const;
const KOBO_SHELF_NAME = 'Kobo';
const KOBO_SHELF_ICON = 'pi pi-tablet';
@Injectable({providedIn: 'root'})
export class ShelfService {
@@ -53,7 +55,7 @@ export class ShelfService {
private getShelvesQueryOptions() {
return queryOptions({
queryKey: SHELVES_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<Shelf[]>(this.url))
queryFn: async () => this.decorateShelves(await lastValueFrom(this.http.get<Shelf[]>(this.url)))
});
}
@@ -110,4 +112,40 @@ export class ShelfService {
return this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length;
}
readonly bookCountByShelfId = computed(() => {
const currentUserId = this.userService.getCurrentUser()?.id;
const counts = new Map<number, number>();
for (const book of this.bookService.books()) {
for (const shelf of book.shelves ?? []) {
if (shelf.id != null) {
counts.set(shelf.id, (counts.get(shelf.id) ?? 0) + 1);
}
}
}
for (const shelf of this.shelves()) {
if (shelf.userId !== currentUserId && shelf.id != null) {
counts.set(shelf.id, shelf.bookCount ?? 0);
}
}
return counts;
});
readonly unshelvedBookCount = computed(() =>
this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length
);
private decorateShelves(shelves: Shelf[]): Shelf[] {
return shelves.map((shelf) => ({
...shelf,
systemKey: this.getSystemKey(shelf),
}));
}
private getSystemKey(shelf: Shelf): Shelf['systemKey'] {
return shelf.name === KOBO_SHELF_NAME && shelf.icon === KOBO_SHELF_ICON ? 'kobo' : null;
}
}