feat(manacore/web): add cross-app search engine with IndexedDB providers

Search registry with providers for todo, calendar, contacts, cards, chat,
and storage. Integrated into layout via contentSearcher prop on GlobalSpotlight.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Till JS 2026-04-01 22:29:59 +02:00
parent f797d70a9e
commit 98ca01f466
13 changed files with 729 additions and 1 deletions

View file

@ -0,0 +1,97 @@
/**
* Cross-App Search Reactive Svelte 5 Store
*
* Wraps the SearchRegistry with debounce, cancellation, and reactive state.
*/
import { SearchRegistry } from './registry';
import type { GroupedSearchResults } from './types';
const DEBOUNCE_MS = 150;
export function createSearchEngine() {
const registry = new SearchRegistry();
let query = $state('');
let results = $state<GroupedSearchResults[]>([]);
let loading = $state(false);
let activeFilters = $state<string[]>([]);
let debounceTimer: ReturnType<typeof setTimeout> | undefined;
let abortController: AbortController | undefined;
function setQuery(q: string) {
query = q;
scheduleSearch();
}
function toggleFilter(appId: string) {
if (activeFilters.includes(appId)) {
activeFilters = activeFilters.filter((id) => id !== appId);
} else {
activeFilters = [...activeFilters, appId];
}
scheduleSearch();
}
function clearFilters() {
activeFilters = [];
scheduleSearch();
}
function scheduleSearch() {
clearTimeout(debounceTimer);
abortController?.abort();
const q = query.trim();
if (!q) {
results = [];
loading = false;
return;
}
loading = true;
debounceTimer = setTimeout(() => executeSearch(q), DEBOUNCE_MS);
}
async function executeSearch(q: string) {
abortController = new AbortController();
const { signal } = abortController;
try {
const r = await registry.search(q, {
appIds: activeFilters.length > 0 ? activeFilters : undefined,
signal,
});
if (!signal.aborted) {
results = r;
loading = false;
}
} catch {
if (!signal.aborted) {
results = [];
loading = false;
}
}
}
return {
registry,
get query() {
return query;
},
get results() {
return results;
},
get loading() {
return loading;
},
get activeFilters() {
return activeFilters;
},
setQuery,
toggleFilter,
clearFilters,
};
}

View file

@ -0,0 +1,4 @@
export { SearchRegistry } from './registry';
export { createSearchEngine } from './engine.svelte';
export { registerAllProviders } from './providers';
export type { SearchProvider, SearchResult, SearchOptions, GroupedSearchResults } from './types';

View file

@ -0,0 +1,55 @@
import { db } from '$lib/data/database';
import { getManaApp } from '@manacore/shared-branding';
import { scoreRecord, truncateSubtitle } from '../scoring';
import type { SearchProvider, SearchResult, SearchOptions } from '../types';
const app = getManaApp('calendar');
export const calendarSearchProvider: SearchProvider = {
appId: 'calendar',
appName: 'Kalender',
appIcon: app?.icon,
appColor: app?.color,
searchableTypes: ['event'],
async search(query: string, options?: SearchOptions): Promise<SearchResult[]> {
const limit = options?.limit ?? 5;
const results: SearchResult[] = [];
const events = await db.table('events').toArray();
for (const event of events) {
if (event.deletedAt) continue;
const { score, matchedField } = scoreRecord(
[
{ name: 'title', value: event.title, weight: 1.0 },
{ name: 'description', value: event.description, weight: 0.7 },
{ name: 'location', value: event.location, weight: 0.5 },
],
query
);
if (score > 0) {
const subtitle = [
event.startDate ? new Date(event.startDate).toLocaleDateString('de-DE') : null,
event.location,
]
.filter(Boolean)
.join(' · ');
results.push({
id: event.id,
type: 'event',
appId: 'calendar',
title: event.title,
subtitle: truncateSubtitle(subtitle) || truncateSubtitle(event.description),
appIcon: app?.icon,
appColor: app?.color,
href: `/calendar?event=${event.id}`,
score,
matchedField,
});
}
}
return results.sort((a, b) => b.score - a.score).slice(0, limit);
},
};

View file

