import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { Search, FileCode2, Box, Code2, BookOpen, Network, CornerDownLeft, ArrowUp, ArrowDown, Command, SearchX, Compass, } from 'lucide-react'; import { fuzzyMatchBest } from '../../lib/fuzzy'; export interface CommandItem { id: string; label: string; sublabel?: string; group: string; icon: React.ComponentType<{ className?: string }>; /** Extra text folded into the search corpus but never displayed */ keywords?: string; run: () => void; } interface RepoCommandPaletteProps { open: boolean; onClose: () => void; items: CommandItem[]; /** Shown as the palette's context line, e.g. "owner/repo" */ scopeLabel?: string; } /** Caps keep very large repositories responsive. */ const MAX_PER_GROUP = 8; const MAX_TOTAL = 50; /** Renders a label with fuzzy-matched characters emphasised. */ const Highlight: React.FC<{ text: string; positions: number[] }> = ({ text, positions }) => { if (positions.length === 0) return <>{text}>; const set = new Set(positions); const parts: React.ReactNode[] = []; let buffer = ''; let bufferMatched = set.has(0); const flush = (key: number) => { if (!buffer) return; parts.push( bufferMatched ? {buffer} : {buffer}, ); buffer = ''; }; for (let i = 0; i < text.length; i++) { const matched = set.has(i); if (matched !== bufferMatched) { flush(i); bufferMatched = matched; } buffer += text[i]; } flush(text.length); return <>{parts}>; }; export const RepoCommandPalette: React.FC = ({ open, onClose, items, scopeLabel, }) => { const [query, setQuery] = useState(''); const [activeIndex, setActiveIndex] = useState(0); const inputRef = useRef(null); const listRef = useRef(null); const restoreFocusRef = useRef(null); /** Ranked, capped, and grouped results. */ const results = useMemo(() => { const trimmed = query.trim(); const scored = items .map((item) => { if (!trimmed) return { item, score: 0, positions: [] as number[] }; const match = fuzzyMatchBest( [ { text: item.label, weight: 1 }, { text: item.sublabel ?? '', weight: 0.6 }, { text: item.keywords ?? '', weight: 0.35 }, ], trimmed, ); if (!match) return null; // Only highlight when the hit was on the visible label. return { item, score: match.score, positions: match.fieldIndex === 0 ? match.positions : [], }; }) .filter((entry): entry is { item: CommandItem; score: number; positions: number[] } => entry !== null); if (trimmed) scored.sort((a, b) => b.score - a.score); // Group while respecting per-group and overall caps. const groups: { name: string; entries: typeof scored }[] = []; const counts = new Map(); let total = 0; for (const entry of scored) { if (total >= MAX_TOTAL) break; const groupName = entry.item.group; const used = counts.get(groupName) ?? 0; if (used >= MAX_PER_GROUP) continue; counts.set(groupName, used + 1); total++; let group = groups.find((g) => g.name === groupName); if (!group) { group = { name: groupName, entries: [] }; groups.push(group); } group.entries.push(entry); } const flat = groups.flatMap((g) => g.entries); return { groups, flat }; }, [items, query]); // Reset transient state each time the palette opens. useEffect(() => { if (!open) return; restoreFocusRef.current = document.activeElement as HTMLElement | null; setQuery(''); setActiveIndex(0); const previousOverflow = document.body.style.overflow; document.body.style.overflow = 'hidden'; // Defer so the input exists before we focus it. const raf = requestAnimationFrame(() => inputRef.current?.focus()); return () => { cancelAnimationFrame(raf); document.body.style.overflow = previousOverflow; restoreFocusRef.current?.focus?.(); }; }, [open]); // Keep the highlighted row in view and within bounds. useEffect(() => { if (activeIndex >= results.flat.length) setActiveIndex(0); }, [results.flat.length, activeIndex]); useEffect(() => { const active = listRef.current?.querySelector('[data-active="true"]'); active?.scrollIntoView({ block: 'nearest' }); }, [activeIndex, query]); const runActive = useCallback(() => { const entry = results.flat[activeIndex]; if (!entry) return; onClose(); entry.item.run(); }, [results.flat, activeIndex, onClose]); const handleKeyDown = (event: React.KeyboardEvent) => { const count = results.flat.length; switch (event.key) { case 'Escape': event.preventDefault(); onClose(); break; case 'ArrowDown': event.preventDefault(); if (count) setActiveIndex((i) => (i + 1) % count); break; case 'ArrowUp': event.preventDefault(); if (count) setActiveIndex((i) => (i - 1 + count) % count); break; case 'Home': event.preventDefault(); setActiveIndex(0); break; case 'End': event.preventDefault(); if (count) setActiveIndex(count - 1); break; case 'Enter': event.preventDefault(); runActive(); break; case 'Tab': // Nothing else is focusable inside; keep focus in the palette. event.preventDefault(); break; default: break; } }; if (!open || typeof document === 'undefined') return null; let flatIndex = -1; return createPortal( {/* Backdrop */} {/* Panel */} {/* Search row */} { setQuery(event.target.value); setActiveIndex(0); }} placeholder="Search files, dependencies, and destinations…" className="flex-grow bg-transparent border-0 outline-none text-sm font-sans text-text placeholder:text-text-subtle min-w-0" /> {scopeLabel && ( {scopeLabel} )} {/* Results */} {results.flat.length === 0 ? ( No matches for "{query}" Try a file name, a package, or a destination like "reading path" or "health". ) : ( results.groups.map((group) => ( {group.name} {group.entries.map(({ item, positions }) => { flatIndex++; const isActive = flatIndex === activeIndex; const rowIndex = flatIndex; const Icon = item.icon; return ( setActiveIndex(rowIndex)} onClick={() => { onClose(); item.run(); }} className={`mx-2 px-2.5 py-2 rounded-lg flex items-center gap-3 cursor-pointer transition-colors duration-100 ${ isActive ? 'bg-primary/10 border border-primary/30' : 'border border-transparent' }`} > {item.sublabel && ( {item.sublabel} )} {isActive && ( )} ); })} )) )} {/* Footer hints */} navigate open esc close {results.flat.length} {results.flat.length === 1 ? 'result' : 'results'} , document.body, ); }; /** Icon set exported so callers build items without importing lucide directly. */ export const COMMAND_ICONS = { file: FileCode2, dependency: Box, tech: Code2, reading: BookOpen, component: Network, navigate: Compass, command: Command, } as const; export default RepoCommandPalette;
No matches for "{query}"
Try a file name, a package, or a destination like "reading path" or "health".