File size: 8,111 Bytes
af1bee9
 
 
 
fb43301
af1bee9
 
 
 
fb43301
 
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import { Modal, useMantineColorScheme } from '@mantine/core';
import {
  IconBug, IconCalendarTime, IconFileReport, IconHistory, IconHome, IconKeyboard, IconListCheck, IconMessageCircle, IconMoon, IconPlayerPlay, IconPlus,
  IconSearch, IconServer, IconSettings, IconSun, IconUserCheck,
} from '@/components/icons';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { useRuns } from '../api/hooks';
import { useAuth } from '../auth/AuthContext';
import { runAreas, runTitle } from '../domain/runName';
import { useWaitsOnMe } from '../domain/waiting';
import { isMac } from './shell/TopBar';
import { useShell } from './shell/prefs';

interface Item { id: string; group: string; label: string; hint?: string; keywords?: string; icon: ReactNode; run: () => void }
const I = { size: 18, stroke: 1.7 };

/** The command palette (Ctrl or Command + K, or the search field): waiting items, go to, test runs, actions, and Ask.

 * It only navigates or opens something; nothing changes until the person confirms on the screen it opens. */
export function CommandPalette({ opened, onClose }: { opened: boolean; onClose: () => void }) {
  const nav = useNavigate();
  const { can } = useAuth();
  const mine = useWaitsOnMe();
  const { chat, newRun, openShortcuts } = useShell();
  const { colorScheme, setColorScheme } = useMantineColorScheme();
  const runs = useRuns(40, 0);
  const [q, setQ] = useState('');
  const [sel, setSel] = useState(0);
  const input = useRef<HTMLInputElement>(null);
  useEffect(() => { if (opened) { setQ(''); setSel(0); } }, [opened]);

  const items = useMemo<Item[]>(() => {
    const go = (to: string) => () => { onClose(); nav(to); };
    const all = runs.data?.items ?? [];
    const waiting = all.filter(mine);
    const out: Item[] = [];
    for (const r of waiting) {
      out.push({
        id: `w-${r.run_id}`, group: 'Waiting for you', icon: <IconUserCheck {...I} />, keywords: `${runTitle(r)} approve decide review`,
        label: r.pending_gate === 'human_review' ? `Decide the failures in ${runAreas(r)}` : `Approve the scenarios for ${runAreas(r)}`, run: go(`/runs/${r.run_id}`),
      });
    }
    out.push(
      { id: 'g-home', group: 'Go to', label: 'Home', hint: 'G H', keywords: 'patch readiness', icon: <IconHome {...I} />, run: go('/') },
      { id: 'g-runs', group: 'Go to', label: 'Test runs', hint: 'G R', icon: <IconPlayerPlay {...I} />, run: go('/runs') },
      { id: 'g-scen', group: 'Go to', label: 'Scenarios', hint: 'G S', icon: <IconListCheck {...I} />, run: go('/scenarios') },
      { id: 'g-def', group: 'Go to', label: 'Defects', hint: 'G D', keywords: 'tickets bugs', icon: <IconBug {...I} />, run: go('/tickets') },
      { id: 'g-rep', group: 'Go to', label: 'Reports', hint: 'G P', keywords: 'sign off', icon: <IconFileReport {...I} />, run: go('/reports') },
      { id: 'g-env', group: 'Go to', label: 'Test environments', hint: 'G E', keywords: 'pods fusion practice', icon: <IconServer {...I} />, run: go('/pods') },
    );
    if (can('admin')) {
      out.push(
        { id: 'g-sch', group: 'Go to', label: 'Scheduled runs', keywords: 'schedule monthly quarterly', icon: <IconCalendarTime {...I} />, run: go('/schedules') },
        { id: 'g-set', group: 'Go to', label: 'Settings', keywords: 'ai models users automatic approval emergency stop kill switch', icon: <IconSettings {...I} />, run: go('/admin') },
        { id: 'g-aud', group: 'Go to', label: 'Audit log', keywords: 'verify chain', icon: <IconHistory {...I} />, run: go('/audit') },
      );
    }
    for (const r of all.slice(0, 40)) {
      out.push({ id: `r-${r.run_id}`, group: 'Test runs', label: runTitle(r), keywords: `${r.run_id} ${r.status}`, icon: <IconPlayerPlay {...I} />, run: go(`/runs/${r.run_id}`) });
    }
    if (can('run.start')) out.push({ id: 'a-new', group: 'Actions', label: 'New test run', hint: 'N', keywords: 'start', icon: <IconPlus {...I} />, run: () => { onClose(); newRun(); } });
    out.push(
      { id: 'a-theme', group: 'Actions', label: colorScheme === 'dark' ? 'Use the light appearance' : 'Use the dark appearance', keywords: 'theme dark light appearance',
        icon: colorScheme === 'dark' ? <IconSun {...I} /> : <IconMoon {...I} />, run: () => { setColorScheme(colorScheme === 'dark' ? 'light' : 'dark'); onClose(); } },
      { id: 'a-keys', group: 'Actions', label: 'Keyboard shortcuts', hint: '?', icon: <IconKeyboard {...I} />, run: () => { onClose(); openShortcuts(); } },
    );
    return out;
  }, [runs.data, can, mine, nav, onClose, newRun, openShortcuts, colorScheme, setColorScheme]);

  const needle = q.trim().toLowerCase();
  const shown = useMemo(() => {
    const words = needle.split(/\s+/).filter(Boolean);
    const hit = (it: Item) => words.every((w) => `${it.label} ${it.keywords ?? ''}`.toLowerCase().includes(w));
    let list = needle ? items.filter(hit) : items.filter((it) => it.group !== 'Test runs');
    list = list.slice(0, needle ? 12 : 14);
    if (chat) {
      list = [...list, { id: 'ask', group: 'Ask', label: needle ? `Ask: “${q.trim()}”` : 'Ask the co-worker a question', hint: 'Enter', icon: <IconMessageCircle {...I} />,
        run: () => { onClose(); chat.ask(needle ? q.trim() : undefined); } }];
    }
    return list;
  }, [items, needle, q, chat, onClose]);
  useEffect(() => setSel(0), [needle]);

  const groups: string[] = [];
  for (const it of shown) if (!groups.includes(it.group)) groups.push(it.group);
  const flat = groups.flatMap((g) => shown.filter((it) => it.group === g));
  const onKey = (e: React.KeyboardEvent) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setSel((s) => Math.min(flat.length - 1, s + 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setSel((s) => Math.max(0, s - 1)); }
    else if (e.key === 'Enter') { e.preventDefault(); flat[sel]?.run(); }
  };
  useEffect(() => { document.getElementById(`pal-${sel}`)?.scrollIntoView?.({ block: 'nearest' }); }, [sel]);

  return (
    <Modal opened={opened} onClose={onClose} withCloseButton={false} padding={0} size={640} radius="var(--r-xl)" yOffset="11vh" classNames={{ content: 'trio-palette', body: 'trio-palette-body', header: 'fpt-sr-only' }}

      trapFocus returnFocus transitionProps={{ transition: 'pop', duration: 200 }} title="Command palette">

      <div data-testid="palette" onKeyDown={onKey}>

        <div className="trio-pin">

          <IconSearch size={20} stroke={1.7} aria-hidden />

          <input ref={input} autoFocus value={q} onChange={(e) => setQ(e.currentTarget.value)} placeholder="Search, go to a page, or ask a question" aria-label="Search or ask"

            role="combobox" aria-expanded aria-controls="pal-list" aria-activedescendant={flat[sel] ? `pal-${sel}` : undefined} autoComplete="off" spellCheck={false} />

          <kbd className="fpt-kbd">Esc</kbd>

        </div>

        <div className="trio-pl" id="pal-list" role="listbox" aria-label="Results">

          {!flat.length && <div className="trio-pe">Nothing matches.</div>}

          {groups.map((g) => (

            <div key={g} role="group" aria-label={g}>

              <h6>{g}</h6>

              {shown.filter((it) => it.group === g).map((it) => {

                const idx = flat.indexOf(it);

                return (

                  <div key={it.id} id={`pal-${idx}`} role="option" aria-selected={idx === sel} className="trio-pit" onMouseMove={() => setSel(idx)} onClick={it.run}>

                    {it.icon}<span className="trio-pit-label">{it.label}</span>{it.hint && <span className="trio-pit-k">{it.hint}</span>}

                  </div>

                );

              })}

            </div>

          ))}

        </div>

        <div className="trio-pf"><span>Up and Down to move</span><span>Enter to open</span><span>Nothing changes until you confirm.</span><span className="trio-pf-sp" />{isMac() ? '⌘K' : 'Ctrl K'}</div>

      </div>

    </Modal>
  );
}