@ -0,0 +1,75 @@
import { db } from '$lib/data/database';
import { getManaApp } from '@manacore/shared-branding';
import { scoreRecord, truncateSubtitle } from '../scoring';
import type { SearchProvider, SearchResult, SearchOptions } from '../types';
const app = getManaApp('cards');
export const cardsSearchProvider: SearchProvider = {
appId: 'cards',
appName: 'Cards',
appIcon: app?.icon,
appColor: app?.color,
searchableTypes: ['deck', 'card'],
async search(query: string, options?: SearchOptions): Promise<SearchResult[]> {
const limit = options?.limit ?? 5;
const results: SearchResult[] = [];
// Search decks
const decks = await db.table('cardDecks').toArray();
for (const deck of decks) {
if (deck.deletedAt) continue;
const { score, matchedField } = scoreRecord(
[
{ name: 'name', value: deck.name, weight: 1.0 },
{ name: 'description', value: deck.description, weight: 0.7 },
],
query
);
if (score > 0) {
results.push({
id: deck.id,
type: 'deck',
appId: 'cards',
title: deck.name,
subtitle: truncateSubtitle(deck.description) || 'Deck',
appIcon: app?.icon,
appColor: app?.color,
href: `/cards/${deck.id}`,
score,
matchedField,
});
}
}
// Search cards (front/back)
const cards = await db.table('cards').toArray();
for (const card of cards) {
if (card.deletedAt) continue;
const { score, matchedField } = scoreRecord(
[
{ name: 'front', value: card.front, weight: 1.0 },
{ name: 'back', value: card.back, weight: 0.8 },
],
query
);
if (score > 0) {
results.push({
id: card.id,
type: 'card',
appId: 'cards',
title: truncateSubtitle(card.front, 60) || 'Karte',
subtitle: truncateSubtitle(card.back, 60),
appIcon: app?.icon,
appColor: app?.color,
href: `/cards/${card.deckId}`,
score,
matchedField,
});
}
}
return results.sort((a, b) => b.score - a.score).slice(0, limit);
},
};

View file

@ -0,0 +1,72 @@
import { db } from '$lib/data/database';
import { getManaApp } from '@manacore/shared-branding';
import { scoreRecord, truncateSubtitle } from '../scoring';
import type { SearchProvider, SearchResult, SearchOptions } from '../types';
const app = getManaApp('chat');
export const chatSearchProvider: SearchProvider = {
appId: 'chat',
appName: 'Chat',
appIcon: app?.icon,
appColor: app?.color,
searchableTypes: ['conversation', 'message'],
async search(query: string, options?: SearchOptions): Promise<SearchResult[]> {
const limit = options?.limit ?? 5;
const results: SearchResult[] = [];
// Search conversations by title
const conversations = await db.table('conversations').toArray();
for (const conv of conversations) {
if (conv.deletedAt || conv.isArchived) continue;
const { score, matchedField } = scoreRecord(
[{ name: 'title', value: conv.title, weight: 1.0 }],
query
);
if (score > 0) {
results.push({
id: conv.id,
type: 'conversation',
appId: 'chat',
title: conv.title || 'Untitled',
subtitle: 'Konversation',
appIcon: app?.icon,
appColor: app?.color,
href: `/chat/${conv.id}`,
score,
matchedField,
});
}
}
// Search recent messages (limit scan to avoid performance issues)
const messages = await db.table('messages').limit(500).toArray();
const seenConversations = new Set<string>();
for (const msg of messages) {
if (msg.deletedAt || seenConversations.has(msg.conversationId)) continue;
const { score, matchedField } = scoreRecord(
[{ name: 'messageText', value: msg.messageText, weight: 0.7 }],
query
);
if (score > 0) {
seenConversations.add(msg.conversationId);
results.push({
id: msg.id,
type: 'message',
appId: 'chat',
title: truncateSubtitle(msg.messageText, 60) || 'Nachricht',
subtitle: `in Konversation`,
appIcon: app?.icon,
appColor: app?.color,
href: `/chat/${msg.conversationId}`,
score,
matchedField,
});
}
}
return results.sort((a, b) => b.score - a.score).slice(0, limit);
},
};

View file

