okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge tui-update (3165c2e8a)a1cc285fa

main
8.4 KiB177 linesraw
1import {sessionTitle} from '../lib/session-title';
2import { tr } from '../lib/i18n';
3import { bindingKeys, useBindings } from '../lib/shortcut-bindings';
4/** ⌘K palette — jump to a screen or run an engine action. */
5import { useEffect, useMemo, useRef, useState } from 'react';
6import { useSurfaceFocus } from '../lib/focus';
7import { cx } from '../lib/format';
8import { go, selectSession, setActiveWorkspace, setPalette, useStore } from '../lib/store';
9import { highlight, parseScope, rank } from '../lib/fuzzy';
10import { Icon, type IconName } from '../components/ui';
11import { getCommands, runCommand, MOD } from '../lib/commands';
12interface Command {
13    id: string;
14    label: string;
15    hint?: string;
16    icon: IconName;
17    /** Marks an action that changes or removes something, so it is not mistaken
18     *  for navigation. */
19    danger?: boolean;
20    /** The keyboard binding, shown so the palette teaches the shortcut. */
21    keys?: string[];
22    /** Which scope this belongs to; `>` narrows to commands. */
23    scope: 'command' | 'session' | 'workspace';
24    /** Extra words that should find this entry. The label stays human; aliases
25     *  cover what people actually type. */
26    keywords?: string;
27    group: 'Go to' | 'Session' | 'Engine' | 'Model' | 'Navigation' | 'Chat';
28    run: () => void;
29}
30export function CommandPalette({ open }: {
31    open: boolean;
32}) {
33    const bindings = useBindings();
34    const language = useStore(s => s.language);
35    const [query, setQuery] = useState('');
36    const [cursor, setCursor] = useState(0);
37    const inputRef = useRef<HTMLInputElement>(null);
38    const library = useStore((s) => s.library);
39    const theme = useStore((s) => s.theme);
40    const loaded = library?.loaded ?? null;
41    // Focus and query reset follow the open state now that the palette stays
42    // mounted (so closing can animate rather than unmount mid-flight).
43    // Focus, trapping and restoring are shared with every other overlay; see
44    // src/lib/focus.ts for why a plain focus() call here did not work.
45    const modalRef = useRef<HTMLDivElement>(null);
46    useSurfaceFocus(open, modalRef, inputRef);
47    useEffect(() => {
48        if (!open) {
49            setQuery('');
50            setCursor(0);
51        }
52    }, [open]);
53    const activeId = useStore(s => s.activeSession);
54    const sessionList = useStore(s => s.sessions);
55    const commands = useMemo<Command[]>(() => getCommands()
56        .filter(c => c.palette !== false && (!c.available || c.available()))
57        .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]);
58    const sessions = useStore((s) => s.sessions);
59    const workspaces = useStore((s) => s.workspaces);
60    // Conversations and workspaces are reachable from here so the palette is a
61    // real launcher rather than a screen switcher.
62    const extras = useMemo<Command[]>(() => {
63        const rows: Command[] = sessions.map((sess) => ({
64            id: `session:${sess.id}`,
65            label: sessionTitle(sess),
66            icon: 'chat',
67            group: 'Go to',
68            scope: 'session',
69            run: () => {
70                selectSession(sess.id);
71                go('chat', sess.id);
72            },
73        }));
74        for (const w of workspaces) {
75            rows.push({
76                id: `workspace:${w.id}`,
77                label: w.name,
78                hint: w.path,
79                icon: 'folder',
80                group: 'Go to',
81                scope: 'workspace',
82                run: () => {
83                    setActiveWorkspace(w.id);
84                    go('chat');
85                },
86            });
87        }
88        return rows;
89    }, [sessions, workspaces, language]);
90    const all = useMemo(() => [...commands, ...extras], [commands, extras]);
91    /** Ranked, scoped and explained: the match indices drive the highlighting. */
92    const filtered = useMemo(() => {
93        const { scope, term } = parseScope(query);
94        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);
95        return rank(term, pool, (c) => [c.label, c.keywords ?? '', c.hint ?? '']).map(({ item, indices }) => ({
96            ...item,
97            indices,
98        }));
99    }, [all, query, commands, extras]);
100    useEffect(() => {
101        setCursor(0);
102    }, [query]);
103    const grouped = useMemo(() => {
104        const map = new Map<string, (Command & {
105            indices: number[];
106        })[]>();
107        for (const c of filtered) {
108            const arr = map.get(c.group) ?? [];
109            arr.push(c);
110            map.set(c.group, arr);
111        }
112        return [...map.entries()];
113    }, [filtered]);
114    const flat = grouped.flatMap(([, items]) => items);
115    const onKeyDown = (e: React.KeyboardEvent) => {
116        if (e.key === 'ArrowDown') {
117            e.preventDefault();
118            setCursor((c) => Math.min(flat.length - 1, c + 1));
119        }
120        else if (e.key === 'ArrowUp') {
121            e.preventDefault();
122            setCursor((c) => Math.max(0, c - 1));
123        }
124        else if (e.key === 'Enter') {
125            e.preventDefault();
126            setPalette(false);
127            flat[cursor]?.run();
128        }
129    };
130    let index = -1;
131    return (<>
132      <div className="scrim" data-open={open} onClick={() => setPalette(false)} aria-hidden="true"/>
133      <div ref={modalRef} className="modal" data-open={open} role="dialog" aria-modal="true" aria-label={tr("Command palette")} inert={!open}>
134        <div className="modal__head">
135          <Icon name="chat" size={18} style={{ color: 'var(--st-ink-muted)' }}/>
136          <input ref={inputRef} className="st-input st-input--bare" style={{ flex: 1 }} placeholder={tr("Search chats, screens or actions…")} aria-label={tr("Search commands")} aria-activedescendant={flat[cursor] ? `command-${flat[cursor].id}` : undefined} value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={onKeyDown}/>
137          <kbd className="kbd">{tr("esc")}</kbd>
138        </div>
139        <div className="palette__list">
140          {tr(flat.length === 0 ? (<div className="small muted" style={{ padding: 18 }}>{tr("Nothing matches “{0}”. Try > for commands, # for conversations, or @ for workspaces.", [query])}</div>) : (grouped.map(([group, items]) => (<div key={group} style={{ marginBottom: 6 }}>
141                <div className="navgroup__label" style={{ padding: '8px 12px 4px' }}>
142                  {tr(group)}
143                </div>
144                {tr(items.map((c) => {
145                index += 1;
146                const active = index === cursor;
147                const i = index;
148                return (<button key={c.id} id={`command-${c.id}`} type="button" className={cx('navitem', 'palette__row')} data-danger={c.danger || undefined} aria-selected={active} style={{
149                        height: 42,
150                        background: active ? 'var(--st-surface-2)' : undefined,
151                        boxShadow: active ? 'inset 0 0 0 1px var(--st-line)' : undefined,
152                    }} onMouseEnter={() => setCursor(i)} onClick={() => {
153                        setPalette(false);
154                        c.run();
155                    }}>
156                      <Icon name={c.icon}/>
157                      <span className="navitem__text">
158                        {/* The matched characters are emphasised so a fuzzy hit
159                explains itself instead of looking like a mistake. */}
160                        {tr(highlight(c.label, c.indices).map((part, k) => part.hit ? (<mark key={k}>{part.text}</mark>) : (<span key={k}>{part.text}</span>)))}
161                      </span>
162                      {tr(c.hint ? <span className="navitem__meta">{c.hint}</span> : null)}
163                      {tr(c.keys?.length ? (<span className="palette__keys">
164                          {tr(c.keys.map((k) => (<kbd key={k}>{tr(k)}</kbd>)))}
165                        </span>) : null)}
166                    </button>);
167            }))}
168              </div>))))}
169        </div>
170        <div className="palette__foot">
171          <span className="palette__hint"><kbd className="kbd">Enter</kbd>{tr("Open")}</span>
172          <span className="spacer"/>
173          <span className="palette__hint"><kbd className="kbd">esc</kbd>{tr("Close")}</span>
174        </div>
175      </div>
176    </>);
177}