import {sessionTitle} from '../lib/session-title'; import { tr } from '../lib/i18n'; import { bindingKeys, useBindings } from '../lib/shortcut-bindings'; /** ⌘K palette — jump to a screen or run an engine action. */ import { useEffect, useMemo, useRef, useState } from 'react'; import { useSurfaceFocus } from '../lib/focus'; import { cx } from '../lib/format'; import { go, selectSession, setActiveWorkspace, setPalette, useStore } from '../lib/store'; import { highlight, parseScope, rank } from '../lib/fuzzy'; import { Icon, type IconName } from '../components/ui'; import { getCommands, runCommand, MOD } from '../lib/commands'; interface Command { id: string; label: string; hint?: string; icon: IconName; /** Marks an action that changes or removes something, so it is not mistaken * for navigation. */ danger?: boolean; /** The keyboard binding, shown so the palette teaches the shortcut. */ keys?: string[]; /** Which scope this belongs to; `>` narrows to commands. */ scope: 'command' | 'session' | 'workspace'; /** Extra words that should find this entry. The label stays human; aliases * cover what people actually type. */ keywords?: string; group: 'Go to' | 'Session' | 'Engine' | 'Model' | 'Navigation' | 'Chat'; run: () => void; } export function CommandPalette({ open }: { open: boolean; }) { const bindings = useBindings(); const language = useStore(s => s.language); const [query, setQuery] = useState(''); const [cursor, setCursor] = useState(0); const inputRef = useRef(null); const library = useStore((s) => s.library); const theme = useStore((s) => s.theme); const loaded = library?.loaded ?? null; // Focus and query reset follow the open state now that the palette stays // mounted (so closing can animate rather than unmount mid-flight). // Focus, trapping and restoring are shared with every other overlay; see // src/lib/focus.ts for why a plain focus() call here did not work. const modalRef = useRef(null); useSurfaceFocus(open, modalRef, inputRef); useEffect(() => { if (!open) { setQuery(''); setCursor(0); } }, [open]); const activeId = useStore(s => s.activeSession); const sessionList = useStore(s => s.sessions); const commands = useMemo(() => getCommands() .filter(c => c.palette !== false && (!c.available || c.available())) .map(c => ({ ...c, label: tr(c.label), hint: tr(c.hint), scope: 'command', keys: c.binding ? bindingKeys(c.binding, MOD) : undefined, run: () => runCommand(c) })), [library, theme, loaded, activeId, sessionList, bindings, language]); const sessions = useStore((s) => s.sessions); const workspaces = useStore((s) => s.workspaces); // Conversations and workspaces are reachable from here so the palette is a // real launcher rather than a screen switcher. const extras = useMemo(() => { const rows: Command[] = sessions.map((sess) => ({ id: `session:${sess.id}`, label: sessionTitle(sess), icon: 'chat', group: 'Go to', scope: 'session', run: () => { selectSession(sess.id); go('chat', sess.id); }, })); for (const w of workspaces) { rows.push({ id: `workspace:${w.id}`, label: w.name, hint: w.path, icon: 'folder', group: 'Go to', scope: 'workspace', run: () => { setActiveWorkspace(w.id); go('chat'); }, }); } return rows; }, [sessions, workspaces, language]); const all = useMemo(() => [...commands, ...extras], [commands, extras]); /** Ranked, scoped and explained: the match indices drive the highlighting. */ const filtered = useMemo(() => { const { scope, term } = parseScope(query); const pool = !query.trim() ? [...commands.filter(c => ['new', 'go:models', 'go:monitor', 'go:tasks'].includes(c.id)), ...extras.filter(c => c.scope === 'session').slice(0, 4)] : scope === 'all' ? all : all.filter((c) => c.scope === scope); return rank(term, pool, (c) => [c.label, c.keywords ?? '', c.hint ?? '']).map(({ item, indices }) => ({ ...item, indices, })); }, [all, query, commands, extras]); useEffect(() => { setCursor(0); }, [query]); const grouped = useMemo(() => { const map = new Map(); for (const c of filtered) { const arr = map.get(c.group) ?? []; arr.push(c); map.set(c.group, arr); } return [...map.entries()]; }, [filtered]); const flat = grouped.flatMap(([, items]) => items); const onKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'ArrowDown') { e.preventDefault(); setCursor((c) => Math.min(flat.length - 1, c + 1)); } else if (e.key === 'ArrowUp') { e.preventDefault(); setCursor((c) => Math.max(0, c - 1)); } else if (e.key === 'Enter') { e.preventDefault(); setPalette(false); flat[cursor]?.run(); } }; let index = -1; return (<>
setPalette(false)} aria-hidden="true"/>
setQuery(e.target.value)} onKeyDown={onKeyDown}/> {tr("esc")}
{tr(flat.length === 0 ? (
{tr("Nothing matches “{0}”. Try > for commands, # for conversations, or @ for workspaces.", [query])}
) : (grouped.map(([group, items]) => (
{tr(group)}
{tr(items.map((c) => { index += 1; const active = index === cursor; const i = index; return (); }))}
))))}
Enter{tr("Open")} esc{tr("Close")}
); }