@ -0,0 +1,52 @@
import { db } from '$lib/data/database';
import { getManaApp } from '@manacore/shared-branding';
import { scoreRecord } from '../scoring';
import type { SearchProvider, SearchResult, SearchOptions } from '../types';
const app = getManaApp('contacts');
export const contactsSearchProvider: SearchProvider = {
appId: 'contacts',
appName: 'Kontakte',
appIcon: app?.icon,
appColor: app?.color,
searchableTypes: ['contact'],
async search(query: string, options?: SearchOptions): Promise<SearchResult[]> {
const limit = options?.limit ?? 5;
const results: SearchResult[] = [];
const contacts = await db.table('contacts').toArray();
for (const contact of contacts) {
if (contact.deletedAt || contact.isArchived) continue;
const fullName = [contact.firstName, contact.lastName].filter(Boolean).join(' ');
const { score, matchedField } = scoreRecord(
[
{ name: 'name', value: fullName, weight: 1.0 },
{ name: 'email', value: contact.email, weight: 0.5 },
{ name: 'phone', value: contact.phone, weight: 0.4 },
{ name: 'company', value: contact.company, weight: 0.5 },
{ name: 'jobTitle', value: contact.jobTitle, weight: 0.4 },
],
query
);
if (score > 0) {
const subtitle = [contact.company, contact.email].filter(Boolean).join(' · ');
results.push({
id: contact.id,
type: 'contact',
appId: 'contacts',
title: fullName || contact.email || 'Unbekannt',
subtitle: subtitle || undefined,
appIcon: app?.icon,
appColor: app?.color,
href: `/contacts?id=${contact.id}`,
score,
matchedField,
});
}
}
return results.sort((a, b) => b.score - a.score).slice(0, limit);
},
};

View file

@ -0,0 +1,25 @@
import type { SearchRegistry } from '../registry';
import { todoSearchProvider } from './todo';
import { calendarSearchProvider } from './calendar';
import { contactsSearchProvider } from './contacts';
import { chatSearchProvider } from './chat';
import { storageSearchProvider } from './storage';
import { cardsSearchProvider } from './cards';
export function registerAllProviders(registry: SearchRegistry): void {
registry.register(todoSearchProvider);
registry.register(calendarSearchProvider);
registry.register(contactsSearchProvider);
registry.register(chatSearchProvider);
registry.register(storageSearchProvider);
registry.register(cardsSearchProvider);
}
export {
todoSearchProvider,
calendarSearchProvider,
contactsSearchProvider,
chatSearchProvider,
storageSearchProvider,
cardsSearchProvider,
};

View file

@ -0,0 +1,72 @@
import { db } from '$lib/data/database';
import { getManaApp } from '@manacore/shared-branding';
import { scoreRecord } from '../scoring';
import type { SearchProvider, SearchResult, SearchOptions } from '../types';
const app = getManaApp('storage');
export const storageSearchProvider: SearchProvider = {
appId: 'storage',
appName: 'Storage',
appIcon: app?.icon,
appColor: app?.color,
searchableTypes: ['file', 'folder'],
async search(query: string, options?: SearchOptions): Promise<SearchResult[]> {
const limit = options?.limit ?? 5;
const results: SearchResult[] = [];
// Search files
const files = await db.table('files').toArray();
for (const file of files) {
if (file.deletedAt || file.isDeleted) continue;
const { score, matchedField } = scoreRecord(
[
{ name: 'name', value: file.name, weight: 1.0 },
{ name: 'originalName', value: file.originalName, weight: 0.8 },
],
query
);
if (score > 0) {
results.push({
id: file.id,
type: 'file',
appId: 'storage',
title: file.name,
subtitle: file.mimeType || 'Datei',
appIcon: app?.icon,
appColor: app?.color,
href: `/storage?file=${file.id}`,
score,
matchedField,
});
}
}
// Search folders
const folders = await db.table('storageFolders').toArray();
for (const folder of folders) {
if (folder.deletedAt || folder.isDeleted) continue;
const { score, matchedField } = scoreRecord(
[{ name: 'name', value: folder.name, weight: 1.0 }],
query
);
if (score > 0) {
results.push({
id: folder.id,
type: 'folder',
appId: 'storage',
title: folder.name,
subtitle: 'Ordner',
appIcon: app?.icon,
appColor: app?.color,
href: `/storage?folder=${folder.id}`,
score,
matchedField,
});
}
}
return results.sort((a, b) => b.score - a.score).slice(0, limit);
},
};

View file

