Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

feat: add wiki search with full-text matching

nash_sua1072d0decdd
diff --git a/src/components/search/search-view.tsx b/src/components/search/search-view.tsx
new file mode 100644
index 00000000..bad7a2f8
--- /dev/null
+++ b/src/components/search/search-view.tsx
@@ -0,0 +1,162 @@
+import { useState, useEffect, useRef, useCallback } from "react"
+import { Search, FileText } from "lucide-react"
+import { ScrollArea } from "@/components/ui/scroll-area"
+import { useWikiStore } from "@/stores/wiki-store"
+import { readFile } from "@/commands/fs"
+import { searchWiki, type SearchResult } from "@/lib/search"
+
+export function SearchView() {
+ const project = useWikiStore((s) => s.project)
+ const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
+ const setFileContent = useWikiStore((s) => s.setFileContent)
+ const setActiveView = useWikiStore((s) => s.setActiveView)
+
+ const [query, setQuery] = useState("")
+ const [results, setResults] = useState<SearchResult[]>([])
+ const [searching, setSearching] = useState(false)
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+
+ const doSearch = useCallback(
+ async (q: string) => {
+ if (!project || !q.trim()) {
+ setResults([])
+ return
+ }
+ setSearching(true)
+ try {
+ const found = await searchWiki(project.path, q)
+ setResults(found)
+ } catch (err) {
+ console.error("Search failed:", err)
+ setResults([])
+ } finally {
+ setSearching(false)
+ }
+ },
+ [project],
+ )
+
+ useEffect(() => {
+ if (debounceRef.current) clearTimeout(debounceRef.current)
+ debounceRef.current = setTimeout(() => doSearch(query), 300)
+ return () => {
+ if (debounceRef.current) clearTimeout(debounceRef.current)
+ }
+ }, [query, doSearch])
+
+ async function handleOpen(result: SearchResult) {
+ try {
+ const content = await readFile(result.path)
+ setSelectedFile(result.path)
+ setFileContent(content)
+ setActiveView("wiki")
+ } catch (err) {
+ console.error("Failed to open search result:", err)
+ }
+ }
+
+ return (
+ <div className="flex h-full flex-col">
+ <div className="border-b px-4 py-3">
+ <div className="relative">
+ <Search className="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
+ <input
+ type="text"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search wiki..."
+ autoFocus
+ className="w-full rounded-md border bg-background py-2 pl-9 pr-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"
+ />
+ </div>
+ </div>
+
+ <ScrollArea className="flex-1">
+ {!query.trim() ? (
+ <div className="flex flex-col items-center justify-center gap-2 p-8 text-center text-sm text-muted-foreground">
+ <Search className="h-8 w-8 text-muted-foreground/30" />
+ <p>Type to search wiki pages</p>
+ </div>
+ ) : searching ? (
+ <div className="p-4 text-center text-sm text-muted-foreground">Searching...</div>
+ ) : results.length === 0 ? (
+ <div className="p-4 text-center text-sm text-muted-foreground">
+ No results for <span className="font-medium">"{query}"</span>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-1 p-2">
+ <div className="px-2 py-1 text-xs text-muted-foreground">
+ {results.length} result{results.length !== 1 ? "s" : ""}
+ </div>
+ {results.map((result) => (
+ <SearchResultCard
+ key={result.path}
+ result={result}
+ query={query}
+ onClick={() => handleOpen(result)}
+ />
+ ))}
+ </div>
+ )}
+ </ScrollArea>
+ </div>
+ )
+}
+
+function SearchResultCard({
+ result,
+ query,
+ onClick,
+}: {
+ result: SearchResult
+ query: string
+ onClick: () => void
+}) {
+ const shortPath = result.path.split("/wiki/").pop() ?? result.path
+
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="w-full rounded-lg border p-3 text-left text-sm hover:bg-accent transition-colors"
+ >
+ <div className="flex items-start gap-2 mb-1.5">
+ <FileText className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="flex-1 min-w-0">
+ <div className="font-medium truncate">
+ <HighlightedText text={result.title} query={query} />
+ </div>
+ <div className="text-[11px] text-muted-foreground truncate">{shortPath}</div>
+ </div>
+ </div>
+ <p className="text-xs text-muted-foreground line-clamp-2">
+ <HighlightedText text={result.snippet} query={query} />
+ </p>
+ </button>
+ )
+}
+
+function HighlightedText({ text, query }: { text: string; query: string }) {
+ if (!query.trim()) return <>{text}</>
+
+ const regex = new RegExp(`(${escapeRegex(query)})`, "gi")
+ const parts = text.split(regex)
+
+ return (
+ <>
+ {parts.map((part, i) =>
+ regex.test(part) ? (
+ <mark key={i} className="bg-yellow-200 dark:bg-yellow-800 rounded px-0.5">
+ {part}
+ </mark>
+ ) : (
+ <span key={i}>{part}</span>
+ )
+ )}
+ </>
+ )
+}
+
+function escapeRegex(str: string): string {
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
+}
diff --git a/src/lib/search.ts b/src/lib/search.ts
new file mode 100644
index 00000000..0fd836be
--- /dev/null
+++ b/src/lib/search.ts
@@ -0,0 +1,108 @@
+import { readFile, listDirectory } from "@/commands/fs"
+import type { FileNode } from "@/types/wiki"
+
+export interface SearchResult {
+ path: string
+ title: string
+ snippet: string
+ titleMatch: boolean
+}
+
+const MAX_RESULTS = 20
+const SNIPPET_CONTEXT = 80
+
+function flattenMdFiles(nodes: FileNode[]): FileNode[] {
+ const files: FileNode[] = []
+ for (const node of nodes) {
+ if (node.is_dir && node.children) {
+ files.push(...flattenMdFiles(node.children))
+ } else if (!node.is_dir && node.name.endsWith(".md")) {
+ files.push(node)
+ }
+ }
+ return files
+}
+
+function extractTitle(content: string, fileName: string): string {
+ // Try YAML frontmatter title
+ const frontmatterMatch = content.match(/^---\n[\s\S]*?^title:\s*["']?(.+?)["']?\s*$/m)
+ if (frontmatterMatch) return frontmatterMatch[1].trim()
+
+ // Try first heading
+ const headingMatch = content.match(/^#\s+(.+)$/m)
+ if (headingMatch) return headingMatch[1].trim()
+
+ // Fall back to filename
+ return fileName.replace(/\.md$/, "").replace(/-/g, " ")
+}
+
+function buildSnippet(content: string, query: string): string {
+ const lower = content.toLowerCase()
+ const lowerQuery = query.toLowerCase()
+ const idx = lower.indexOf(lowerQuery)
+ if (idx === -1) return content.slice(0, SNIPPET_CONTEXT * 2).replace(/\n/g, " ")
+
+ const start = Math.max(0, idx - SNIPPET_CONTEXT)
+ const end = Math.min(content.length, idx + query.length + SNIPPET_CONTEXT)
+ let snippet = content.slice(start, end).replace(/\n/g, " ")
+ if (start > 0) snippet = "..." + snippet
+ if (end < content.length) snippet = snippet + "..."
+ return snippet
+}
+
+export async function searchWiki(
+ projectPath: string,
+ query: string,
+): Promise<SearchResult[]> {
+ if (!query.trim()) return []
+
+ const wikiRoot = `${projectPath}/wiki`
+ let tree: FileNode[]
+ try {
+ tree = await listDirectory(wikiRoot)
+ } catch {
+ return []
+ }
+
+ const wikiFiles = flattenMdFiles(tree)
+ const lowerQuery = query.toLowerCase()
+
+ const titleMatches: SearchResult[] = []
+ const contentMatches: SearchResult[] = []
+
+ for (const file of wikiFiles) {
+ let content = ""
+ try {
+ content = await readFile(file.path)
+ } catch {
+ continue
+ }
+
+ const title = extractTitle(content, file.name)
+ const titleLower = title.toLowerCase()
+ const fileNameLower = file.name.toLowerCase()
+ const contentLower = content.toLowerCase()
+
+ const matchesTitle =
+ titleLower.includes(lowerQuery) || fileNameLower.includes(lowerQuery)
+ const matchesContent = contentLower.includes(lowerQuery)
+
+ if (!matchesTitle && !matchesContent) continue
+
+ const snippet = buildSnippet(content, query)
+ const result: SearchResult = {
+ path: file.path,
+ title,
+ snippet,
+ titleMatch: matchesTitle,
+ }
+
+ if (matchesTitle) {
+ titleMatches.push(result)
+ } else {
+ contentMatches.push(result)
+ }
+ }
+
+ return [...titleMatches, ...contentMatches].slice(0, MAX_RESULTS)
+}