refactor(books): shared search normalisation and debounce helpers + migrate command palette to server-side queries (#2232)

This commit is contained in:
Alex
2026-09-21 13:01:56 +01:00
committed by GitHub
parent 7ed1c35ca0
commit 04467d7d68
9 changed files with 339 additions and 83 deletions
@@ -38,7 +38,9 @@
@if (hasQuery) {
<div class="command-palette-results" role="listbox">
@if (!isSearching && groups.length === 0) {
@if (svc.bookSearchFailed()) {
<div class="command-palette-empty">{{ t('bookSearchError') }}</div>
} @else if (!isSearching && groups.length === 0) {
<div class="command-palette-empty">{{ t('empty') }}</div>
}
@@ -26,6 +26,7 @@ class MockCommandPaletteService {
readonly isOpen = this._isOpen.asReadonly();
readonly query = signal('');
readonly isSearching = signal(false);
readonly bookSearchFailed = signal(false);
readonly items = signal<PaletteItem[]>([]);
readonly groups = computed<PaletteGroup[]>(() =>
this.query().trim()
@@ -1,14 +1,17 @@
import { signal } from '@angular/core';
import { ApplicationRef, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { HttpTestingController } from '@angular/common/http/testing';
import { Router } from '@angular/router';
import { of } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MessageService } from '@openng/optimus-ui/api';
import { createQueryClientHarness } from '../../core/testing/query-testing';
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 { BookPage } from '../book/data/book-query.models';
import { BookQueryService } from '../book/data/book-query.service';
import { BookSummary } from '../book/data/book-response.models';
import { LibraryService } from '../book/service/library.service';
import { ShelfService } from '../book/service/shelf.service';
import { MagicShelfService } from '../magic-shelf/service/magic-shelf.service';
@@ -19,7 +22,12 @@ import { DialogLauncherService } from '../../shared/services/dialog-launcher.ser
import { CommandPaletteService } from './command-palette.service';
function makeBook(id: number, title: string, authors: string[] = [], overrides: Partial<Book> = {}): Book {
function makeBook(
id: number,
title: string,
authors: string[] = [],
overrides: Partial<BookSummary> = {},
): BookSummary {
return {
id,
libraryId: 1,
@@ -27,16 +35,17 @@ function makeBook(id: number, title: string, authors: string[] = [], overrides:
...overrides,
metadata: {
bookId: id,
title,
authors,
allMetadataLocked: false,
title,
...overrides.metadata,
},
} as Book;
};
}
describe('CommandPaletteService', () => {
let service: CommandPaletteService;
let books = signal<Book[]>([]);
let http: HttpTestingController;
let urlHelper: {
getThumbnailUrl: ReturnType<typeof vi.fn>;
getAudiobookThumbnailUrl: ReturnType<typeof vi.fn>;
@@ -47,11 +56,7 @@ describe('CommandPaletteService', () => {
});
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']),
]);
const queryHarness = createQueryClientHarness();
urlHelper = {
getThumbnailUrl: vi.fn(() => null),
getAudiobookThumbnailUrl: vi.fn(() => null),
@@ -60,8 +65,9 @@ describe('CommandPaletteService', () => {
TestBed.configureTestingModule({
imports: [getTranslocoModule()],
providers: [
...queryHarness.providers,
{ provide: Router, useValue: { navigate: vi.fn(() => Promise.resolve(true)) } },
{ provide: BookService, useValue: { books: books.asReadonly() } },
BookQueryService,
{ provide: ShelfService, useValue: { shelves: signal([]) } },
{ provide: MagicShelfService, useValue: { shelves: signal([]) } },
{ provide: LibraryService, useValue: { libraries: signal([]) } },
@@ -87,71 +93,184 @@ describe('CommandPaletteService', () => {
});
service = TestBed.inject(CommandPaletteService);
http = TestBed.inject(HttpTestingController);
TestBed.flushEffects();
});
afterEach(() => {
http.verify();
TestBed.resetTestingModule();
vi.runOnlyPendingTimers();
vi.useRealTimers();
vi.restoreAllMocks();
});
it('queries matching book groups locally after the debounce window', async () => {
service.query.set('tolkien');
function makeBookPage(books: BookSummary[]): BookPage {
return {
content: books,
page: {
number: 0,
size: 50,
totalElements: books.length,
totalPages: books.length > 0 ? 1 : 0,
cursor: 'opaque-cursor',
},
links: [],
};
}
async function searchBooks(query: string, books: BookSummary[]): Promise<void> {
service.open();
service.query.set(query);
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
const request = http.expectOne(request => request.url.endsWith('/api/v1/books/page'));
expect(request.request.params.get('facet_logic')).toBe('or');
expect(request.request.params.get('query')).toBe(query);
expect(request.request.params.get('sort')).toBe('title');
expect(request.request.params.get('size')).toBe('50');
request.flush(makeBookPage(books));
await TestBed.inject(ApplicationRef).whenStable();
TestBed.flushEffects();
}
it('queries the page endpoint with the normalized term after the debounce window', async () => {
service.open();
service.query.set('it!');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(199);
TestBed.flushEffects();
http.expectNone(request => request.url.endsWith('/api/v1/books/page'));
await vi.advanceTimersByTimeAsync(1);
TestBed.flushEffects();
const request = http.expectOne(request => request.url.endsWith('/api/v1/books/page'));
expect(request.request.params.get('facet_logic')).toBe('or');
expect(request.request.params.get('query')).toBe('it');
expect(request.request.params.get('sort')).toBe('title');
expect(request.request.params.get('size')).toBe('50');
request.flush(makeBookPage([makeBook(1, 'It', ['Stephen King'])]));
await TestBed.inject(ApplicationRef).whenStable();
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',
]);
expect(bookGroup?.items.map((item) => item.title)).toEqual(['It']);
});
it('does not show book groups for one-character searches', async () => {
service.query.set('d');
it('reports a failed book search instead of claiming no results', async () => {
service.open();
service.query.set('tolkien');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
const request = http.expectOne(req => req.url.endsWith('/api/v1/books/page'));
request.flush('Bad request', {status: 400, statusText: 'Bad Request'});
await TestBed.inject(ApplicationRef).whenStable();
TestBed.flushEffects();
expect(service.bookSearchFailed()).toBe(true);
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([]);
});
it('uses square audiobook metadata and audiobook thumbnails for audiobook results', async () => {
urlHelper.getAudiobookThumbnailUrl.mockReturnValue('/audio-thumb.jpg');
books.set([
makeBook(4, 'Audio Sample', ['Narrator'], {
primaryFile: { id: 4, bookId: 4, bookType: 'AUDIOBOOK' },
metadata: {
bookId: 4,
title: 'Audio Sample',
authors: ['Narrator'],
audiobookCoverUpdatedOn: 'audio-updated',
},
}),
]);
service.query.set('audio');
it('does not search when the normalized term is below two characters', async () => {
service.open();
service.query.set('d!');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
const book = service.groups().find((group) => group.kind === 'book')?.items[0];
http.expectNone(request => request.url.endsWith('/api/v1/books/page'));
expect(service.groups().find((group) => group.kind === 'book')).toBeUndefined();
});
it('does not search for eligible text while the palette is closed', async () => {
service.query.set('dune');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
expect(book?.bookMeta?.isAudiobook).toBe(true);
expect(book?.bookMeta?.thumbnailUrl).toBe('/audio-thumb.jpg');
expect(urlHelper.getAudiobookThumbnailUrl).toHaveBeenCalledWith(4, 'audio-updated');
expect(urlHelper.getThumbnailUrl).not.toHaveBeenCalled();
http.expectNone(request => request.url.endsWith('/api/v1/books/page'));
expect(service.groups().find((group) => group.kind === 'book')).toBeUndefined();
});
it('cancels an in-flight book search when debounced text changes', async () => {
service.open();
service.query.set('dune');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
const duneRequest = http.expectOne(request => request.urlWithParams.includes('query=dune'));
service.query.set('tolkien');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
expect(duneRequest.cancelled).toBe(true);
const tolkienRequest = http.expectOne(request => request.urlWithParams.includes('query=tolkien'));
tolkienRequest.flush(makeBookPage([]));
TestBed.flushEffects();
});
it('cancels an in-flight book search on close and does not refire it on quick reopen', async () => {
service.open();
service.query.set('dune');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
const duneRequest = http.expectOne(request => request.urlWithParams.includes('query=dune'));
service.hide();
TestBed.flushEffects();
expect(duneRequest.cancelled).toBe(true);
service.open();
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
http.expectNone(request => request.url.endsWith('/api/v1/books/page'));
});
it('hides results from the previous search while the next search is debouncing', async () => {
await searchBooks('dune', [makeBook(3, 'Dune', ['Frank Herbert'])]);
expect(service.groups().find((group) => group.kind === 'book')!.items[0].title).toBe('Dune');
service.query.set('tolkien');
TestBed.flushEffects();
expect(service.groups().find((group) => group.kind === 'book')).toBeUndefined();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
const request = http.expectOne(request => request.urlWithParams.includes('query=tolkien'));
request.flush(makeBookPage([]));
TestBed.flushEffects();
});
it('hides a failed search error while the next term is debouncing', async () => {
service.open();
service.query.set('dune');
TestBed.flushEffects();
await vi.advanceTimersByTimeAsync(200);
TestBed.flushEffects();
const duneRequest = http.expectOne(request => request.urlWithParams.includes('query=dune'));
duneRequest.flush('Bad request', {status: 400, statusText: 'Bad Request'});
await TestBed.inject(ApplicationRef).whenStable();
TestBed.flushEffects();
expect(service.bookSearchFailed()).toBe(true);
service.query.set('tolkien');
TestBed.flushEffects();
expect(service.bookSearchFailed()).toBe(false);
});
});
@@ -1,14 +1,14 @@
import { computed, inject, Injectable, signal } from '@angular/core';
import { MessageService } from '@openng/optimus-ui/api';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { toSignal } from '@angular/core/rxjs-interop';
import { Router } from '@angular/router';
import { TranslocoService } from '@jsverse/transloco';
import { debounceTime, distinctUntilChanged } from 'rxjs';
import { injectQuery, QueryClient } from '@tanstack/angular-query-experimental';
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 { BookPageParams, EMPTY_FACET_SELECTION } from '../book/data/book-query-params';
import { BookSummary } from '../book/data/book-response.models';
import { BookQueryService } from '../book/data/book-query.service';
import { LibraryService } from '../book/service/library.service';
import { ShelfService } from '../book/service/shelf.service';
import { MagicShelfService } from '../magic-shelf/service/magic-shelf.service';
@@ -21,6 +21,8 @@ import { CustomSvgService } from '../../shared/services/custom-svg.service';
import { toIconSelection } from '../../shared/icons/icon-selection';
import { PaletteGroup, PaletteItem, PaletteItemKind } from './command-palette.model';
import {normalizeLocalSearchTerm, normalizeRemoteSearchTerm, SEARCH_DEBOUNCE_MS} from '../../shared/util/search-terms';
import {debouncedSignal} from '../../shared/util/debounced-signal';
interface GroupDef {
kind: PaletteItemKind;
@@ -36,14 +38,14 @@ interface CommandPaletteOverlayController {
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 bookQueryService = inject(BookQueryService);
private readonly queryClient = inject(QueryClient);
private readonly shelfService = inject(ShelfService);
private readonly magicShelfService = inject(MagicShelfService);
private readonly libraryService = inject(LibraryService);
@@ -61,23 +63,31 @@ export class CommandPaletteService {
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 normalizedBookQuery = computed(() => normalizeRemoteSearchTerm(this.query()));
private readonly debouncedBookQuery = debouncedSignal(this.normalizedBookQuery, SEARCH_DEBOUNCE_MS);
private readonly bookSearchParams = computed<BookPageParams>(() => ({
query: this.debouncedBookQuery(),
facets: EMPTY_FACET_SELECTION,
facetLogic: 'or',
sort: [{key: 'title', direction: 'asc'}],
size: BOOK_RESULT_LIMIT,
}));
private readonly bookSearchQuery = injectQuery(() => ({
...this.bookQueryService.page(this.bookSearchParams()),
enabled: this._isOpen()
&& this.normalizedBookQuery().length >= MIN_BOOK_SEARCH_LENGTH
&& this.debouncedBookQuery().length >= MIN_BOOK_SEARCH_LENGTH,
}));
private readonly remoteBookItems = computed<PaletteItem[]>(() =>
(this.bookSearchQuery.data()?.content ?? []).map(book => this.toPaletteBookItem(book))
);
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));
});
readonly bookSearchFailed = computed(() =>
this._isOpen()
&& this.normalizedBookQuery().length >= MIN_BOOK_SEARCH_LENGTH
&& this.normalizedBookQuery() === this.debouncedBookQuery()
&& this.bookSearchQuery.isError()
);
registerOverlayController(controller: CommandPaletteOverlayController): () => void {
this.overlayController = controller;
@@ -116,6 +126,9 @@ export class CommandPaletteService {
}
hide(): void {
void this.queryClient.cancelQueries({
queryKey: this.bookQueryService.page(this.bookSearchParams()).queryKey,
});
this.overlayController?.close();
this._isOpen.set(false);
this.query.set('');
@@ -144,7 +157,7 @@ export class CommandPaletteService {
readonly groups = computed<PaletteGroup[]>(() => {
const raw = this.trimmedQuery();
const normalized = normalizeSearchTerm(raw);
const normalized = normalizeLocalSearchTerm(raw);
const tokens = normalized ? normalized.split(/\s+/).filter(Boolean) : [];
if (tokens.length === 0) {
return [];
@@ -182,12 +195,12 @@ export class CommandPaletteService {
);
readonly isSearching = computed(() => {
const raw = this.trimmedQuery();
if (raw.length < MIN_BOOK_SEARCH_LENGTH) {
const normalized = this.normalizedBookQuery();
if (normalized.length < MIN_BOOK_SEARCH_LENGTH) {
return false;
}
return raw !== this.debouncedBookQuery();
return normalized !== this.debouncedBookQuery() || this.bookSearchQuery.isFetching();
});
private filterItems(source: PaletteItem[], tokens: string[], cap: number): PaletteItem[] {
@@ -236,7 +249,7 @@ export class CommandPaletteService {
kind: 'shelf' as const,
title: shelf.name,
icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined,
searchText: normalizeSearchTerm(shelf.name),
searchText: normalizeLocalSearchTerm(shelf.name),
route: [`/shelf/${shelf.id}/books`],
}))
);
@@ -249,7 +262,7 @@ export class CommandPaletteService {
kind: 'magicShelf' as const,
title: shelf.name,
icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined,
searchText: normalizeSearchTerm(shelf.name),
searchText: normalizeLocalSearchTerm(shelf.name),
route: [`/magic-shelf/${shelf.id}/books`],
}))
);
@@ -262,18 +275,21 @@ export class CommandPaletteService {
kind: 'library' as const,
title: library.name,
icon: library.icon ? toIconSelection(library.icon, library.iconType) : undefined,
searchText: normalizeSearchTerm(library.name),
searchText: normalizeLocalSearchTerm(library.name),
route: [`/library/${library.id}/books`],
}))
);
private readonly visibleBookItems = computed<PaletteItem[]>(() =>
this.trimmedQuery().length >= MIN_BOOK_SEARCH_LENGTH ? this.localBookItems() : []
this.normalizedBookQuery().length >= MIN_BOOK_SEARCH_LENGTH
&& this.normalizedBookQuery() === this.debouncedBookQuery()
? this.remoteBookItems()
: []
);
private toPaletteBookItem(book: Book): PaletteItem {
private toPaletteBookItem(book: BookSummary): PaletteItem {
const metadata = book.metadata;
const title = metadata?.title ?? book.primaryFile?.fileName ?? book.fileName ?? '';
const title = metadata?.title || book.primaryFile?.fileName || '';
const authors = metadata?.authors ?? [];
const publishedDate = metadata?.publishedDate ?? '';
const year = publishedDate && /^\d{4}/.test(publishedDate) ? publishedDate.slice(0, 4) : null;
@@ -285,7 +301,7 @@ export class CommandPaletteService {
kind: 'book',
title,
icon: { type: 'LUCIDE', value: 'book-open' },
searchText: normalizeSearchTerm(haystack),
searchText: normalizeLocalSearchTerm(haystack),
route: ['/book', book.id],
queryParams: { tab: 'view' },
bookMeta: {
@@ -307,7 +323,7 @@ export class CommandPaletteService {
kind,
title: item.label,
icon: item.icon ? toIconSelection(item.icon, item.iconType) : undefined,
searchText: normalizeSearchTerm(item.label),
searchText: normalizeLocalSearchTerm(item.label),
route: item.routerLink,
command: item.action,
};
@@ -0,0 +1,56 @@
import {effect, signal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {debouncedSignal} from './debounced-signal';
describe('debouncedSignal', () => {
beforeEach(() => {
vi.useFakeTimers();
TestBed.configureTestingModule({});
});
afterEach(() => {
TestBed.resetTestingModule();
vi.useRealTimers();
});
it('exposes the initial source value immediately', () => {
const source = signal('initial');
const debounced = TestBed.runInInjectionContext(() => debouncedSignal(source, 200));
expect(debounced()).toBe('initial');
});
it('updates only after the debounce window', () => {
const source = signal('initial');
const debounced = TestBed.runInInjectionContext(() => debouncedSignal(source, 200));
source.set('changed');
TestBed.flushEffects();
vi.advanceTimersByTime(200 - 1);
expect(debounced()).toBe('initial');
vi.advanceTimersByTime(1);
expect(debounced()).toBe('changed');
});
it('does not emit when a change reverts to the settled value', () => {
const source = signal('settled');
const debounced = TestBed.runInInjectionContext(() => debouncedSignal(source, 200));
const values: string[] = [];
TestBed.runInInjectionContext(() => {
effect(() => values.push(debounced()));
});
TestBed.flushEffects();
source.set('temporary');
TestBed.flushEffects();
vi.advanceTimersByTime(200 / 2);
source.set('settled');
TestBed.flushEffects();
vi.advanceTimersByTime(200);
expect(values).toEqual(['settled']);
});
});
@@ -0,0 +1,11 @@
import {Injector, Signal} from '@angular/core';
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
import {debounceTime, distinctUntilChanged} from 'rxjs';
export function debouncedSignal<T>(source: Signal<T>, ms: number, injector?: Injector): Signal<T> {
return toSignal(
toObservable(source, {injector}).pipe(debounceTime(ms), distinctUntilChanged()),
{initialValue: source(), injector},
);
}
@@ -0,0 +1,32 @@
import {describe, expect, it} from 'vitest';
import {normalizeLocalSearchTerm, normalizeRemoteSearchTerm} from './search-terms';
describe('normalizeRemoteSearchTerm', () => {
it('strips punctuation and collapses whitespace without changing letters', () => {
expect(normalizeRemoteSearchTerm(' Dune!\t/ Messiah? ')).toBe('Dune Messiah');
expect(normalizeRemoteSearchTerm(' Łódź Ærø STRAẞE ')).toBe('Łódź Ærø STRAẞE');
});
it('returns an empty string for empty or whitespace-only input', () => {
expect(normalizeRemoteSearchTerm('')).toBe('');
expect(normalizeRemoteSearchTerm(' \t ')).toBe('');
});
});
describe('normalizeLocalSearchTerm', () => {
it('normalizes representative text for local matching', () => {
expect(normalizeLocalSearchTerm(' Ætna Łódź / Straße! ')).toBe('aetna lodz strasse');
});
it('strips punctuation and collapses whitespace', () => {
expect(normalizeLocalSearchTerm(' Dune!\t/ Messiah? ')).toBe('dune messiah');
});
it('returns an empty string for empty or whitespace-only input', () => {
expect(normalizeLocalSearchTerm('')).toBe('');
expect(normalizeLocalSearchTerm(' \t ')).toBe('');
});
});
@@ -0,0 +1,18 @@
export const SEARCH_DEBOUNCE_MS = 200;
export function normalizeRemoteSearchTerm(str: string): string {
return str
.replace(/[!@$%^&*_=|~`<>?/";']/g, '')
.replace(/\s+/g, ' ')
.trim();
}
export function normalizeLocalSearchTerm(str: string): string {
const folded = str.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
.replace(/ø/gi, 'o')
.replace(/ł/gi, 'l')
.replace(/æ/gi, 'ae')
.replace(/œ/gi, 'oe')
.replace(/ß/g, 'ss');
return normalizeRemoteSearchTerm(folded).toLowerCase();
}
+1
View File
@@ -1842,6 +1842,7 @@
"commandPalette": {
"placeholder": "Search books, pages, libraries, shelves, and actions...",
"empty": "No matches",
"bookSearchError": "Book search failed",
"hintNavigate": "navigate",
"hintSelect": "select",
"ariaLabel": "Command palette",