@ -0,0 +1,72 @@
import { db } from '$lib/data/database';
import { getManaApp } from '@manacore/shared-branding';
import { scoreRecord, truncateSubtitle } from '../scoring';
import type { SearchProvider, SearchResult, SearchOptions } from '../types';
const app = getManaApp('todo');
export const todoSearchProvider: SearchProvider = {
appId: 'todo',
appName: 'Todo',
appIcon: app?.icon,
appColor: app?.color,
searchableTypes: ['task', 'project'],
async search(query: string, options?: SearchOptions): Promise<SearchResult[]> {
const limit = options?.limit ?? 5;
const results: SearchResult[] = [];
// Search tasks
const tasks = await db.table('tasks').toArray();
for (const task of tasks) {
if (task.deletedAt) continue;
const { score, matchedField } = scoreRecord(
[
{ name: 'title', value: task.title, weight: 1.0 },
{ name: 'description', value: task.description, weight: 0.7 },
],
query
);
if (score > 0) {
results.push({
id: task.id,
type: 'task',
appId: 'todo',
title: task.title,
subtitle: truncateSubtitle(task.description),
appIcon: app?.icon,
appColor: app?.color,
href: `/todo?task=${task.id}`,
score,
matchedField,
});
}
}
// Search projects
const projects = await db.table('todoProjects').toArray();
for (const project of projects) {
if (project.deletedAt) continue;
const { score, matchedField } = scoreRecord(
[{ name: 'name', value: project.name, weight: 1.0 }],
query
);
if (score > 0) {
results.push({
id: project.id,
type: 'project',
appId: 'todo',
title: project.name,
subtitle: 'Projekt',
appIcon: app?.icon,
appColor: app?.color,
href: `/todo?project=${project.id}`,
score,
matchedField,
});
}
}
return results.sort((a, b) => b.score - a.score).slice(0, limit);
},
};

View file

@ -0,0 +1,67 @@
/**
* Cross-App Search Provider Registry
*
* Central registry that fans out search queries to all registered providers
* in parallel and merges results sorted by relevance.
*/
import type { SearchProvider, SearchResult, SearchOptions, GroupedSearchResults } from './types';
export class SearchRegistry {
private providers: SearchProvider[] = [];
register(provider: SearchProvider): void {
// Avoid duplicate registration
if (!this.providers.some((p) => p.appId === provider.appId)) {
this.providers.push(provider);
}
}
getProviders(): SearchProvider[] {
return this.providers;
}
/**
* Search across all registered providers in parallel.
* Returns results grouped by app, each group sorted by score.
*/
async search(query: string, options?: SearchOptions): Promise<GroupedSearchResults[]> {
const q = query.trim();
if (!q) return [];
const limit = options?.limit ?? 5;
const targetProviders = options?.appIds
? this.providers.filter((p) => options.appIds!.includes(p.appId))
: this.providers;
const settled = await Promise.allSettled(
targetProviders.map((provider) =>
provider.search(q, { ...options, limit }).then((results) => ({
provider,
results,
}))
)
);
const groups: GroupedSearchResults[] = [];
for (const result of settled) {
if (result.status !== 'fulfilled') continue;
const { provider, results } = result.value;
if (results.length === 0) continue;
groups.push({
appId: provider.appId,
appName: provider.appName,
appIcon: provider.appIcon,
appColor: provider.appColor,
results: results.sort((a, b) => b.score - a.score).slice(0, limit),
});
}
// Sort groups by their best result's score (descending)
groups.sort((a, b) => (b.results[0]?.score ?? 0) - (a.results[0]?.score ?? 0));
return groups;
}
}

View file

@ -0,0 +1,56 @@
/**
* Cross-App Search Text matching and relevance scoring
*/
/**
* Score a text field against a query string.
* Returns 0 if no match, or a score between 0.11.0 based on match quality.
*/
export function scoreMatch(text: string | undefined | null, query: string, weight: number): number {
if (!text) return 0;
const lower = text.toLowerCase();
const q = query.toLowerCase();
if (lower === q) return 1.0 * weight;
if (lower.startsWith(q)) return 0.9 * weight;
if (lower.includes(q)) return 0.7 * weight;
// Word-boundary match (query matches start of any word)
const words = lower.split(/\s+/);
if (words.some((w) => w.startsWith(q))) return 0.8 * weight;
return 0;
}
/**
* Score a record against a query across multiple fields.
* Returns the highest score from any field, plus the name of the matched field.
*/
export function scoreRecord(
fields: { name: string; value: string | undefined | null; weight: number }[],
query: string
): { score: number; matchedField?: string } {
let best = 0;
let matchedField: string | undefined;
for (const field of fields) {
const s = scoreMatch(field.value, query, field.weight);
if (s > best) {
best = s;
matchedField = field.name;
}
}
return { score: best, matchedField };
}
/**
* Truncate text to a max length, adding ellipsis if needed.
*/
export function truncateSubtitle(text: string | undefined | null, maxLen = 80): string | undefined {
if (!text) return undefined;
const clean = text.replace(/\n/g, ' ').trim();
if (clean.length <= maxLen) return clean;
return clean.slice(0, maxLen).trimEnd() + '...';
}

