openclaw/apps/web/lib/search-index.ts

128 lines
3.6 KiB
TypeScript
Raw Normal View History

Dench workspace: unified @ mention search, entry detail modal, and workspace link system New libraries: - workspace-links.ts: builders, parsers, and type guards for workspace URLs (/workspace?path=... for files/objects, /workspace?entry=objName:id for entries). Replaces ad-hoc relative-path links with real navigable URLs. - search-index.ts: useSearchIndex hook that fetches a unified search index from the API and provides Fuse.js-powered fuzzy search across files, objects, and database entries. Exposes a stable ref-based search function safe for capture in tiptap extensions. New API routes: - GET /api/workspace/search-index: builds a flat search index from the filesystem tree (knowledge/, reports/, top-level files) and all DuckDB object entries with display-field labels and preview fields. - GET /api/workspace/objects/[name]/entries/[id]: fetches a single entry with all field values, resolved relation labels, reverse relations (incoming links from other objects), and the effective display field. New component: - EntryDetailModal: slide-over modal for viewing an individual entry's fields, enum badges, user avatars, clickable relation chips (navigate to related entries), reverse relation sections, and timestamps. Supports Escape to close and backdrop click dismiss. Slash command refactor (slash-command.tsx): - New createWorkspaceMention(searchFn) replaces the old file-only @ mention with unified search across files, objects, and entries. - searchItemToSlashItem() converts search index items into tiptap suggestion items with proper icons, badges (object name pill for entries), and link insertion commands using real workspace URLs. - Legacy createFileMention(tree) now delegates to createWorkspaceMention with a simple substring-match fallback for when no search index is available. Editor integration (markdown-editor.tsx, document-view.tsx): - MarkdownEditor accepts optional searchFn prop; when provided, uses createWorkspaceMention instead of the legacy createFileMention. - Link click interception now uses the shared isWorkspaceLink() helper and registers handlers in capture phase for reliable interception. - DocumentView forwards searchFn to editor and adds a delegated click handler in read mode to intercept workspace links and navigate via onNavigate. Object table (object-table.tsx): - Added onEntryClick prop; table rows are now clickable with cursor-pointer styling, firing the callback with the entry ID. Workspace page (page.tsx): - Integrates useSearchIndex hook and passes search function down to editor. - Entry detail modal state with URL synchronization (?entry=objName:id param). - New resolveNode() with fallback strategies: exact match, knowledge/ prefix toggle, and last-segment object name matching. - Unified handleEditorNavigate() dispatches /workspace?entry=... to the modal and /workspace?path=... to file/object navigation. - URL bar syncs with activePath via router.replace (no full page reloads). - Top-level container click safety net catches any workspace link clicks that bubble up unhandled. Styles (globals.css): - Added .slash-cmd-item-badge for object-name pills in the @ mention popup.
2026-02-11 21:41:23 -08:00
"use client";
import { useState, useEffect, useCallback, useRef, useMemo } from "react";
import Fuse from "fuse.js";
// --- Types (must match the API response) ---
export type SearchIndexItem = {
id: string;
label: string;
sublabel?: string;
kind: "file" | "object" | "entry";
icon?: string;
objectName?: string;
entryId?: string;
fields?: Record<string, string>;
path?: string;
nodeType?: "document" | "folder" | "file" | "report" | "database";
};
// --- Fuse.js config ---
const FUSE_OPTIONS: ConstructorParameters<typeof Fuse<SearchIndexItem>>[1] = {
keys: [
{ name: "label", weight: 3 },
{ name: "sublabel", weight: 1 },
{ name: "objectName", weight: 1.5 },
// Search within field values for entries
{ name: "fieldValues", weight: 2 },
],
threshold: 0.4,
distance: 200,
includeScore: true,
shouldSort: true,
minMatchCharLength: 1,
};
/** Flatten field values into a searchable string for Fuse.js. */
function enrichForSearch(
items: SearchIndexItem[],
): Array<SearchIndexItem & { fieldValues?: string }> {
return items.map((item) => ({
...item,
fieldValues: item.fields
? Object.values(item.fields).join(" ")
: undefined,
}));
}
// --- Hook ---
/**
* Hook that fetches the workspace search index and provides fuzzy search.
* Refetches when `refreshSignal` changes (wire to tree watcher refresh count).
*/
export function useSearchIndex(refreshSignal?: number) {
const [items, setItems] = useState<SearchIndexItem[]>([]);
const [loading, setLoading] = useState(true);
const mountedRef = useRef(true);
const fetchIndex = useCallback(async () => {
try {
const res = await fetch("/api/workspace/search-index");
const data = await res.json();
if (mountedRef.current) {
setItems(data.items ?? []);
setLoading(false);
}
} catch {
if (mountedRef.current) {setLoading(false);}
}
}, []);
useEffect(() => {
mountedRef.current = true;
void fetchIndex();
Dench workspace: unified @ mention search, entry detail modal, and workspace link system New libraries: - workspace-links.ts: builders, parsers, and type guards for workspace URLs (/workspace?path=... for files/objects, /workspace?entry=objName:id for entries). Replaces ad-hoc relative-path links with real navigable URLs. - search-index.ts: useSearchIndex hook that fetches a unified search index from the API and provides Fuse.js-powered fuzzy search across files, objects, and database entries. Exposes a stable ref-based search function safe for capture in tiptap extensions. New API routes: - GET /api/workspace/search-index: builds a flat search index from the filesystem tree (knowledge/, reports/, top-level files) and all DuckDB object entries with display-field labels and preview fields. - GET /api/workspace/objects/[name]/entries/[id]: fetches a single entry with all field values, resolved relation labels, reverse relations (incoming links from other objects), and the effective display field. New component: - EntryDetailModal: slide-over modal for viewing an individual entry's fields, enum badges, user avatars, clickable relation chips (navigate to related entries), reverse relation sections, and timestamps. Supports Escape to close and backdrop click dismiss. Slash command refactor (slash-command.tsx): - New createWorkspaceMention(searchFn) replaces the old file-only @ mention with unified search across files, objects, and entries. - searchItemToSlashItem() converts search index items into tiptap suggestion items with proper icons, badges (object name pill for entries), and link insertion commands using real workspace URLs. - Legacy createFileMention(tree) now delegates to createWorkspaceMention with a simple substring-match fallback for when no search index is available. Editor integration (markdown-editor.tsx, document-view.tsx): - MarkdownEditor accepts optional searchFn prop; when provided, uses createWorkspaceMention instead of the legacy createFileMention. - Link click interception now uses the shared isWorkspaceLink() helper and registers handlers in capture phase for reliable interception. - DocumentView forwards searchFn to editor and adds a delegated click handler in read mode to intercept workspace links and navigate via onNavigate. Object table (object-table.tsx): - Added onEntryClick prop; table rows are now clickable with cursor-pointer styling, firing the callback with the entry ID. Workspace page (page.tsx): - Integrates useSearchIndex hook and passes search function down to editor. - Entry detail modal state with URL synchronization (?entry=objName:id param). - New resolveNode() with fallback strategies: exact match, knowledge/ prefix toggle, and last-segment object name matching. - Unified handleEditorNavigate() dispatches /workspace?entry=... to the modal and /workspace?path=... to file/object navigation. - URL bar syncs with activePath via router.replace (no full page reloads). - Top-level container click safety net catches any workspace link clicks that bubble up unhandled. Styles (globals.css): - Added .slash-cmd-item-badge for object-name pills in the @ mention popup.
2026-02-11 21:41:23 -08:00
return () => {
mountedRef.current = false;
};
}, [fetchIndex, refreshSignal]);
// Build the Fuse instance whenever items change
const fuse = useMemo(() => {
if (items.length === 0) {return null;}
const enriched = enrichForSearch(items);
return new Fuse(enriched, FUSE_OPTIONS);
}, [items]);
/** Inner search implementation (recreated when fuse/items change). */
const searchImpl = useCallback(
(query: string, limit = 20): SearchIndexItem[] => {
if (!query.trim()) {
// No query: return first N items, files/objects first, then entries
const sorted = [...items].toSorted((a, b) => {
const kindOrder = { object: 0, file: 1, entry: 2 };
return (kindOrder[a.kind] ?? 9) - (kindOrder[b.kind] ?? 9);
});
return sorted.slice(0, limit);
}
if (!fuse) {return [];}
const results = fuse.search(query, { limit });
return results.map((r) => r.item);
},
[fuse, items],
);
// Keep a ref to the latest implementation so the tiptap extension
// (which captures the search function at creation time) always calls
// the current version, not a stale closure.
const searchImplRef = useRef(searchImpl);
searchImplRef.current = searchImpl;
/**
* Stable search function -- identity never changes, but always delegates
* to the latest searchImpl via ref. Safe to capture in closures/extensions.
*/
const search = useCallback(
(query: string, limit?: number): SearchIndexItem[] => {
return searchImplRef.current(query, limit);
},
[],
);
return { items, loading, search };
}