import { computed, inject, Injectable, signal } from '@angular/core'; import { MessageService } from '@openng/optimus-ui/api'; import { toSignal } from '@angular/core/rxjs-interop'; import { Router } from '@angular/router'; import { TranslocoService } from '@jsverse/transloco'; import { injectQuery, QueryClient } from '@tanstack/angular-query-experimental'; import { BookDialogHelperService } from '../book/components/book-browser/book-dialog-helper.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'; 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 { UrlHelperService } from '../../shared/service/url-helper.service'; import { DialogLauncherService } from '../../shared/services/dialog-launcher.service'; 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; source: PaletteItem[]; cap: number; } interface CommandPaletteOverlayController { open(): void; close(): void; focusInput(): void; } const BOOK_RESULT_LIMIT = 50; const MIN_BOOK_SEARCH_LENGTH = 2; @Injectable({ providedIn: 'root' }) export class CommandPaletteService { private readonly router = inject(Router); private readonly t = inject(TranslocoService); private readonly userService = inject(UserService); 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); private readonly dialogLauncherService = inject(DialogLauncherService); private readonly bookDialogHelperService = inject(BookDialogHelperService); private readonly customSvgService = inject(CustomSvgService); private readonly urlHelper = inject(UrlHelperService); private readonly messageService = inject(MessageService); 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 normalizedBookQuery = computed(() => normalizeRemoteSearchTerm(this.query())); private readonly debouncedBookQuery = debouncedSignal(this.normalizedBookQuery, SEARCH_DEBOUNCE_MS); private readonly bookSearchParams = computed(() => ({ 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(() => (this.bookSearchQuery.data()?.content ?? []).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; 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(); 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.customSvgService.getSvgIconContent(item.icon.value).subscribe({ error: () => undefined }); } } }; collect(this.indexedLibraries()); collect(this.indexedShelves()); collect(this.indexedMagicShelves()); } hide(): void { void this.queryClient.cancelQueries({ queryKey: this.bookQueryService.page(this.bookSearchParams()).queryKey, }); 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) { void Promise.resolve(item.command()).catch(() => undefined); return; } if (item.route) { void this.router.navigate(item.route, item.queryParams ? { queryParams: item.queryParams } : {}); } }); } readonly groups = computed(() => { const raw = this.trimmedQuery(); const normalized = normalizeLocalSearchTerm(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(() => this.groups().flatMap((group) => group.items) ); readonly isSearching = computed(() => { const normalized = this.normalizedBookQuery(); if (normalized.length < MIN_BOOK_SEARCH_LENGTH) { return false; } return normalized !== this.debouncedBookQuery() || this.bookSearchQuery.isFetching(); }); 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(() => { this.activeLang(); const user = this.userService.currentUser(); if (!user) return []; return buildQuickActionNavItems(this.translate, user.permissions, { createLibrary: () => void this.dialogLauncherService.openLibraryCreateDialog().catch(() => undefined), createShelf: () => void this.bookDialogHelperService.openShelfCreatorDialog().catch(() => undefined), createMagicShelf: () => void this.dialogLauncherService.openMagicShelfCreateDialog().catch(() => undefined), uploadBook: () => void this.dialogLauncherService.openFileUploadDialog().catch(() => undefined), }).map((item) => this.toPaletteNavItem(item, 'action')); }); private readonly indexedPages = computed(() => { 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(() => this.shelfService.shelves() .filter((shelf) => shelf.id != null) .map((shelf) => ({ id: `shelf:${shelf.id}`, kind: 'shelf' as const, title: shelf.name, icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined, searchText: normalizeLocalSearchTerm(shelf.name), route: [`/shelf/${shelf.id}/books`], })) ); private readonly indexedMagicShelves = computed(() => this.magicShelfService.shelves() .filter((shelf) => shelf.id != null) .map((shelf) => ({ id: `magic-shelf:${shelf.id}`, kind: 'magicShelf' as const, title: shelf.name, icon: shelf.icon ? toIconSelection(shelf.icon, shelf.iconType) : undefined, searchText: normalizeLocalSearchTerm(shelf.name), route: [`/magic-shelf/${shelf.id}/books`], })) ); private readonly indexedLibraries = computed(() => this.libraryService.libraries() .filter((library) => library.id != null) .map((library) => ({ id: `library:${library.id}`, kind: 'library' as const, title: library.name, icon: library.icon ? toIconSelection(library.icon, library.iconType) : undefined, searchText: normalizeLocalSearchTerm(library.name), route: [`/library/${library.id}/books`], })) ); private readonly visibleBookItems = computed(() => this.normalizedBookQuery().length >= MIN_BOOK_SEARCH_LENGTH && this.normalizedBookQuery() === this.debouncedBookQuery() ? this.remoteBookItems() : [] ); private toPaletteBookItem(book: BookSummary): PaletteItem { const metadata = book.metadata; 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; const haystack = [title, metadata?.seriesName ?? '', ...authors].filter(Boolean).join(' '); const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK'; return { id: `book:${book.id}`, kind: 'book', title, icon: { type: 'LUCIDE', value: 'book-open' }, searchText: normalizeLocalSearchTerm(haystack), route: ['/book', book.id], queryParams: { tab: 'view' }, bookMeta: { thumbnailUrl: isAudiobook ? this.urlHelper.getAudiobookThumbnailUrl(book.id, metadata?.audiobookCoverUpdatedOn) : this.urlHelper.getThumbnailUrl(book.id, metadata?.coverUpdatedOn), authors, seriesName: metadata?.seriesName ?? null, seriesNumber: metadata?.seriesNumber ?? null, year, isAudiobook, }, }; } private toPaletteNavItem(item: NavItem, kind: Extract): PaletteItem { return { id: `${kind}:${item.id}`, kind, title: item.label, icon: item.icon ? toIconSelection(item.icon, item.iconType) : undefined, searchText: normalizeLocalSearchTerm(item.label), route: item.routerLink, command: item.action, }; } }