View file

@ -0,0 +1,61 @@
/**
* Cross-App Search Type Definitions
*
* Provider-based search architecture: each app registers a SearchProvider
* that knows how to search its own IndexedDB data and return ranked results.
*/
export interface SearchResult {
/** Unique ID (usually the record ID) */
id: string;
/** Content type (e.g. 'task', 'event', 'contact') */
type: string;
/** Owning app ID (e.g. 'todo', 'calendar') */
appId: string;
/** Primary display text */
title: string;
/** Secondary text (description snippet, date, etc.) */
subtitle?: string;
/** App icon (data URL) */
appIcon?: string;
/** App brand color */
appColor?: string;
/** Navigation URL */
href: string;
/** Relevance score (01) */
score: number;
/** Which field matched */
matchedField?: string;
}
export interface SearchOptions {
/** Max results per provider (default: 5) */
limit?: number;
/** Filter to specific app IDs */
appIds?: string[];
/** AbortSignal for cancellation */
signal?: AbortSignal;
}
export interface SearchProvider {
/** App identifier */
appId: string;
/** Display name */
appName: string;
/** App icon (data URL) */
appIcon?: string;
/** App brand color */
appColor?: string;
/** Content types this provider can search (for filter UI) */
searchableTypes: string[];
/** Execute search against this provider's data */
search(query: string, options?: SearchOptions): Promise<SearchResult[]>;
}
export interface GroupedSearchResults {
appId: string;
appName: string;
appIcon?: string;
appColor?: string;
results: SearchResult[];
}

View file

@ -7,7 +7,12 @@
import SessionWarning from '$lib/components/SessionWarning.svelte';
import { locale } from 'svelte-i18n';
import { PillNavigation, TagStrip, DragPreview, ActionZone } from '@manacore/shared-ui';
import type { PillNavItem, PillDropdownItem, SpotlightAction } from '@manacore/shared-ui';
import type {
PillNavItem,
PillDropdownItem,
SpotlightAction,
ContentSearcher,
} from '@manacore/shared-ui';
import { tagLocalStore, tagMutations, useAllTags } from '$lib/stores/tags.svelte';
import { linkLocalStore, linkMutations } from '@manacore/shared-links';
import { manacoreStore } from '$lib/data/local-store';
@ -43,6 +48,9 @@
import { onboardingStore } from '$lib/stores/onboarding.svelte';
import { OnboardingWizard } from '$lib/components/onboarding';
import { STORAGE_KEYS } from '$lib/config/storage-keys';
import { SearchRegistry } from '$lib/search/registry';
import { registerAllProviders } from '$lib/search/providers';
import { initSharedUload } from '@manacore/shared-uload';
let { children }: { children: Snippet } = $props();
@ -250,6 +258,9 @@
cardsReader.initialize(),
]);
// Initialize shared-uload (opens uLoad IndexedDB for cross-app link creation)
initSharedUload();
// Start syncing to server
const getToken = () => authStore.getValidToken();
manacoreStore.startSync(getToken);
@ -280,6 +291,14 @@
loading = false;
});
// Cross-app search
const searchRegistry = new SearchRegistry();
registerAllProviders(searchRegistry);
const contentSearcher: ContentSearcher = async (query, signal) => {
return searchRegistry.search(query, { signal });
};
const spotlightActions: SpotlightAction[] = [
{ id: 'home', label: 'Home', category: 'Navigation', onExecute: () => goto('/home') },
{
@ -353,6 +372,7 @@
helpHref="/help"
allAppsHref="/apps"
{spotlightActions}
{contentSearcher}
/>
<!-- TagStrip (above PillNav, toggled via Tags pill) -->