refactor(books): shared search normalisation and debounce helpers + migrate command palette to server-side queries (#2232)
This commit is contained in:
@@ -38,7 +38,9 @@
|
|||||||
|
|
||||||
@if (hasQuery) {
|
@if (hasQuery) {
|
||||||
<div class="command-palette-results" role="listbox">
|
<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>
|
<div class="command-palette-empty">{{ t('empty') }}</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ class MockCommandPaletteService {
|
|||||||
readonly isOpen = this._isOpen.asReadonly();
|
readonly isOpen = this._isOpen.asReadonly();
|
||||||
readonly query = signal('');
|
readonly query = signal('');
|
||||||
readonly isSearching = signal(false);
|
readonly isSearching = signal(false);
|
||||||
|
readonly bookSearchFailed = signal(false);
|
||||||
readonly items = signal<PaletteItem[]>([]);
|
readonly items = signal<PaletteItem[]>([]);
|
||||||
readonly groups = computed<PaletteGroup[]>(() =>
|
readonly groups = computed<PaletteGroup[]>(() =>
|
||||||
this.query().trim()
|
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 { TestBed } from '@angular/core/testing';
|
||||||
|
import { HttpTestingController } from '@angular/common/http/testing';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { of } from 'rxjs';
|
import { of } from 'rxjs';
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
import { MessageService } from '@openng/optimus-ui/api';
|
import { MessageService } from '@openng/optimus-ui/api';
|
||||||
|
import { createQueryClientHarness } from '../../core/testing/query-testing';
|
||||||
import { getTranslocoModule } from '../../core/testing/transloco-testing';
|
import { getTranslocoModule } from '../../core/testing/transloco-testing';
|
||||||
import { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.service';
|
import { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.service';
|
||||||
import { Book } from '../book/model/book.model';
|
import { BookPage } from '../book/data/book-query.models';
|
||||||
import { BookService } from '../book/service/book.service';
|
import { BookQueryService } from '../book/data/book-query.service';
|
||||||
|
import { BookSummary } from '../book/data/book-response.models';
|
||||||
import { LibraryService } from '../book/service/library.service';
|
import { LibraryService } from '../book/service/library.service';
|
||||||
import { ShelfService } from '../book/service/shelf.service';
|
import { ShelfService } from '../book/service/shelf.service';
|
||||||
import { MagicShelfService } from '../magic-shelf/service/magic-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';
|
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 {
|
return {
|
||||||
id,
|
id,
|
||||||
libraryId: 1,
|
libraryId: 1,
|
||||||
@@ -27,16 +35,17 @@ function makeBook(id: number, title: string, authors: string[] = [], overrides:
|
|||||||
...overrides,
|
...overrides,
|
||||||
metadata: {
|
metadata: {
|
||||||
bookId: id,
|
bookId: id,
|
||||||
title,
|
|
||||||
authors,
|
authors,
|
||||||
|
allMetadataLocked: false,
|
||||||
|
title,
|
||||||
...overrides.metadata,
|
...overrides.metadata,
|
||||||
},
|
},
|
||||||
} as Book;
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('CommandPaletteService', () => {
|
describe('CommandPaletteService', () => {
|
||||||
let service: CommandPaletteService;
|
let service: CommandPaletteService;
|
||||||
let books = signal<Book[]>([]);
|
let http: HttpTestingController;
|
||||||
let urlHelper: {
|
let urlHelper: {
|
||||||
getThumbnailUrl: ReturnType<typeof vi.fn>;
|
getThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||||
getAudiobookThumbnailUrl: ReturnType<typeof vi.fn>;
|
getAudiobookThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||||
@@ -47,11 +56,7 @@ describe('CommandPaletteService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
books = signal([
|
const queryHarness = createQueryClientHarness();
|
||||||
makeBook(1, 'The Hobbit', ['J.R.R. Tolkien']),
|
|
||||||
makeBook(2, 'The Fellowship of the Ring', ['J.R.R. Tolkien']),
|
|
||||||
makeBook(3, 'Dune', ['Frank Herbert']),
|
|
||||||
]);
|
|
||||||
urlHelper = {
|
urlHelper = {
|
||||||
getThumbnailUrl: vi.fn(() => null),
|
getThumbnailUrl: vi.fn(() => null),
|
||||||
getAudiobookThumbnailUrl: vi.fn(() => null),
|
getAudiobookThumbnailUrl: vi.fn(() => null),
|
||||||
@@ -60,8 +65,9 @@ describe('CommandPaletteService', () => {
|
|||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
imports: [getTranslocoModule()],
|
imports: [getTranslocoModule()],
|
||||||
providers: [
|
providers: [
|
||||||
|
...queryHarness.providers,
|
||||||
{ provide: Router, useValue: { navigate: vi.fn(() => Promise.resolve(true)) } },
|
{ provide: Router, useValue: { navigate: vi.fn(() => Promise.resolve(true)) } },
|
||||||
{ provide: BookService, useValue: { books: books.asReadonly() } },
|
BookQueryService,
|
||||||
{ provide: ShelfService, useValue: { shelves: signal([]) } },
|
{ provide: ShelfService, useValue: { shelves: signal([]) } },
|
||||||
{ provide: MagicShelfService, useValue: { shelves: signal([]) } },
|
{ provide: MagicShelfService, useValue: { shelves: signal([]) } },
|
||||||
{ provide: LibraryService, useValue: { libraries: signal([]) } },
|
{ provide: LibraryService, useValue: { libraries: signal([]) } },
|
||||||
@@ -87,71 +93,184 @@ describe('CommandPaletteService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
service = TestBed.inject(CommandPaletteService);
|
service = TestBed.inject(CommandPaletteService);
|
||||||
|
http = TestBed.inject(HttpTestingController);
|
||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
http.verify();
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
vi.runOnlyPendingTimers();
|
vi.runOnlyPendingTimers();
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('queries matching book groups locally after the debounce window', async () => {
|
function makeBookPage(books: BookSummary[]): BookPage {
|
||||||
service.query.set('tolkien');
|
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();
|
TestBed.flushEffects();
|
||||||
await vi.advanceTimersByTimeAsync(200);
|
await vi.advanceTimersByTimeAsync(200);
|
||||||
TestBed.flushEffects();
|
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');
|
const bookGroup = service.groups().find((group) => group.kind === 'book');
|
||||||
|
|
||||||
expect(bookGroup).toBeDefined();
|
expect(bookGroup).toBeDefined();
|
||||||
expect(bookGroup?.items.map((item) => item.title)).toEqual([
|
expect(bookGroup?.items.map((item) => item.title)).toEqual(['It']);
|
||||||
'The Hobbit',
|
|
||||||
'The Fellowship of the Ring',
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does not show book groups for one-character searches', async () => {
|
it('reports a failed book search instead of claiming no results', async () => {
|
||||||
service.query.set('d');
|
service.open();
|
||||||
|
service.query.set('tolkien');
|
||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
await vi.advanceTimersByTimeAsync(200);
|
await vi.advanceTimersByTimeAsync(200);
|
||||||
TestBed.flushEffects();
|
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();
|
expect(service.groups().find((group) => group.kind === 'book')).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns no groups when the query is empty', () => {
|
it('does not search when the normalized term is below two characters', async () => {
|
||||||
service.query.set('');
|
service.open();
|
||||||
|
service.query.set('d!');
|
||||||
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');
|
|
||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
await vi.advanceTimersByTimeAsync(200);
|
await vi.advanceTimersByTimeAsync(200);
|
||||||
TestBed.flushEffects();
|
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);
|
http.expectNone(request => request.url.endsWith('/api/v1/books/page'));
|
||||||
expect(book?.bookMeta?.thumbnailUrl).toBe('/audio-thumb.jpg');
|
expect(service.groups().find((group) => group.kind === 'book')).toBeUndefined();
|
||||||
expect(urlHelper.getAudiobookThumbnailUrl).toHaveBeenCalledWith(4, 'audio-updated');
|
});
|
||||||
expect(urlHelper.getThumbnailUrl).not.toHaveBeenCalled();
|
|
||||||
|
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 { computed, inject, Injectable, signal } from '@angular/core';
|
||||||
import { MessageService } from '@openng/optimus-ui/api';
|
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 { Router } from '@angular/router';
|
||||||
import { TranslocoService } from '@jsverse/transloco';
|
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 { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.service';
|
||||||
import { filterBooksBySearchTerm, normalizeSearchTerm } from '../book/components/book-browser/filters/HeaderFilter';
|
import { BookPageParams, EMPTY_FACET_SELECTION } from '../book/data/book-query-params';
|
||||||
import { Book } from '../book/model/book.model';
|
import { BookSummary } from '../book/data/book-response.models';
|
||||||
import { BookService } from '../book/service/book.service';
|
import { BookQueryService } from '../book/data/book-query.service';
|
||||||
import { LibraryService } from '../book/service/library.service';
|
import { LibraryService } from '../book/service/library.service';
|
||||||
import { ShelfService } from '../book/service/shelf.service';
|
import { ShelfService } from '../book/service/shelf.service';
|
||||||
import { MagicShelfService } from '../magic-shelf/service/magic-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 { toIconSelection } from '../../shared/icons/icon-selection';
|
||||||
|
|
||||||
import { PaletteGroup, PaletteItem, PaletteItemKind } from './command-palette.model';
|
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 {
|
interface GroupDef {
|
||||||
kind: PaletteItemKind;
|
kind: PaletteItemKind;
|
||||||
@@ -36,14 +38,14 @@ interface CommandPaletteOverlayController {
|
|||||||
|
|
||||||
const BOOK_RESULT_LIMIT = 50;
|
const BOOK_RESULT_LIMIT = 50;
|
||||||
const MIN_BOOK_SEARCH_LENGTH = 2;
|
const MIN_BOOK_SEARCH_LENGTH = 2;
|
||||||
const BOOK_SEARCH_DEBOUNCE_MS = 200;
|
|
||||||
|
|
||||||
@Injectable({ providedIn: 'root' })
|
@Injectable({ providedIn: 'root' })
|
||||||
export class CommandPaletteService {
|
export class CommandPaletteService {
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private readonly userService = inject(UserService);
|
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 shelfService = inject(ShelfService);
|
||||||
private readonly magicShelfService = inject(MagicShelfService);
|
private readonly magicShelfService = inject(MagicShelfService);
|
||||||
private readonly libraryService = inject(LibraryService);
|
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 activeLang = toSignal(this.t.langChanges$, { initialValue: this.t.getActiveLang() });
|
||||||
private readonly translate = (key: string): string => this.t.translate(key);
|
private readonly translate = (key: string): string => this.t.translate(key);
|
||||||
private readonly trimmedQuery = computed(() => this.query().trim());
|
private readonly trimmedQuery = computed(() => this.query().trim());
|
||||||
private readonly debouncedBookQuery = toSignal(
|
private readonly normalizedBookQuery = computed(() => normalizeRemoteSearchTerm(this.query()));
|
||||||
toObservable(this.trimmedQuery).pipe(
|
private readonly debouncedBookQuery = debouncedSignal(this.normalizedBookQuery, SEARCH_DEBOUNCE_MS);
|
||||||
debounceTime(BOOK_SEARCH_DEBOUNCE_MS),
|
private readonly bookSearchParams = computed<BookPageParams>(() => ({
|
||||||
distinctUntilChanged(),
|
query: this.debouncedBookQuery(),
|
||||||
),
|
facets: EMPTY_FACET_SELECTION,
|
||||||
{ initialValue: this.trimmedQuery() },
|
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)
|
readonly bookSearchFailed = computed(() =>
|
||||||
.slice(0, BOOK_RESULT_LIMIT)
|
this._isOpen()
|
||||||
.map((book) => this.toPaletteBookItem(book));
|
&& this.normalizedBookQuery().length >= MIN_BOOK_SEARCH_LENGTH
|
||||||
});
|
&& this.normalizedBookQuery() === this.debouncedBookQuery()
|
||||||
|
&& this.bookSearchQuery.isError()
|
||||||
|
);
|
||||||
|
|
||||||
registerOverlayController(controller: CommandPaletteOverlayController): () => void {
|
registerOverlayController(controller: CommandPaletteOverlayController): () => void {
|
||||||
this.overlayController = controller;
|
this.overlayController = controller;
|
||||||
@@ -116,6 +126,9 @@ export class CommandPaletteService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
hide(): void {
|
hide(): void {
|
||||||
|
void this.queryClient.cancelQueries({
|
||||||
|
queryKey: this.bookQueryService.page(this.bookSearchParams()).queryKey,
|
||||||
|
});
|
||||||
this.overlayController?.close();
|
this.overlayController?.close();
|
||||||
this._isOpen.set(false);
|
this._isOpen.set(false);
|
||||||
this.query.set('');
|
this.query.set('');
|
||||||
@@ -144,7 +157,7 @@ export class CommandPaletteService {
|
|||||||
|
|
||||||
readonly groups = computed<PaletteGroup[]>(() => {
|
readonly groups = computed<PaletteGroup[]>(() => {
|
||||||
const raw = this.trimmedQuery();
|
const raw = this.trimmedQuery();
|
||||||
const normalized = normalizeSearchTerm(raw);
|
const normalized = normalizeLocalSearchTerm(raw);
|
||||||
const tokens = normalized ? normalized.split(/\s+/).filter(Boolean) : [];
|
const tokens = normalized ? normalized.split(/\s+/).filter(Boolean) : [];
|
||||||
if (tokens.length === 0) {
|
if (tokens.length === 0) {
|
||||||
return [];
|
return [];
|
||||||
@@ -182,12 +195,12 @@ export class CommandPaletteService {
|
|||||||
);
|
);
|
||||||
|
|
||||||
readonly isSearching = computed(() => {
|
readonly isSearching = computed(() => {
|
||||||
const raw = this.trimmedQuery();
|
const normalized = this.normalizedBookQuery();
|
||||||
if (raw.length < MIN_BOOK_SEARCH_LENGTH) {
|
if (normalized.length < MIN_BOOK_SEARCH_LENGTH) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return raw !== this.debouncedBookQuery();
|
return normalized !== this.debouncedBookQuery() || this.bookSearchQuery.isFetching();
|
||||||
});
|
});
|
||||||
|
|
||||||
private filterItems(source: PaletteItem[], tokens: string[], cap: number): PaletteItem[] {
|
private filterItems(source: PaletteItem[], tokens: string[], cap: number): PaletteItem[] {
|
||||||
@@ -236,7 +249,7 @@ export class CommandPaletteService {
|
|||||||
kind: 'shelf' as const,
|
kind: 'shelf' as const,
|
||||||
title: shelf.name,
|
title: shelf.name,
|
||||||
icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined,
|
icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined,
|
||||||
searchText: normalizeSearchTerm(shelf.name),
|
searchText: normalizeLocalSearchTerm(shelf.name),
|
||||||
route: [`/shelf/${shelf.id}/books`],
|
route: [`/shelf/${shelf.id}/books`],
|
||||||
}))
|
}))
|
||||||
);
|
);
|
||||||
@@ -249,7 +262,7 @@ export class CommandPaletteService {
|
|||||||
kind: 'magicShelf' as const,
|
kind: 'magicShelf' as const,
|
||||||
title: shelf.name,
|
title: shelf.name,
|
||||||
icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined,
|
icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined,
|
||||||
searchText: normalizeSearchTerm(shelf.name),
|
searchText: normalizeLocalSearchTerm(shelf.name),
|
||||||
route: [`/magic-shelf/${shelf.id}/books`],
|
route: [`/magic-shelf/${shelf.id}/books`],
|
||||||
}))
|
}))
|
||||||
);
|
);
|
||||||
@@ -262,18 +275,21 @@ export class CommandPaletteService {
|
|||||||
kind: 'library' as const,
|
kind: 'library' as const,
|
||||||
title: library.name,
|
title: library.name,
|
||||||
icon: library.icon ? toIconSelection(library.icon, library.iconType) : undefined,
|
icon: library.icon ? toIconSelection(library.icon, library.iconType) : undefined,
|
||||||
searchText: normalizeSearchTerm(library.name),
|
searchText: normalizeLocalSearchTerm(library.name),
|
||||||
route: [`/library/${library.id}/books`],
|
route: [`/library/${library.id}/books`],
|
||||||
}))
|
}))
|
||||||
);
|
);
|
||||||
|
|
||||||
private readonly visibleBookItems = computed<PaletteItem[]>(() =>
|
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 metadata = book.metadata;
|
||||||
const title = metadata?.title ?? book.primaryFile?.fileName ?? book.fileName ?? '';
|
const title = metadata?.title || book.primaryFile?.fileName || '';
|
||||||
const authors = metadata?.authors ?? [];
|
const authors = metadata?.authors ?? [];
|
||||||
const publishedDate = metadata?.publishedDate ?? '';
|
const publishedDate = metadata?.publishedDate ?? '';
|
||||||
const year = publishedDate && /^\d{4}/.test(publishedDate) ? publishedDate.slice(0, 4) : null;
|
const year = publishedDate && /^\d{4}/.test(publishedDate) ? publishedDate.slice(0, 4) : null;
|
||||||
@@ -285,7 +301,7 @@ export class CommandPaletteService {
|
|||||||
kind: 'book',
|
kind: 'book',
|
||||||
title,
|
title,
|
||||||
icon: { type: 'LUCIDE', value: 'book-open' },
|
icon: { type: 'LUCIDE', value: 'book-open' },
|
||||||
searchText: normalizeSearchTerm(haystack),
|
searchText: normalizeLocalSearchTerm(haystack),
|
||||||
route: ['/book', book.id],
|
route: ['/book', book.id],
|
||||||
queryParams: { tab: 'view' },
|
queryParams: { tab: 'view' },
|
||||||
bookMeta: {
|
bookMeta: {
|
||||||
@@ -307,7 +323,7 @@ export class CommandPaletteService {
|
|||||||
kind,
|
kind,
|
||||||
title: item.label,
|
title: item.label,
|
||||||
icon: item.icon ? toIconSelection(item.icon, item.iconType) : undefined,
|
icon: item.icon ? toIconSelection(item.icon, item.iconType) : undefined,
|
||||||
searchText: normalizeSearchTerm(item.label),
|
searchText: normalizeLocalSearchTerm(item.label),
|
||||||
route: item.routerLink,
|
route: item.routerLink,
|
||||||
command: item.action,
|
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();
|
||||||
|
}
|
||||||
@@ -1842,6 +1842,7 @@
|
|||||||
"commandPalette": {
|
"commandPalette": {
|
||||||
"placeholder": "Search books, pages, libraries, shelves, and actions...",
|
"placeholder": "Search books, pages, libraries, shelves, and actions...",
|
||||||
"empty": "No matches",
|
"empty": "No matches",
|
||||||
|
"bookSearchError": "Book search failed",
|
||||||
"hintNavigate": "navigate",
|
"hintNavigate": "navigate",
|
||||||
"hintSelect": "select",
|
"hintSelect": "select",
|
||||||
"ariaLabel": "Command palette",
|
"ariaLabel": "Command palette",
|
||||||
|
|||||||
Reference in New Issue
Block a user