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
@@ -1,4 +1,5 @@
<ng-container *transloco="let t; prefix: 'authorBrowser'">
<div class="author-browser-page">
@if (loading()) {
<div class="loading-state">
<p-progressSpinner
@@ -271,4 +272,5 @@
</div>
}
}
</div>
</ng-container>
@@ -1,12 +1,24 @@
.author-browser-page {
--browser-gutter-inline: 2.1rem;
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
padding: 1.1rem 0 0;
position: relative;
}
.loading-state {
display: flex;
flex: 1 1 auto;
align-items: center;
justify-content: center;
height: calc(100dvh - 6.7rem);
min-height: 0;
}
.browse-header {
padding: 0.75rem 1rem 0;
padding: 0.75rem var(--browser-gutter-inline) 0;
}
.browse-title {
@@ -131,15 +143,15 @@
}
.virtual-scroller {
flex: 1 1 auto;
width: 100%;
height: calc(100dvh - 12.5rem);
padding: 1rem;
min-height: 0;
padding: 1rem var(--browser-gutter-inline);
box-sizing: border-box;
overflow-y: auto;
@media (width <= 768px) {
height: calc(100dvh - 13rem);
padding: 0.5rem;
padding-block: 0.5rem;
}
}
@@ -241,8 +253,14 @@
}
@media (width <= 767px) {
.author-browser-page {
--browser-gutter-inline: 0.5rem;
padding: 1.5rem 0 0;
}
.browse-header {
padding: 0.5rem 0.5rem 0;
padding-top: 0.5rem;
}
.browse-controls {
@@ -205,7 +205,6 @@ export class AuthorBrowserComponent implements OnInit {
minItemWidth: this.minCardWidth,
gap: AuthorBrowserComponent.GRID_GAP,
initialOffset: this.initialScrollOffset,
fillItemWidth: true,
estimateItemHeight: itemWidth => Math.round(itemWidth * this.cardAspectRatio()),
});
@@ -1,19 +1,35 @@
.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);
}
.author-wrapper {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
position: relative;
}
.author-wrapper {
position: relative;
border-radius: 0.75rem;
overflow: hidden;
border: 1px solid var(--p-content-border-color);
.author-wrapper > p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
::ng-deep .author-wrapper .p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
::ng-deep .author-wrapper .p-tabpanel-active {
display: flex;
flex-direction: column;
min-height: 0;
}
.loading-state {
@@ -147,6 +163,10 @@
}
.books-section {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
padding: 0 0.5rem;
}
@@ -158,8 +178,9 @@
}
.author-books-scroller {
flex: 1 1 auto;
width: 100%;
height: calc(100dvh - 22rem);
min-height: 0;
box-sizing: border-box;
overflow-y: auto;
}
@@ -2,7 +2,7 @@
display: flex;
flex-direction: column;
flex: 1;
min-height: calc(100dvh - 11rem);
min-height: 0;
}
.editor-container {
@@ -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;
}
}
@@ -1,17 +1,9 @@
.main-card {
display: flex;
flex-direction: column;
height: calc(100dvh - 6.1rem);
border-radius: 0.75rem;
height: 100%;
overflow: hidden;
background: var(--card-background);
border: 1px solid var(--p-content-border-color);
@media (width <= 768px) {
height: calc(100dvh - 4.4rem);
border-radius: 0;
border-width: 1px 0 0;
}
background: var(--page-background);
}
.header {
@@ -22,7 +14,7 @@
justify-content: space-between;
border-bottom: 1px solid var(--p-content-border-color);
gap: 1rem;
@media (width <= 768px) {
padding: 1rem;
}
@@ -41,7 +33,7 @@
p {
font-size: 0.875rem;
color: rgb(156 163 175);
strong {
color: var(--primary-color);
}
@@ -82,7 +74,6 @@
align-items: center;
justify-content: center;
z-index: 50;
border-radius: 0.75rem;
}
.loading-content {
@@ -119,7 +110,6 @@
align-items: center;
justify-content: center;
z-index: 50;
border-radius: 0.75rem;
> * + * {
margin-top: 0.75rem;
@@ -217,7 +207,7 @@ p-inputgroup.disabled {
display: flex;
gap: 1rem;
align-items: center;
@media (width <= 640px) {
flex-wrap: wrap;
width: 100%;
@@ -0,0 +1,112 @@
<ng-template #paletteTpl>
<ng-container *transloco="let t; prefix: 'layout.commandPalette'">
<div class="command-palette-shell" cdkTrapFocus [cdkTrapFocusAutoCapture]="true" [attr.aria-label]="t('ariaLabel')">
<div class="command-palette" [style.max-height.px]="availableHeightPx()">
<!-- iOS needs both type="search" and a form with an action attribute. -->
<form ngNoForm action="." class="command-palette-form" (submit)="$event.preventDefault()">
<div class="command-palette-input-row">
<i class="pi pi-search" aria-hidden="true"></i>
<input
#paletteInput
type="search"
name="q"
class="command-palette-input"
autocomplete="off"
spellcheck="false"
autocapitalize="none"
enterkeyhint="search"
[placeholder]="t('placeholder')"
[attr.aria-label]="t('ariaLabel')"
[ngModel]="svc.query()"
(ngModelChange)="onQueryChange($event)"
(keydown)="onKeydown($event)"
/>
</div>
</form>
@let groups = svc.groups();
@let hasQuery = svc.query().trim().length > 0;
@let isSearching = svc.isSearching();
@if (hasQuery) {
<div class="command-palette-results" role="listbox">
@if (!isSearching && groups.length === 0) {
<div class="command-palette-empty">{{ t('empty') }}</div>
}
@for (group of groups; track group.kind) {
<div class="command-palette-group" role="group" [attr.aria-label]="t(groupLabelKey(group.kind))">
<div class="command-palette-group-label" aria-hidden="true">{{ t(groupLabelKey(group.kind)) }}</div>
@for (item of group.items; track item.id) {
<button
type="button"
class="command-palette-item"
[class.active]="activeItem()?.id === item.id"
[class.book-item]="item.kind === 'book' && !!item.bookMeta"
[id]="itemDomId(item)"
role="option"
[attr.aria-selected]="activeItem()?.id === item.id"
(mouseenter)="onItemHover(item)"
(click)="svc.select(item)"
>
@if (item.kind === 'book' && item.bookMeta; as bookMeta) {
<ng-container *transloco="let tb; prefix: 'book.searcher'">
<div class="command-palette-book-cover">
@if (bookMeta.thumbnailUrl) {
<img [src]="bookMeta.thumbnailUrl" alt="" />
} @else {
<app-cover-placeholder
[title]="item.title"
[author]="bookMeta.authors.join(', ')"
size="sm"
></app-cover-placeholder>
}
</div>
<div class="command-palette-book-details">
<div class="command-palette-book-title">{{ item.title }}</div>
<div class="command-palette-book-meta">
@if (bookMeta.authors.length) {
<span>{{ tb('byPrefix') }} {{ bookMeta.authors.join(', ') }}</span>
}
@if (bookMeta.seriesName) {
<span>{{ bookMeta.seriesName }}@if (bookMeta.seriesNumber) { #{{ bookMeta.seriesNumber }} }</span>
}
@if (bookMeta.year) {
<span>{{ bookMeta.year }}</span>
}
</div>
</div>
</ng-container>
} @else {
@if (item.icon) {
<app-icon-display
class="command-palette-item-icon"
[icon]="item.icon"
size="18px"
[displayEmpty]="true"
></app-icon-display>
}
<span class="command-palette-item-title">{{ item.title }}</span>
@if (item.subtitle) {
<span class="command-palette-item-subtitle">{{ item.subtitle }}</span>
}
}
</button>
}
</div>
}
</div>
<div class="command-palette-hint" aria-hidden="true">
<span class="command-palette-hint-item">
<kbd>↑↓</kbd> {{ t('hintNavigate') }}
</span>
<span class="command-palette-hint-item">
<kbd>↵</kbd> {{ t('hintSelect') }}
</span>
</div>
}
</div>
</div>
</ng-container>
</ng-template>
@@ -0,0 +1,244 @@
:host {
display: contents;
}
.command-palette-shell {
position: relative;
width: min(640px, calc(100vw - 2rem));
}
.command-palette {
display: flex;
flex-direction: column;
width: 100%;
max-height: min(70vh, calc(100dvh - 4rem));
background: var(--surface-overlay);
color: var(--text-color);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
box-shadow: var(--shadow-overlay);
overflow: hidden;
}
.command-palette-form {
&:has(+ .command-palette-results) .command-palette-input-row {
border-bottom: 1px solid var(--border-color);
}
}
.command-palette-input-row {
display: flex;
align-items: center;
gap: var(--space-3);
padding: var(--space-4) var(--space-5);
i {
color: var(--text-secondary-color);
font-size: var(--text-lg);
}
}
.command-palette-input {
flex: 1;
min-width: 0;
padding: 0;
background: transparent;
border: none;
outline: none;
color: inherit;
font-size: var(--text-lg);
line-height: 1.4;
appearance: none;
&::placeholder {
color: var(--text-secondary-color);
}
&::-webkit-search-cancel-button,
&::-webkit-search-decoration {
appearance: none;
display: none;
}
}
.command-palette-results {
flex: 1;
overflow-y: auto;
padding: var(--space-1) var(--space-3);
}
.command-palette-empty {
padding: var(--space-6) var(--space-4);
color: var(--text-secondary-color);
text-align: center;
font-size: var(--text-sm);
}
.command-palette-group {
padding: var(--space-2) 0;
& + .command-palette-group {
border-top: 1px solid var(--border-color);
}
}
.command-palette-group-label {
padding: var(--space-2) var(--space-2) var(--space-1);
font-size: var(--text-xs);
font-weight: 500;
color: var(--text-secondary-color);
}
.command-palette-item {
display: flex;
align-items: center;
gap: var(--space-2);
width: 100%;
padding: var(--space-2);
background: transparent;
border: none;
border-radius: var(--radius-md);
color: inherit;
text-align: left;
font: inherit;
cursor: pointer;
scroll-margin: var(--space-2) 0;
.command-palette-item-icon {
color: var(--text-secondary-color);
flex-shrink: 0;
}
&.active {
background: color-mix(in srgb, var(--primary-color) 8%, transparent);
color: var(--primary-color);
.command-palette-item-icon {
color: inherit;
}
}
&.book-item {
align-items: center;
gap: var(--space-3);
padding: var(--space-2);
}
}
.command-palette-book-cover {
flex-shrink: 0;
width: 32px;
height: 48px;
border-radius: var(--radius-sm);
overflow: hidden;
background: var(--surface-800);
box-shadow: var(--shadow-sm);
img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
}
.command-palette-book-details {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.command-palette-book-title {
font-size: var(--text-base);
font-weight: 600;
line-height: 1.3;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.command-palette-book-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
min-width: 0;
font-size: var(--text-sm);
color: var(--text-secondary-color);
> * + *::before {
content: '·';
margin: 0 var(--space-2);
}
}
.command-palette-item-title {
flex: 0 1 auto;
min-width: 0;
font-size: var(--text-base);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.command-palette-item-subtitle {
flex: 1 1 auto;
min-width: 0;
margin-left: var(--space-2);
color: var(--text-secondary-color);
font-size: var(--text-sm);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: right;
}
.command-palette-hint {
display: flex;
justify-content: flex-end;
gap: var(--space-3);
padding: var(--space-2) var(--space-4);
border-top: 1px solid var(--border-color);
color: var(--text-secondary-color);
font-size: var(--text-xs);
}
.command-palette-hint-item {
display: inline-flex;
align-items: center;
gap: var(--space-2);
}
.command-palette-hint kbd {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 1.25rem;
padding: 0 var(--space-1);
border-radius: var(--radius-sm);
background: var(--surface-hover);
font-family: inherit;
font-size: var(--text-xs);
line-height: 1.5;
color: var(--text-color);
}
@media (width <= 991px) {
.command-palette-shell {
width: 100vw;
}
.command-palette {
max-height: calc(100dvh - 3.5rem);
border-top: none;
border-left: none;
border-right: none;
border-radius: 0;
box-shadow: 0 12px 24px rgb(0 0 0 / 18%);
}
.command-palette-hint {
display: none;
}
}
@@ -0,0 +1,227 @@
import { computed, signal } from '@angular/core';
import { OverlayContainer } from '@angular/cdk/overlay';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NavigationStart, Router } from '@angular/router';
import { Subject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTranslocoModule } from '../../core/testing/transloco-testing';
import type { PaletteGroup, PaletteItem } from './command-palette.model';
import { CommandPaletteComponent } from './command-palette.component';
import { CommandPaletteService } from './command-palette.service';
function createItem(id: string, title: string): PaletteItem {
return {
id,
kind: 'page',
title,
searchText: title.toLowerCase(),
};
}
class MockCommandPaletteService {
private readonly _isOpen = signal(false);
private overlayController?: { open(): void; close(): void; focusInput(): void };
readonly isOpen = this._isOpen.asReadonly();
readonly query = signal('');
readonly isSearching = signal(false);
readonly items = signal<PaletteItem[]>([]);
readonly groups = computed<PaletteGroup[]>(() =>
this.query().trim()
? [{ kind: 'page', items: this.items() }]
: []
);
readonly visibleItems = computed<PaletteItem[]>(() =>
this.groups().flatMap((group) => group.items)
);
readonly select = vi.fn();
readonly hide = vi.fn(() => {
this.overlayController?.close();
this._isOpen.set(false);
this.query.set('');
});
registerOverlayController(controller: { open(): void; close(): void; focusInput(): void }): () => void {
this.overlayController = controller;
return () => {
if (this.overlayController === controller) {
this.overlayController = undefined;
}
};
}
open(): void {
this.overlayController?.open();
this._isOpen.set(true);
}
}
describe('CommandPaletteComponent', () => {
let fixture: ComponentFixture<CommandPaletteComponent>;
let overlayContainer: OverlayContainer;
let overlayRoot: HTMLElement;
let service: MockCommandPaletteService;
let routerEvents: Subject<unknown>;
let originalScrollIntoView: PropertyDescriptor | undefined;
let originalMatchMedia: PropertyDescriptor | undefined;
beforeEach(() => {
originalScrollIntoView = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollIntoView');
originalMatchMedia = Object.getOwnPropertyDescriptor(window, 'matchMedia');
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
configurable: true,
writable: true,
value: vi.fn(),
});
Object.defineProperty(window, 'matchMedia', {
configurable: true,
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
routerEvents = new Subject<unknown>();
TestBed.configureTestingModule({
imports: [CommandPaletteComponent, getTranslocoModule()],
providers: [
{ provide: CommandPaletteService, useClass: MockCommandPaletteService },
{ provide: Router, useValue: { events: routerEvents.asObservable() } },
],
});
fixture = TestBed.createComponent(CommandPaletteComponent);
overlayContainer = TestBed.inject(OverlayContainer);
overlayRoot = overlayContainer.getContainerElement();
service = TestBed.inject(CommandPaletteService) as unknown as MockCommandPaletteService;
fixture.detectChanges();
});
afterEach(() => {
fixture?.destroy();
overlayRoot?.replaceChildren();
document.querySelectorAll('.cdk-overlay-container').forEach((el) => el.remove());
if (originalScrollIntoView) {
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', originalScrollIntoView);
} else {
delete (HTMLElement.prototype as { scrollIntoView?: unknown }).scrollIntoView;
}
if (originalMatchMedia) {
Object.defineProperty(window, 'matchMedia', originalMatchMedia);
} else {
delete (window as { matchMedia?: unknown }).matchMedia;
}
TestBed.resetTestingModule();
vi.restoreAllMocks();
});
it('opens the overlay when the service opens and focuses the search input', async () => {
service.query.set('dash');
service.items.set([createItem('page:dashboard', 'Dashboard')]);
service.open();
await flushPalette(fixture);
const input = overlayRoot.querySelector('.command-palette-input') as HTMLInputElement | null;
expect(input).not.toBeNull();
expect(document.activeElement).toBe(input);
});
it('closes the overlay on Escape', async () => {
service.query.set('dash');
service.items.set([createItem('page:dashboard', 'Dashboard')]);
service.open();
await flushPalette(fixture);
const input = overlayRoot.querySelector('.command-palette-input') as HTMLInputElement;
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
await flushPalette(fixture);
expect(service.hide).toHaveBeenCalled();
expect(overlayRoot.querySelector('.command-palette-input')).toBeNull();
});
it('wraps keyboard navigation through the result list', async () => {
service.query.set('a');
service.items.set([
createItem('page:dashboard', 'Dashboard'),
createItem('page:authors', 'Authors'),
]);
service.open();
await flushPalette(fixture);
const input = overlayRoot.querySelector('.command-palette-input') as HTMLInputElement;
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', bubbles: true }));
await flushPalette(fixture);
const items = Array.from(overlayRoot.querySelectorAll('.command-palette-item'));
expect(items[1].classList.contains('active')).toBe(true);
});
it('selects the highlighted item on Enter', async () => {
const items = [
createItem('page:dashboard', 'Dashboard'),
createItem('page:authors', 'Authors'),
];
service.query.set('a');
service.items.set(items);
service.open();
await flushPalette(fixture);
const input = overlayRoot.querySelector('.command-palette-input') as HTMLInputElement;
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));
await flushPalette(fixture);
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
expect(service.select).toHaveBeenCalledWith(items[1]);
});
it('disposes the overlay when the component is destroyed while open', async () => {
service.query.set('dash');
service.items.set([createItem('page:dashboard', 'Dashboard')]);
service.open();
await flushPalette(fixture);
expect(overlayRoot.querySelector('.command-palette-input')).not.toBeNull();
fixture.destroy();
expect(overlayRoot.querySelector('.command-palette-input')).toBeNull();
fixture = null as unknown as ComponentFixture<CommandPaletteComponent>;
});
it('closes through the service when navigation starts', async () => {
service.query.set('dash');
service.items.set([createItem('page:dashboard', 'Dashboard')]);
service.open();
await flushPalette(fixture);
routerEvents.next(new NavigationStart(1, '/dashboard'));
await flushPalette(fixture);
expect(service.hide).toHaveBeenCalled();
expect(service.isOpen()).toBe(false);
expect(service.query()).toBe('');
expect(overlayRoot.querySelector('.command-palette-input')).toBeNull();
});
});
async function flushPalette(fixture: ComponentFixture<CommandPaletteComponent>): Promise<void> {
fixture.detectChanges();
TestBed.flushEffects();
await Promise.resolve();
await Promise.resolve();
fixture.detectChanges();
}
@@ -0,0 +1,296 @@
import { A11yModule } from '@angular/cdk/a11y';
import { Overlay, OverlayModule, OverlayRef } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import { Component, computed, DestroyRef, effect, ElementRef, inject, signal, TemplateRef, untracked, ViewContainerRef, viewChild } from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import { filter, take } from 'rxjs/operators';
import { FormsModule } from '@angular/forms';
import { TranslocoDirective } from '@jsverse/transloco';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CoverPlaceholderComponent } from '../../shared/components/cover-generator/cover-generator.component';
import { IconDisplayComponent } from '../../shared/components/icon-display/icon-display.component';
import { PaletteItem } from './command-palette.model';
import { CommandPaletteService } from './command-palette.service';
const MOBILE_MEDIA_QUERY = '(max-width: 991px)';
const MOBILE_TOPBAR_HEIGHT = '3.5rem';
@Component({
selector: 'app-command-palette',
standalone: true,
imports: [A11yModule, OverlayModule, FormsModule, TranslocoDirective, IconDisplayComponent, CoverPlaceholderComponent],
templateUrl: './command-palette.component.html',
styleUrl: './command-palette.component.scss',
})
export class CommandPaletteComponent {
protected readonly svc = inject(CommandPaletteService);
private readonly overlay = inject(Overlay);
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
private readonly vcRef = inject(ViewContainerRef);
protected readonly paletteTpl = viewChild.required<TemplateRef<unknown>>('paletteTpl');
protected readonly inputEl = viewChild<ElementRef<HTMLInputElement>>('paletteInput');
protected readonly activeIndex = signal(0);
protected readonly availableHeightPx = signal<number | null>(null);
protected readonly activeItem = computed<PaletteItem | null>(() => {
const items = this.svc.visibleItems();
if (items.length === 0) return null;
const idx = Math.min(this.activeIndex(), items.length - 1);
return items[Math.max(0, idx)];
});
private overlayRef: OverlayRef | undefined;
private focusAnimationFrameId: number | undefined;
private focusTimeoutId: number | undefined;
private mobileMedia: MediaQueryList | undefined;
private readonly mobileMediaListener = () => {
this.applyPositionStrategy();
this.refreshAvailableHeight();
};
private readonly visualViewportListener = () => this.refreshAvailableHeight();
constructor() {
const unregisterOverlayController = this.svc.registerOverlayController({
open: () => this.openOverlay(),
close: () => this.closeOverlay(),
focusInput: () => this.focusInputNow(),
});
this.destroyRef.onDestroy(() => {
unregisterOverlayController();
this.clearPendingFocus();
this.closeOverlay();
});
this.router.events
.pipe(
filter((event): event is NavigationStart => event instanceof NavigationStart),
takeUntilDestroyed(this.destroyRef),
)
.subscribe(() => this.svc.hide());
effect(() => {
this.svc.visibleItems();
untracked(() => this.activeIndex.set(0));
});
effect(() => {
const item = this.activeItem();
if (!item) return;
queueMicrotask(() => {
const el = document.getElementById(this.itemDomId(item));
el?.scrollIntoView({ block: 'nearest' });
});
});
}
protected itemDomId(item: PaletteItem): string {
return `cp-${item.id.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
}
protected onQueryChange(value: string): void {
this.svc.query.set(value);
}
protected onKeydown(event: KeyboardEvent): void {
const items = this.svc.visibleItems();
switch (event.key) {
case 'ArrowDown':
if (items.length > 0) {
event.preventDefault();
this.activeIndex.update((i) => (i + 1) % items.length);
}
break;
case 'ArrowUp':
if (items.length > 0) {
event.preventDefault();
this.activeIndex.update((i) => (i - 1 + items.length) % items.length);
}
break;
case 'Home':
if (items.length > 0) {
event.preventDefault();
this.activeIndex.set(0);
}
break;
case 'End':
if (items.length > 0) {
event.preventDefault();
this.activeIndex.set(items.length - 1);
}
break;
case 'Enter': {
if (this.isMobileViewport()) {
event.preventDefault();
(event.target as HTMLElement | null)?.blur?.();
break;
}
const active = this.activeItem();
if (active) {
event.preventDefault();
this.svc.select(active);
}
break;
}
case 'Escape':
event.preventDefault();
this.svc.hide();
break;
}
}
protected onItemHover(item: PaletteItem): void {
const items = this.svc.visibleItems();
const idx = items.findIndex((candidate) => candidate.id === item.id);
if (idx >= 0) {
this.activeIndex.set(idx);
}
}
protected groupLabelKey(kind: string): string {
return `groups.${kind}`;
}
private openOverlay(): void {
if (this.overlayRef) {
this.focusInputNow();
this.scheduleInputFocus();
return;
}
this.bindMobileMediaListener();
this.bindVisualViewportListener();
this.refreshAvailableHeight();
this.overlayRef = this.overlay.create({
positionStrategy: this.buildPositionStrategy(),
scrollStrategy: this.overlay.scrollStrategies.block(),
hasBackdrop: true,
backdropClass: 'command-palette-backdrop',
panelClass: 'command-palette-panel',
});
this.overlayRef.attach(new TemplatePortal(this.paletteTpl(), this.vcRef));
this.overlayRef.backdropClick().pipe(take(1)).subscribe(() => this.svc.hide());
this.focusInputNow();
this.scheduleInputFocus();
}
private closeOverlay(): void {
this.clearPendingFocus();
this.unbindMobileMediaListener();
this.unbindVisualViewportListener();
this.availableHeightPx.set(null);
this.overlayRef?.dispose();
this.overlayRef = undefined;
}
private buildPositionStrategy() {
const position = this.overlay.position().global();
if (this.isMobileViewport()) {
return position.left('0').top(MOBILE_TOPBAR_HEIGHT);
}
return position.centerHorizontally().top('15vh');
}
private applyPositionStrategy(): void {
if (!this.overlayRef) return;
this.overlayRef.updatePositionStrategy(this.buildPositionStrategy());
}
private isMobileViewport(): boolean {
return this.mobileMedia?.matches ?? false;
}
private bindMobileMediaListener(): void {
if (typeof window === 'undefined' || this.mobileMedia) return;
this.mobileMedia = window.matchMedia(MOBILE_MEDIA_QUERY);
this.mobileMedia.addEventListener('change', this.mobileMediaListener);
}
private unbindMobileMediaListener(): void {
this.mobileMedia?.removeEventListener('change', this.mobileMediaListener);
this.mobileMedia = undefined;
}
private bindVisualViewportListener(): void {
const vv = typeof window !== 'undefined' ? window.visualViewport : null;
if (!vv) return;
vv.addEventListener('resize', this.visualViewportListener);
vv.addEventListener('scroll', this.visualViewportListener);
}
private unbindVisualViewportListener(): void {
const vv = typeof window !== 'undefined' ? window.visualViewport : null;
if (!vv) return;
vv.removeEventListener('resize', this.visualViewportListener);
vv.removeEventListener('scroll', this.visualViewportListener);
}
private refreshAvailableHeight(): void {
// dvh doesn't shrink when the iOS virtual keyboard opens; visualViewport does.
if (!this.isMobileViewport()) {
this.availableHeightPx.set(null);
return;
}
const vv = typeof window !== 'undefined' ? window.visualViewport : null;
if (!vv) {
this.availableHeightPx.set(null);
return;
}
const topbarPx = this.readTopbarHeightPx();
this.availableHeightPx.set(Math.max(0, Math.round(vv.height - topbarPx)));
}
private readTopbarHeightPx(): number {
const fontSize = typeof window !== 'undefined'
? parseFloat(window.getComputedStyle(document.documentElement).fontSize)
: 16;
return (isNaN(fontSize) ? 16 : fontSize) * 3.5;
}
private scheduleInputFocus(): void {
this.clearPendingFocus();
if (typeof window === 'undefined') return;
// iOS Safari only raises the virtual keyboard when focus() lands after layout.
const focusInput = () => this.focusInputNow();
this.focusAnimationFrameId = window.requestAnimationFrame(focusInput);
this.focusTimeoutId = window.setTimeout(focusInput, 60);
}
private focusInputNow(): void {
const input = this.resolveInputElement();
if (!input) return;
try {
input.focus({ preventScroll: true });
} catch {
input.focus();
}
const cursorPosition = input.value.length;
input.setSelectionRange(cursorPosition, cursorPosition);
}
private resolveInputElement(): HTMLInputElement | null {
const viewInput = this.inputEl()?.nativeElement;
if (viewInput) return viewInput;
const overlayInput = this.overlayRef?.overlayElement.querySelector('.command-palette-input');
return overlayInput instanceof HTMLInputElement ? overlayInput : null;
}
private clearPendingFocus(): void {
if (typeof window !== 'undefined' && this.focusAnimationFrameId !== undefined) {
window.cancelAnimationFrame(this.focusAnimationFrameId);
}
if (typeof window !== 'undefined' && this.focusTimeoutId !== undefined) {
window.clearTimeout(this.focusTimeoutId);
}
this.focusAnimationFrameId = undefined;
this.focusTimeoutId = undefined;
}
}
@@ -0,0 +1,37 @@
import { IconSelection } from '../../shared/service/icon-picker.service';
export type PaletteItemKind =
| 'action'
| 'page'
| 'book'
| 'author'
| 'series'
| 'shelf'
| 'magicShelf'
| 'library';
export interface PaletteBookMeta {
thumbnailUrl: string | null;
authors: string[];
seriesName: string | null;
seriesNumber: number | null;
year: string | null;
}
export interface PaletteItem {
id: string;
kind: PaletteItemKind;
title: string;
subtitle?: string;
icon?: IconSelection;
searchText: string;
route?: unknown[];
queryParams?: Record<string, string>;
command?: () => void;
bookMeta?: PaletteBookMeta;
}
export interface PaletteGroup {
kind: PaletteItemKind;
items: PaletteItem[];
}
@@ -0,0 +1,118 @@
import { signal } from '@angular/core';
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 { getTranslocoModule } from '../../core/testing/transloco-testing';
import { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.service';
import { Book } from '../book/model/book.model';
import { BookService } from '../book/service/book.service';
import { LibraryService } from '../book/service/library.service';
import { ShelfService } from '../book/service/shelf.service';
import { MagicShelfService } from '../magic-shelf/service/magic-shelf.service';
import { UrlHelperService } from '../../shared/service/url-helper.service';
import { UserService } from '../settings/user-management/user.service';
import { IconService } from '../../shared/services/icon.service';
import { DialogLauncherService } from '../../shared/services/dialog-launcher.service';
import { CommandPaletteService } from './command-palette.service';
function makeBook(id: number, title: string, authors: string[] = []): Book {
return {
id,
libraryId: 1,
libraryName: 'Library',
metadata: {
bookId: id,
title,
authors,
},
} as Book;
}
describe('CommandPaletteService', () => {
let service: CommandPaletteService;
let books = signal<Book[]>([]);
beforeEach(() => {
vi.useFakeTimers();
});
beforeEach(() => {
books = signal([
makeBook(1, 'The Hobbit', ['J.R.R. Tolkien']),
makeBook(2, 'The Fellowship of the Ring', ['J.R.R. Tolkien']),
makeBook(3, 'Dune', ['Frank Herbert']),
]);
TestBed.configureTestingModule({
imports: [getTranslocoModule()],
providers: [
{ provide: Router, useValue: { navigate: vi.fn(() => Promise.resolve(true)) } },
{ provide: BookService, useValue: { books: books.asReadonly() } },
{ provide: ShelfService, useValue: { shelves: signal([]) } },
{ provide: MagicShelfService, useValue: { shelves: signal([]) } },
{ provide: LibraryService, useValue: { libraries: signal([]) } },
{ provide: UserService, useValue: { currentUser: signal({ permissions: {} }) } },
{ provide: UrlHelperService, useValue: { getThumbnailUrl: vi.fn(() => null) } },
{ provide: IconService, useValue: { getSvgIconContent: vi.fn(() => of('')) } },
{
provide: DialogLauncherService,
useValue: {
openLibraryCreateDialog: vi.fn(),
openMagicShelfCreateDialog: vi.fn(),
openFileUploadDialog: vi.fn(),
},
},
{
provide: BookDialogHelperService,
useValue: {
openShelfCreatorDialog: vi.fn(),
},
},
],
});
service = TestBed.inject(CommandPaletteService);
TestBed.flushEffects();
});
afterEach(() => {
TestBed.resetTestingModule();
vi.runOnlyPendingTimers();
vi.useRealTimers();
vi.restoreAllMocks();
});
it('queries matching book groups locally after the debounce window', async () => {
service.query.set('tolkien');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
const bookGroup = service.groups().find((group) => group.kind === 'book');
expect(bookGroup).toBeDefined();
expect(bookGroup?.items.map((item) => item.title)).toEqual([
'The Hobbit',
'The Fellowship of the Ring',
]);
});
it('does not show book groups for one-character searches', async () => {
service.query.set('d');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
expect(service.groups().find((group) => group.kind === 'book')).toBeUndefined();
});
it('returns no groups when the query is empty', () => {
service.query.set('');
expect(service.groups()).toEqual([]);
expect(service.visibleItems()).toEqual([]);
});
});
@@ -0,0 +1,320 @@
import { computed, inject, Injectable, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { Router } from '@angular/router';
import { TranslocoService } from '@jsverse/transloco';
import { debounceTime, distinctUntilChanged } from 'rxjs';
import { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.service';
import { filterBooksBySearchTerm, normalizeSearchTerm } from '../book/components/book-browser/filters/HeaderFilter';
import { Book } from '../book/model/book.model';
import { BookService } from '../book/service/book.service';
import { LibraryService } from '../book/service/library.service';
import { ShelfService } from '../book/service/shelf.service';
import { MagicShelfService } from '../magic-shelf/service/magic-shelf.service';
import { UserService } from '../settings/user-management/user.service';
import { NavItem } from '../../shared/layout/navigation/nav-item.model';
import { buildAllNavPages, buildQuickActionNavItems } from '../../shared/layout/navigation/nav-catalog';
import { IconSelection } from '../../shared/service/icon-picker.service';
import { UrlHelperService } from '../../shared/service/url-helper.service';
import { DialogLauncherService } from '../../shared/services/dialog-launcher.service';
import { IconService } from '../../shared/services/icon.service';
import { PaletteGroup, PaletteItem, PaletteItemKind } from './command-palette.model';
interface GroupDef {
kind: PaletteItemKind;
source: PaletteItem[];
cap: number;
}
interface CommandPaletteOverlayController {
open(): void;
close(): void;
focusInput(): void;
}
const BOOK_RESULT_LIMIT = 50;
const MIN_BOOK_SEARCH_LENGTH = 2;
const BOOK_SEARCH_DEBOUNCE_MS = 200;
@Injectable({ providedIn: 'root' })
export class CommandPaletteService {
private readonly router = inject(Router);
private readonly t = inject(TranslocoService);
private readonly userService = inject(UserService);
private readonly bookService = inject(BookService);
private readonly shelfService = inject(ShelfService);
private readonly magicShelfService = inject(MagicShelfService);
private readonly libraryService = inject(LibraryService);
private readonly dialogLauncherService = inject(DialogLauncherService);
private readonly bookDialogHelperService = inject(BookDialogHelperService);
private readonly iconService = inject(IconService);
private readonly urlHelper = inject(UrlHelperService);
private readonly _isOpen = signal(false);
readonly isOpen = this._isOpen.asReadonly();
readonly query = signal('');
private overlayController?: CommandPaletteOverlayController;
private readonly activeLang = toSignal(this.t.langChanges$, { initialValue: this.t.getActiveLang() });
private readonly translate = (key: string): string => this.t.translate(key);
private readonly trimmedQuery = computed(() => this.query().trim());
private readonly debouncedBookQuery = toSignal(
toObservable(this.trimmedQuery).pipe(
debounceTime(BOOK_SEARCH_DEBOUNCE_MS),
distinctUntilChanged(),
),
{ initialValue: this.trimmedQuery() },
);
private readonly localBookItems = computed<PaletteItem[]>(() => {
const query = this.debouncedBookQuery();
if (query.length < MIN_BOOK_SEARCH_LENGTH) {
return [];
}
return filterBooksBySearchTerm(this.bookService.books(), query)
.slice(0, BOOK_RESULT_LIMIT)
.map((book) => this.toPaletteBookItem(book));
});
registerOverlayController(controller: CommandPaletteOverlayController): () => void {
this.overlayController = controller;
return () => {
if (this.overlayController === controller) {
this.overlayController = undefined;
}
};
}
open(): void {
if (!this._isOpen()) {
this.overlayController?.open();
this._isOpen.set(true);
} else {
this.overlayController?.focusInput();
}
this.prefetchCustomIcons();
}
private prefetchCustomIcons(): void {
const seen = new Set<string>();
const collect = (items: PaletteItem[]) => {
for (const item of items) {
if (item.icon?.type === 'CUSTOM_SVG' && !seen.has(item.icon.value)) {
seen.add(item.icon.value);
this.iconService.getSvgIconContent(item.icon.value).subscribe({ error: () => undefined });
}
}
};
collect(this.indexedLibraries());
collect(this.indexedShelves());
collect(this.indexedMagicShelves());
}
hide(): void {
this.overlayController?.close();
this._isOpen.set(false);
this.query.set('');
}
toggle(): void {
if (this._isOpen()) {
this.hide();
} else {
this.open();
}
}
select(item: PaletteItem): void {
this.hide();
queueMicrotask(() => {
if (item.command) {
item.command();
return;
}
if (item.route) {
void this.router.navigate(item.route, item.queryParams ? { queryParams: item.queryParams } : {});
}
});
}
readonly groups = computed<PaletteGroup[]>(() => {
const raw = this.trimmedQuery();
const normalized = normalizeSearchTerm(raw);
const tokens = normalized ? normalized.split(/\s+/).filter(Boolean) : [];
if (tokens.length === 0) {
return [];
}
const groups: PaletteGroup[] = [];
const bookItems = this.visibleBookItems();
if (bookItems.length > 0) {
groups.push({ kind: 'book', items: bookItems });
}
const defs: GroupDef[] = [
{ kind: 'shelf', source: this.indexedShelves(), cap: 10 },
{ kind: 'magicShelf', source: this.indexedMagicShelves(), cap: 10 },
{ kind: 'library', source: this.indexedLibraries(), cap: 10 },
{ kind: 'page', source: this.indexedPages(), cap: 10 },
{ kind: 'action', source: this.indexedActions(), cap: 10 },
];
groups.push(
...defs
.map((def) => ({
kind: def.kind,
items: this.filterItems(def.source, tokens, def.cap),
}))
.filter((group) => group.items.length > 0)
);
return groups;
});
readonly visibleItems = computed<PaletteItem[]>(() =>
this.groups().flatMap((group) => group.items)
);
readonly isSearching = computed(() => {
const raw = this.trimmedQuery();
if (raw.length < MIN_BOOK_SEARCH_LENGTH) {
return false;
}
return raw !== this.debouncedBookQuery();
});
private filterItems(source: PaletteItem[], tokens: string[], cap: number): PaletteItem[] {
const matched: PaletteItem[] = [];
for (const item of source) {
if (matched.length >= cap) break;
let hit = true;
for (const tok of tokens) {
if (!item.searchText.includes(tok)) {
hit = false;
break;
}
}
if (hit) {
matched.push(item);
}
}
return matched;
}
private readonly indexedActions = computed<PaletteItem[]>(() => {
this.activeLang();
const user = this.userService.currentUser();
if (!user) return [];
return buildQuickActionNavItems(this.translate, user.permissions, {
createLibrary: () => this.dialogLauncherService.openLibraryCreateDialog(),
createShelf: () => this.bookDialogHelperService.openShelfCreatorDialog(),
createMagicShelf: () => this.dialogLauncherService.openMagicShelfCreateDialog(),
uploadBook: () => this.dialogLauncherService.openFileUploadDialog(),
}).map((item) => this.toPaletteNavItem(item, 'action'));
});
private readonly indexedPages = computed<PaletteItem[]>(() => {
this.activeLang();
const user = this.userService.currentUser();
if (!user) return [];
return buildAllNavPages(this.translate, user.permissions)
.map((item) => this.toPaletteNavItem(item, 'page'));
});
private readonly indexedShelves = computed<PaletteItem[]>(() =>
this.shelfService.shelves()
.filter((shelf) => shelf.id != null)
.map((shelf) => ({
id: `shelf:${shelf.id}`,
kind: 'shelf' as const,
title: shelf.name,
icon: this.iconSelectionFor(shelf.icon, shelf.iconType, 'pi-bookmark'),
searchText: normalizeSearchTerm(shelf.name),
route: [`/shelf/${shelf.id}/books`],
}))
);
private readonly indexedMagicShelves = computed<PaletteItem[]>(() =>
this.magicShelfService.shelves()
.filter((shelf) => shelf.id != null)
.map((shelf) => ({
id: `magic-shelf:${shelf.id}`,
kind: 'magicShelf' as const,
title: shelf.name,
icon: this.iconSelectionFor(shelf.icon, shelf.iconType, 'pi-sparkles'),
searchText: normalizeSearchTerm(shelf.name),
route: [`/magic-shelf/${shelf.id}/books`],
}))
);
private readonly indexedLibraries = computed<PaletteItem[]>(() =>
this.libraryService.libraries()
.filter((library) => library.id != null)
.map((library) => ({
id: `library:${library.id}`,
kind: 'library' as const,
title: library.name,
icon: this.iconSelectionFor(library.icon, library.iconType, 'pi-folder'),
searchText: normalizeSearchTerm(library.name),
route: [`/library/${library.id}/books`],
}))
);
private readonly visibleBookItems = computed<PaletteItem[]>(() =>
this.trimmedQuery().length >= MIN_BOOK_SEARCH_LENGTH ? this.localBookItems() : []
);
private iconSelectionFor(
value: string | null | undefined,
iconType: string | null | undefined,
fallback: string,
): IconSelection {
if (!value) return { type: 'PRIME_NG', value: fallback };
if (iconType === 'CUSTOM_SVG') return { type: 'CUSTOM_SVG', value };
return { type: 'PRIME_NG', value };
}
private toPaletteBookItem(book: Book): PaletteItem {
const metadata = book.metadata;
const title = metadata?.title ?? book.primaryFile?.fileName ?? book.fileName ?? '';
const authors = metadata?.authors ?? [];
const publishedDate = metadata?.publishedDate ?? '';
const year = publishedDate && /^\d{4}/.test(publishedDate) ? publishedDate.slice(0, 4) : null;
const haystack = [title, metadata?.seriesName ?? '', ...authors].filter(Boolean).join(' ');
return {
id: `book:${book.id}`,
kind: 'book',
title,
icon: { type: 'PRIME_NG', value: 'pi-book' },
searchText: normalizeSearchTerm(haystack),
route: ['/book', book.id],
queryParams: { tab: 'view' },
bookMeta: {
thumbnailUrl: this.urlHelper.getThumbnailUrl(book.id, metadata?.coverUpdatedOn),
authors,
seriesName: metadata?.seriesName ?? null,
seriesNumber: metadata?.seriesNumber ?? null,
year,
},
};
}
private toPaletteNavItem(item: NavItem, kind: Extract<PaletteItemKind, 'action' | 'page'>): PaletteItem {
return {
id: `${kind}:${item.id}`,
kind,
title: item.label,
icon: item.icon ? { type: 'PRIME_NG', value: item.icon } : undefined,
searchText: normalizeSearchTerm(item.label),
route: item.routerLink,
command: item.action,
};
}
}
@@ -4,8 +4,8 @@
margin-bottom: 2rem;
position: relative;
overflow: hidden;
background: rgb(30 30 45 / 40%);
border: color-mix(in srgb, var(--p-surface-500), transparent 50%) 1px solid;
background: transparent;
border: 1px solid var(--border-subtle);
}
.dashboard-scroller-title {
@@ -14,7 +14,7 @@
font-weight: 800;
margin-bottom: 1rem;
padding: 0;
background: linear-gradient(135deg, #fff, #e2e8f0, #3b82f6);
background: linear-gradient(135deg, var(--text-color), var(--text-color-secondary), var(--primary-color));
background-clip: text;
-webkit-text-fill-color: transparent;
position: relative;
@@ -1,24 +1,28 @@
.dashboard-container {
height: calc(100dvh - 6.7rem);
box-sizing: border-box;
height: 100%;
overflow-y: auto;
position: relative;
}
@media (width <= 768px) {
.dashboard-container {
height: calc(100dvh - 5rem);
}
}
.dashboard {
box-sizing: border-box;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100%;
padding: 1.1rem 1.1rem 0;
text-align: center;
position: relative;
z-index: 1;
}
@media (width <= 768px) {
.dashboard {
padding: 0.5rem 0.5rem 0;
}
}
.loading-state {
display: flex;
align-items: center;
@@ -42,7 +46,7 @@
font-size: 1.75rem;
font-weight: 700;
margin-bottom: 2rem;
background: linear-gradient(135deg, #fff, #e2e8f0, var(--p-primary-500));
background: linear-gradient(135deg, var(--text-color), var(--text-color-secondary), var(--primary-color));
background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 0 2px 4px rgb(0 0 0 / 30%);
@@ -51,9 +55,9 @@
.dashboard-no-library {
padding: 3rem;
background: var(--p-surface-900);
background: transparent;
border-radius: 24px;
border: 1px solid var(--p-content-border-color);
border: 1px solid var(--border-subtle);
position: relative;
overflow: hidden;
}
@@ -74,11 +78,11 @@
::ng-deep .p-button {
box-shadow: 0 4px 12px rgb(0 0 0 / 30%);
background: rgb(var(--p-surface-900-rgb), 80%);
border: 1px solid var(--p-content-border-color);
background: transparent;
border: 1px solid var(--border-subtle);
&:hover {
background: rgb(var(--p-surface-800-rgb), 90%);
background: var(--surface-toolbar);
transform: scale(1.05);
transition: all 0.2s ease;
}
@@ -116,6 +116,16 @@ export class MagicShelfService {
).length;
}
readonly bookCountByMagicShelfId = computed(() => {
const counts = new Map<number, number>();
for (const shelf of this.shelves()) {
if (shelf.id != null) {
counts.set(shelf.id, this.getBookCountValue(shelf.id));
}
}
return counts;
});
deleteShelf(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
@@ -13,42 +13,45 @@
}
.tabs-wrapper {
border-radius: 0.75rem;
flex: 1 1 auto;
min-height: 0;
overflow: hidden;
border: 1px solid var(--p-content-border-color);
}
.tabs-wrapper > p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.tabs-wrapper > p-tabs > p-tablist {
flex: 0 0 auto;
}
.dialog-mode {
border: 1px solid var(--p-content-border-color);
border-radius: 0 0 0.75rem 0.75rem !important;
border-width: 1px 0 0 !important;
}
.tabpanels-responsive {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
::ng-deep .layout-main .tabpanels-responsive {
height: calc(100dvh - 9.7rem);
}
@media (width <= 768px) {
::ng-deep .layout-main .tabpanels-responsive {
height: calc(100dvh - 8.5rem);
}
}
::ng-deep .book-details-dialog .p-dialog-content,
::ng-deep .book-details-dialog app-book-metadata-center,
::ng-deep .book-details-dialog app-book-metadata-center > div,
::ng-deep .book-details-dialog app-book-metadata-center p-tabs {
:host-context(.book-details-dialog) {
display: flex;
width: 100%;
}
::ng-deep .book-details-dialog p-tablist {
flex-shrink: 0;
:host-context(.book-details-dialog) .book-metadata-center-container,
:host-context(.book-details-dialog) p-tabs {
display: flex;
width: 100%;
}
::ng-deep .book-details-dialog .p-dialog-content {
padding: 0;
:host-context(.book-details-dialog) p-tablist {
flex-shrink: 0;
}
@@ -114,26 +114,25 @@
.main-container {
width: 100%;
padding: 1rem;
height: calc(100dvh - 10.5rem);
border-width: 1px;
border-radius: 0.5rem;
box-sizing: border-box;
padding: 1rem 0;
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
@media (width >= 768px) {
height: calc(100dvh - 6.125rem);
}
}
.enclosing-container {
border-color: var(--p-content-border-color);
background: var(--p-content-background);
}
.settings-header {
margin-top: 0.75rem;
flex-shrink: 0;
@media (width >= 768px) {
padding: 0 1rem;
}
}
.settings-title {
@@ -257,7 +256,6 @@
border: 1px solid rgb(128 128 128 / 20%);
border-radius: 8px;
overflow: hidden;
background: var(--ground-background);
display: flex;
flex-direction: column;
flex: 1;
@@ -4,11 +4,32 @@
.main-container {
@include settings.settings-page-container;
gap: 0;
overflow-y: hidden;
height: calc(100dvh - 5rem);
padding: 0;
}
@media (width >= 768px) {
height: calc(100dvh - 5.6rem);
.main-container > .settings-header,
.main-container > .settings-card {
margin-inline: 1.1rem;
}
.main-container > .settings-header {
margin-top: 1.1rem;
}
.main-container > .settings-card {
margin-top: 1.5rem;
}
@media (width <= 768px) {
.main-container > .settings-header,
.main-container > .settings-card {
margin-inline: 0.5rem;
}
.main-container > .settings-header {
margin-top: 0.5rem;
}
}
@@ -20,6 +41,11 @@
display: flex;
flex-direction: column;
gap: 1.5rem;
padding: 1.5rem 1.1rem 0;
@media (width <= 768px) {
padding: 1.5rem 0.5rem 0;
}
}
@include settings.settings-page-header;
@@ -274,9 +274,6 @@
object-fit: contain;
box-shadow: 0 8px 32px rgb(0 0 0 / 60%);
border-radius: 4px;
&.previous-image {
}
}
&.fit-width {
@@ -294,12 +294,10 @@ $transition-fast: 150ms ease;
inset: 0;
width: 100%;
height: 100%;
overflow-x: hidden;
overflow-y: auto;
overflow: hidden auto;
&.horizontal-scroll {
overflow-x: auto;
overflow-y: hidden;
overflow: auto hidden;
}
embedpdf-container {
@@ -1,4 +1,5 @@
<ng-container *transloco="let t; prefix: 'seriesBrowser'">
<div class="series-browser-page">
@if (isBooksLoading()) {
<div class="loading-state">
<p-progressSpinner
@@ -93,4 +94,5 @@
}
}
}
</div>
</ng-container>
@@ -1,13 +1,24 @@
.series-browser-page {
--browser-gutter-inline: 2.1rem;
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
padding: 1.1rem 0 0;
}
.loading-state {
display: flex;
flex: 1 1 auto;
align-items: center;
justify-content: center;
height: calc(100dvh - 6.7rem);
min-height: 0;
}
// Browse Header
.browse-header {
padding: 0.75rem 1rem 0;
padding: 0.75rem var(--browser-gutter-inline) 0;
}
.browse-title {
@@ -98,19 +109,25 @@
// Virtual scroller and grid
.virtual-scroller {
flex: 1 1 auto;
width: 100%;
height: calc(100dvh - 12.5rem);
padding: 1rem;
min-height: 0;
padding: 1rem var(--browser-gutter-inline);
box-sizing: border-box;
overflow: hidden auto;
scrollbar-gutter: stable;
@media (width <= 768px) {
height: calc(100dvh - 13rem);
padding: 0.5rem;
padding-block: 0.5rem;
}
}
.virtual-scroller-item {
position: relative;
overflow: visible;
transition: width 0.2s ease, height 0.2s ease;
}
// Empty state
.empty-state {
display: flex;
@@ -134,8 +151,14 @@
}
@media (width <= 767px) {
.series-browser-page {
--browser-gutter-inline: 0.5rem;
padding: 1.5rem 0 0;
}
.browse-header {
padding: 0.5rem 0.5rem 0;
padding-top: 0.5rem;
}
.browse-controls {
@@ -120,7 +120,6 @@ export class SeriesBrowserComponent implements OnInit {
minItemWidth: this.minCardWidth,
gap: SeriesBrowserComponent.GRID_GAP,
initialOffset: this.initialScrollOffset,
fillItemWidth: true,
estimateItemHeight: itemWidth => Math.round(itemWidth * this.cardAspectRatio()),
});
readonly currentCardScale = computed(() => this.virtualGrid.itemWidth() / this.baseCardWidth());
@@ -3,12 +3,9 @@
.main-container {
width: 100%;
padding: 1rem;
height: calc(100dvh - 10.5rem);
height: 100%;
min-height: 0;
overflow-y: auto;
@media (width >= 768px) {
height: calc(100dvh - 11.65rem);
}
}
@include settings.settings-page-header;
@@ -1,5 +1,48 @@
:host {
display: block;
height: 100%;
min-height: 0;
}
.settings-container {
border-radius: 0.75rem;
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.settings-container > p-tabs,
.settings-container p-tabs.p-tabs {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.settings-container p-tablist {
flex: 0 0 auto;
}
.settings-container p-tabpanels {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
overflow: hidden;
border: 1px solid var(--p-content-border-color);
padding: 0;
background: transparent;
}
.settings-container p-tabpanel.p-tabpanel-active {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
}
.settings-container p-tabpanel.p-tabpanel-active > * {
display: block;
flex: 1 1 auto;
min-height: 0;
height: 100%;
}
@@ -0,0 +1,32 @@
<ng-container *transloco="let t; prefix: 'settingsView.language'">
<div class="settings-card">
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-language"></i>
{{ t('sectionTitle') }}
</h3>
<p class="section-description">{{ t('sectionDesc') }}</p>
</div>
<div class="section-body">
<div class="setting-item">
<div class="setting-header-standalone">
<span class="setting-label">{{ t('label') }}</span>
</div>
<div class="setting-options">
<div class="select-group">
<p-select
size="small"
[options]="languageOptions"
[ngModel]="activeLang()"
(ngModelChange)="onLanguageChange($event)"
optionLabel="label"
optionValue="value"
appendTo="body">
</p-select>
</div>
</div>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,41 @@
@use '../../../../shared/styles/settings-shared' as settings;
.settings-card {
@include settings.settings-card;
}
.section-header {
@include settings.settings-section-header;
}
.section-title {
@include settings.settings-section-title;
}
.section-description {
@include settings.settings-section-description;
}
.section-body {
@include settings.settings-section-body;
}
.setting-item {
@include settings.settings-item;
}
.setting-header-standalone {
@include settings.settings-item-header-standalone;
}
.setting-label {
@include settings.settings-label;
}
.setting-options {
@include settings.settings-options;
}
.select-group {
@include settings.settings-select-group;
}
@@ -0,0 +1,35 @@
import {Component, DestroyRef, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {takeUntilDestroyed, toSignal} from '@angular/core/rxjs-interop';
import {Select} from 'primeng/select';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {AVAILABLE_LANGS, LANG_LABELS} from '../../../../core/config/transloco-loader';
import {LANG_STORAGE_KEY} from '../../../../core/config/language-initializer';
@Component({
selector: 'app-language-preferences',
standalone: true,
imports: [FormsModule, Select, TranslocoDirective],
templateUrl: './language-preferences.component.html',
styleUrl: './language-preferences.component.scss',
})
export class LanguagePreferencesComponent {
readonly languageOptions = AVAILABLE_LANGS.map(value => ({
value,
label: LANG_LABELS[value] ?? value,
}));
private readonly t = inject(TranslocoService);
private readonly destroyRef = inject(DestroyRef);
readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
onLanguageChange(lang: string): void {
if (lang === this.activeLang()) return;
this.t.load(lang).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: () => {
this.t.setActiveLang(lang);
localStorage.setItem(LANG_STORAGE_KEY, lang);
},
});
}
}
@@ -19,9 +19,9 @@
<div class="setting-options">
<p-select
size="small"
[options]="sortingOptions"
[(ngModel)]="selectedLibrarySorting"
(ngModelChange)="onLibrarySortingChange()"
[options]="sortingOptions()"
[ngModel]="selectedLibrarySorting()"
(ngModelChange)="onLibrarySortingChange($event)"
appendTo="body"
optionLabel="label"
optionValue="value"
@@ -38,9 +38,9 @@
<div class="setting-options">
<p-select
size="small"
[options]="sortingOptions"
[(ngModel)]="selectedShelfSorting"
(ngModelChange)="onShelfSortingChange()"
[options]="sortingOptions()"
[ngModel]="selectedShelfSorting()"
(ngModelChange)="onShelfSortingChange($event)"
appendTo="body"
optionLabel="label"
optionValue="value"
@@ -57,9 +57,9 @@
<div class="setting-options">
<p-select
size="small"
[options]="sortingOptions"
[(ngModel)]="selectedMagicShelfSorting"
(ngModelChange)="onMagicShelfSortingChange()"
[options]="sortingOptions()"
[ngModel]="selectedMagicShelfSorting()"
(ngModelChange)="onMagicShelfSortingChange($event)"
appendTo="body"
optionLabel="label"
optionValue="value"
@@ -1,85 +1,43 @@
import {signal} from '@angular/core';
import {signal, WritableSignal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {MessageService} from 'primeng/api';
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
import {User, UserService, UserSettings} from '../../user-management/user.service';
import {LayoutService} from '../../../../shared/layout/layout.service';
import {SortPref} from '../../../../shared/layout/sidebar-sort-preferences';
import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences.component';
function createUserSettings(): UserSettings {
return {
perBookSetting: {pdf: 'Global', epub: 'Individual', cbx: 'Global'},
pdfReaderSetting: {pageSpread: 'off', pageZoom: '100%', showSidebar: true},
epubReaderSetting: {theme: 'light', font: 'serif', fontSize: 16, flow: 'paginated', spread: 'auto', lineHeight: 1.5, margin: 1, letterSpacing: 0},
ebookReaderSetting: {lineHeight: 1.5, justify: true, hyphenate: true, maxColumnCount: 1, gap: 1, fontSize: 16, theme: 'light', maxInlineSize: 100, maxBlockSize: 100, fontFamily: 'serif', isDark: false, flow: 'paginated'},
cbxReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
newPdfReaderSetting: {pageSpread: 'EVEN', pageViewMode: 'SINGLE_PAGE', fitMode: 'AUTO'},
sidebarLibrarySorting: {field: 'name', order: 'asc'},
sidebarShelfSorting: {field: 'id', order: 'desc'},
sidebarMagicShelfSorting: {field: 'name', order: 'desc'},
filterMode: 'and',
metadataCenterViewMode: 'route',
enableSeriesView: true,
entityViewPreferences: {global: {sortKey: 'title', sortDir: 'ASC', view: 'GRID', coverSize: 100, seriesCollapsed: false, overlayBookType: false}, overrides: []},
koReaderEnabled: false,
autoSaveMetadata: true,
} as UserSettings;
}
function createUser(): User {
return {
id: 9,
username: 'tester',
name: 'Tester',
email: 'tester@example.com',
assignedLibraries: [],
permissions: {
admin: false,
canUpload: false,
canDownload: false,
canEmailBook: false,
canDeleteBook: false,
canEditMetadata: false,
canManageLibrary: false,
canManageMetadataConfig: false,
canSyncKoReader: false,
canSyncKobo: false,
canAccessOpds: false,
canAccessBookdrop: false,
canAccessLibraryStats: false,
canAccessUserStats: false,
canAccessTaskManager: false,
canManageEmailConfig: false,
canManageGlobalPreferences: false,
canManageIcons: false,
canManageFonts: false,
demoUser: false,
canBulkAutoFetchMetadata: false,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: false,
canBulkRegenerateCover: false,
canMoveOrganizeFiles: false,
canBulkLockUnlockMetadata: false,
},
userSettings: createUserSettings(),
};
}
describe('SidebarSortingPreferencesComponent', () => {
let fixture: ComponentFixture<SidebarSortingPreferencesComponent>;
let updateUserSetting: ReturnType<typeof vi.fn>;
let setLibrarySort: ReturnType<typeof vi.fn>;
let messageService: {add: ReturnType<typeof vi.fn>};
let librarySort: WritableSignal<SortPref>;
let shelfSort: WritableSignal<SortPref>;
let magicShelfSort: WritableSignal<SortPref>;
beforeEach(() => {
updateUserSetting = vi.fn();
librarySort = signal<SortPref>({field: 'name', order: 'asc'});
shelfSort = signal<SortPref>({field: 'id', order: 'desc'});
magicShelfSort = signal<SortPref>({field: 'name', order: 'desc'});
setLibrarySort = vi.fn((value: SortPref) => librarySort.set(value));
messageService = {add: vi.fn()};
TestBed.configureTestingModule({
imports: [SidebarSortingPreferencesComponent, getTranslocoModule({translocoConfig: {reRenderOnLangChange: false}})],
providers: [
{provide: UserService, useValue: {currentUser: signal(createUser()), updateUserSetting}},
{
provide: LayoutService,
useValue: {
librarySort,
shelfSort,
magicShelfSort,
setLibrarySort,
setShelfSort: vi.fn((value: SortPref) => shelfSort.set(value)),
setMagicShelfSort: vi.fn((value: SortPref) => magicShelfSort.set(value)),
},
},
{provide: MessageService, useValue: messageService},
],
});
@@ -97,18 +55,18 @@ describe('SidebarSortingPreferencesComponent', () => {
it('hydrates sidebar sorting selections from the current user', () => {
const component = fixture.componentInstance;
expect(component.selectedLibrarySorting).toEqual({field: 'name', order: 'asc'});
expect(component.selectedShelfSorting).toEqual({field: 'id', order: 'desc'});
expect(component.sortingOptions).not.toHaveLength(0);
expect(component.selectedLibrarySorting()).toEqual({field: 'name', order: 'asc'});
expect(component.selectedShelfSorting()).toEqual({field: 'id', order: 'desc'});
expect(component.selectedMagicShelfSorting()).toEqual({field: 'name', order: 'desc'});
expect(component.sortingOptions()).not.toHaveLength(0);
});
it('persists library sorting changes and shows a success toast', () => {
const component = fixture.componentInstance;
component.selectedLibrarySorting = {field: 'id', order: 'asc'};
component.onLibrarySortingChange();
component.onLibrarySortingChange({field: 'id', order: 'asc'});
expect(updateUserSetting).toHaveBeenCalledWith(9, 'sidebarLibrarySorting', {field: 'id', order: 'asc'});
expect(setLibrarySort).toHaveBeenCalledWith({field: 'id', order: 'asc'});
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
});
@@ -1,12 +1,11 @@
import {Component, DestroyRef, effect, inject, OnInit} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Component, computed, inject} from '@angular/core';
import {toSignal} from '@angular/core/rxjs-interop';
import {Select} from 'primeng/select';
import {SidebarLibrarySorting, SidebarMagicShelfSorting, SidebarShelfSorting, User, UserService, UserSettings} from '../../user-management/user.service';
import {MessageService} from 'primeng/api';
import {FormsModule} from '@angular/forms';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
type MutableSettingsBranch = Record<string, unknown>;
import {LayoutService} from '../../../../shared/layout/layout.service';
import {SortPref} from '../../../../shared/layout/sidebar-sort-preferences';
@Component({
selector: 'app-sidebar-sorting-preferences',
@@ -18,73 +17,47 @@ type MutableSettingsBranch = Record<string, unknown>;
templateUrl: './sidebar-sorting-preferences.component.html',
styleUrl: './sidebar-sorting-preferences.component.scss'
})
export class SidebarSortingPreferencesComponent implements OnInit {
export class SidebarSortingPreferencesComponent {
private readonly sortingOptionDefs = [
{value: {field: 'name', order: 'asc'}, translationKey: 'nameAsc'},
{value: {field: 'name', order: 'desc'}, translationKey: 'nameDesc'},
{value: {field: 'id', order: 'asc'}, translationKey: 'creationAsc'},
{value: {field: 'id', order: 'desc'}, translationKey: 'creationDesc'},
];
] satisfies {value: SortPref; translationKey: string}[];
sortingOptions: {label: string; value: {field: string; order: string}; translationKey: string}[] = [];
selectedLibrarySorting: SidebarLibrarySorting = {field: 'id', order: 'asc'};
selectedShelfSorting: SidebarShelfSorting = {field: 'id', order: 'asc'};
selectedMagicShelfSorting: SidebarMagicShelfSorting = {field: 'id', order: 'asc'};
private readonly userService = inject(UserService);
private readonly layoutService = inject(LayoutService);
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private readonly destroyRef = inject(DestroyRef);
private readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
private currentUser: User | null = null;
private hasInitialized = false;
readonly selectedLibrarySorting = this.layoutService.librarySort;
readonly selectedShelfSorting = this.layoutService.shelfSort;
readonly selectedMagicShelfSorting = this.layoutService.magicShelfSort;
private readonly syncUserEffect = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this.currentUser = user;
if (!this.hasInitialized) {
this.hasInitialized = true;
this.loadPreferences(user.userSettings);
}
});
ngOnInit(): void {
this.buildSortingOptions();
this.t.langChanges$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.buildSortingOptions());
}
private buildSortingOptions(): void {
this.sortingOptions = this.sortingOptionDefs.map(opt => ({
readonly sortingOptions = computed(() => {
this.activeLang();
return this.sortingOptionDefs.map(opt => ({
...opt,
label: this.t.translate('settingsView.sidebarSort.' + opt.translationKey)
}));
});
onLibrarySortingChange(value: SortPref) {
this.layoutService.setLibrarySort(value);
this.showSuccessToast();
}
private loadPreferences(settings: UserSettings): void {
this.selectedLibrarySorting = settings.sidebarLibrarySorting;
this.selectedShelfSorting = settings.sidebarShelfSorting;
this.selectedMagicShelfSorting = settings.sidebarMagicShelfSorting;
onShelfSortingChange(value: SortPref) {
this.layoutService.setShelfSort(value);
this.showSuccessToast();
}
private updatePreference(path: string[], value: unknown): void {
if (!this.currentUser) return;
let target = this.currentUser.userSettings as unknown as MutableSettingsBranch;
for (let i = 0; i < path.length - 1; i++) {
const next = target[path[i]];
if (!next || typeof next !== 'object') {
target[path[i]] = {};
}
target = target[path[i]] as MutableSettingsBranch;
}
target[path.at(-1)!] = value;
onMagicShelfSortingChange(value: SortPref) {
this.layoutService.setMagicShelfSort(value);
this.showSuccessToast();
}
const [rootKey] = path;
const updatedValue = this.currentUser.userSettings[rootKey as keyof UserSettings];
this.userService.updateUserSetting(this.currentUser.id, rootKey, updatedValue);
private showSuccessToast(): void {
this.messageService.add({
severity: 'success',
summary: this.t.translate('settingsView.sidebarSort.prefsUpdated'),
@@ -92,16 +65,4 @@ export class SidebarSortingPreferencesComponent implements OnInit {
life: 1500
});
}
onLibrarySortingChange() {
this.updatePreference(['sidebarLibrarySorting'], this.selectedLibrarySorting);
}
onShelfSortingChange() {
this.updatePreference(['sidebarShelfSorting'], this.selectedShelfSorting);
}
onMagicShelfSortingChange() {
this.updatePreference(['sidebarMagicShelfSorting'], this.selectedMagicShelfSorting);
}
}
@@ -0,0 +1,15 @@
<ng-container *transloco="let t; prefix: 'settingsView.theme'">
<div class="settings-card">
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-palette"></i>
{{ t('sectionTitle') }}
</h3>
<p class="section-description">{{ t('sectionDesc') }}</p>
</div>
<div class="section-body">
<app-theme-configurator></app-theme-configurator>
</div>
</div>
</ng-container>
@@ -0,0 +1,21 @@
@use '../../../../shared/styles/settings-shared' as settings;
.settings-card {
@include settings.settings-card;
}
.section-header {
@include settings.settings-section-header;
}
.section-title {
@include settings.settings-section-title;
}
.section-description {
@include settings.settings-section-description;
}
.section-body {
@include settings.settings-section-body;
}
@@ -0,0 +1,12 @@
import {Component} from '@angular/core';
import {TranslocoDirective} from '@jsverse/transloco';
import {ThemeConfiguratorComponent} from '../../../../shared/layout/theme-configurator/theme-configurator.component';
@Component({
selector: 'app-theme-preferences',
standalone: true,
imports: [TranslocoDirective, ThemeConfiguratorComponent],
templateUrl: './theme-preferences.component.html',
styleUrl: './theme-preferences.component.scss',
})
export class ThemePreferencesComponent {}
@@ -10,6 +10,11 @@
</p>
</div>
<app-language-preferences></app-language-preferences>
<div class="section-divider"><hr></div>
<app-theme-preferences></app-theme-preferences>
<div class="section-divider"><hr></div>
<app-view-preferences></app-view-preferences>
<div class="section-divider"><hr></div>
<app-filter-preferences></app-filter-preferences>
@@ -35,10 +40,9 @@
<div class="slider-container">
<p-slider
[(ngModel)]="sidebarWidth"
[min]="175"
[max]="400"
[min]="SIDEBAR_MIN_WIDTH"
[max]="SIDEBAR_MAX_WIDTH"
[step]="1"
(onChange)="onSidebarWidthChange()"
(onSlideEnd)="saveSidebarWidth()">
</p-slider>
</div>
@@ -1,22 +1,30 @@
import {signal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {describe, expect, it, vi} from 'vitest';
import {ViewPreferencesParentComponent} from './view-preferences-parent.component';
import {LocalStorageService} from '../../../shared/service/local-storage.service';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {LayoutService} from '../../../shared/layout/layout.service';
describe('ViewPreferencesParentComponent', () => {
it('loads and saves the sidebar width', () => {
const localStorageGet = vi.fn(() => 312);
const localStorageSet = vi.fn();
function createLayoutService(initialWidth: number) {
const sidebarWidth = signal(initialWidth);
return {
sidebarWidth,
setSidebarWidth: vi.fn((value: number) => sidebarWidth.set(value)),
};
}
it('reads the sidebar width from LayoutService and saves it back with persistence', () => {
const layoutService = createLayoutService(312);
const messageAdd = vi.fn();
const translate = vi.fn(key => key);
TestBed.configureTestingModule({
imports: [ViewPreferencesParentComponent],
providers: [
{provide: LocalStorageService, useValue: {get: localStorageGet, set: localStorageSet}},
{provide: LayoutService, useValue: layoutService},
{provide: MessageService, useValue: {add: messageAdd}},
{provide: TranslocoService, useValue: {translate}},
]
@@ -25,12 +33,11 @@ describe('ViewPreferencesParentComponent', () => {
const fixture = TestBed.createComponent(ViewPreferencesParentComponent);
const component = fixture.componentInstance;
component.ngOnInit();
expect(component.sidebarWidth).toBe(312);
component.saveSidebarWidth();
expect(localStorageSet).toHaveBeenCalledWith('sidebarWidth', 312);
expect(layoutService.setSidebarWidth).toHaveBeenCalledWith(312, true);
expect(messageAdd).toHaveBeenCalledWith({
severity: 'success',
summary: 'settingsView.layout.saved',
@@ -38,13 +45,13 @@ describe('ViewPreferencesParentComponent', () => {
});
});
it('updates the sidebar CSS variable when the width changes', () => {
const localStorageGet = vi.fn(() => 225);
it('updates the layout service width immediately while the slider moves', () => {
const layoutService = createLayoutService(225);
TestBed.configureTestingModule({
imports: [ViewPreferencesParentComponent],
providers: [
{provide: LocalStorageService, useValue: {get: localStorageGet, set: vi.fn()}},
{provide: LayoutService, useValue: layoutService},
{provide: MessageService, useValue: {add: vi.fn()}},
{provide: TranslocoService, useValue: {translate: vi.fn()}},
]
@@ -54,16 +61,18 @@ describe('ViewPreferencesParentComponent', () => {
const component = fixture.componentInstance;
component.sidebarWidth = 287;
component.onSidebarWidthChange();
expect(document.documentElement.style.getPropertyValue('--sidebar-width')).toBe('287px');
expect(layoutService.setSidebarWidth).toHaveBeenCalledWith(287, false);
expect(component.sidebarWidth).toBe(287);
});
it('falls back to the default width when no value is stored', () => {
it('falls back to the layout service default width when nothing custom is loaded', () => {
const layoutService = createLayoutService(225);
TestBed.configureTestingModule({
imports: [ViewPreferencesParentComponent],
providers: [
{provide: LocalStorageService, useValue: {get: vi.fn(() => null), set: vi.fn()}},
{provide: LayoutService, useValue: layoutService},
{provide: MessageService, useValue: {add: vi.fn()}},
{provide: TranslocoService, useValue: {translate: vi.fn()}},
]
@@ -72,8 +81,6 @@ describe('ViewPreferencesParentComponent', () => {
const fixture = TestBed.createComponent(ViewPreferencesParentComponent);
const component = fixture.componentInstance;
component.ngOnInit();
expect(component.sidebarWidth).toBe(225);
});
});
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {TableModule} from 'primeng/table';
@@ -6,10 +6,12 @@ import {ViewPreferencesComponent} from './view-preferences/view-preferences.comp
import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences/sidebar-sorting-preferences.component';
import {MetaCenterViewModeComponent} from './meta-center-view-mode/meta-center-view-mode-component';
import {FilterPreferencesComponent} from './filter-preferences/filter-preferences.component';
import {LanguagePreferencesComponent} from './language-preferences/language-preferences.component';
import {ThemePreferencesComponent} from './theme-preferences/theme-preferences.component';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Slider} from 'primeng/slider';
import {MessageService} from 'primeng/api';
import {LocalStorageService} from '../../../shared/service/local-storage.service';
import {LayoutService, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH} from '../../../shared/layout/layout.service';
@Component({
selector: 'app-view-preferences-parent',
@@ -21,30 +23,32 @@ import {LocalStorageService} from '../../../shared/service/local-storage.service
SidebarSortingPreferencesComponent,
MetaCenterViewModeComponent,
FilterPreferencesComponent,
LanguagePreferencesComponent,
ThemePreferencesComponent,
TranslocoDirective,
Slider,
],
templateUrl: './view-preferences-parent.component.html',
styleUrl: './view-preferences-parent.component.scss'
})
export class ViewPreferencesParentComponent implements OnInit {
export class ViewPreferencesParentComponent {
sidebarWidth = 225;
readonly SIDEBAR_MIN_WIDTH = SIDEBAR_MIN_WIDTH;
readonly SIDEBAR_MAX_WIDTH = SIDEBAR_MAX_WIDTH;
private localStorageService = inject(LocalStorageService);
private layoutService = inject(LayoutService);
private messageService = inject(MessageService);
private t = inject(TranslocoService);
ngOnInit(): void {
this.sidebarWidth = this.localStorageService.get<number>('sidebarWidth') ?? 225;
get sidebarWidth(): number {
return this.layoutService.sidebarWidth();
}
onSidebarWidthChange(): void {
document.documentElement.style.setProperty('--sidebar-width', this.sidebarWidth + 'px');
set sidebarWidth(value: number) {
this.layoutService.setSidebarWidth(value, false);
}
saveSidebarWidth(): void {
this.localStorageService.set('sidebarWidth', this.sidebarWidth);
this.layoutService.setSidebarWidth(this.layoutService.sidebarWidth(), true);
this.messageService.add({
severity: 'success',
summary: this.t.translate('settingsView.layout.saved'),
@@ -2,7 +2,8 @@
max-width: 2500px;
margin: 0 auto;
background: transparent;
height: calc(100dvh - 6.25rem);
box-sizing: border-box;
height: 100%;
overflow-y: auto;
padding: 0.5rem;
}
@@ -1,8 +1,9 @@
.user-stats-container {
max-width: 1800px;
margin: 0 auto;
box-sizing: border-box;
padding: 0.5rem;
height: calc(100dvh - 6.25rem);
height: 100%;
overflow-y: auto;
}