File size: 10,518 Bytes
25b02dd
33ce28f
144145d
33ce28f
ea39c17
144145d
33ce28f
 
f9c7101
33ce28f
f9c7101
144145d
25b02dd
 
4545bb3
 
f9c7101
 
f56442a
25b02dd
f9c7101
f56442a
33ce28f
 
bcc4b86
f9c7101
f56442a
33ce28f
 
 
 
f56442a
33ce28f
 
f56442a
 
144145d
f9c7101
33ce28f
f9c7101
 
8f175f6
f9c7101
33ce28f
f9c7101
 
33ce28f
 
 
 
f9c7101
 
 
 
 
 
25b02dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144145d
4545bb3
 
f9c7101
 
 
 
 
 
2effee4
f9c7101
 
 
25b02dd
 
33ce28f
 
 
f56442a
f9c7101
4545bb3
f9c7101
 
 
4545bb3
 
8f175f6
f9c7101
 
33ce28f
144145d
 
aa61ac1
 
33ce28f
144145d
33ce28f
144145d
25b02dd
33ce28f
 
 
 
 
ea39c17
33ce28f
144145d
25b02dd
f9c7101
144145d
 
25b02dd
 
 
 
 
 
33ce28f
 
144145d
4545bb3
 
33ce28f
f56442a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33ce28f
f56442a
33ce28f
f56442a
33ce28f
 
 
 
 
 
 
4545bb3
 
33ce28f
 
 
 
 
 
 
 
 
f9c7101
 
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import '../../shell.css';
import { Menu, Tooltip, useMantineColorScheme } from '@mantine/core';
import {
  IconAlertTriangle, IconBug, IconCheck, IconDeviceDesktop, IconFileReport, IconHandStop, IconHome, IconListCheck, IconLogout, IconMessageCircle, IconMoon,
  IconPlayerPlay, IconPlug, IconServer, IconSettings, IconSun,
} from '@tabler/icons-react';
import type { ReactNode } from 'react';
import { NavLink as RouterLink, useLocation } from 'react-router-dom';
import type { Schemas } from '../../api/client';
import { useBrand, useHealth, useKill, useRuns } from '../../api/hooks';
import { useAuth } from '../../auth/AuthContext';
import { desktop } from '../../desktop';
import { areaTone } from '../../agents';
import { runTitle } from '../../runName';
import { EnvSwitcher, envKind, useChosenEnv } from './EnvSwitcher';
import { isWaiting, useWaitsOnMe } from '../../waiting';

type RunSummary = Schemas['RunSummary'];
export interface NavItem { to: string; label: string; icon: ReactNode; match?: (p: string) => boolean; admin?: boolean }
const ICON = { size: 16, stroke: 1.7 };

export const MAIN: NavItem[] = [
  { to: '/', label: 'Home', icon: <IconHome {...ICON} />, match: (p) => p === '/' },
  { to: '/runs', label: 'Test runs', icon: <IconPlayerPlay {...ICON} />, match: (p) => p === '/runs' || p.startsWith('/runs/') || p === '/schedules' },
  { to: '/assistant', label: 'Ask', icon: <IconMessageCircle {...ICON} /> },
];
export const LIBRARY: NavItem[] = [
  { to: '/scenarios', label: 'Scenarios', icon: <IconListCheck {...ICON} /> },
  { to: '/tickets', label: 'Defects', icon: <IconBug {...ICON} /> },
  { to: '/reports', label: 'Reports', icon: <IconFileReport {...ICON} /> },
];
export const SETUP: NavItem[] = [
  { to: '/pods', label: 'Test environments', icon: <IconServer {...ICON} /> },
];
export const INTEGRATIONS: NavItem = { to: '/integrations', label: 'Integrations', icon: <IconPlug {...ICON} /> };
export const SETTINGS: NavItem = { to: '/admin', label: 'Settings', icon: <IconSettings {...ICON} />,
  match: (p) => ['/admin', '/agents', '/heal', '/scripts', '/learner', '/audit'].some((x) => p === x || p.startsWith(`${x}/`)) };

/** Where "New test run" links go: they open the Start sheet (`/runs/new` redirects there). */
export const NEW_RUN_PATH = '/runs/new';

export const initials = (name?: string) => (name ?? 'Patchwise').split(/\s+/).slice(0, 2).map((w) => w[0]?.toUpperCase() ?? '').join('') || 'TC';

function NavLink({ item, badge, onNavigate }: { item: NavItem; badge?: number; onNavigate?: () => void }) {
  const loc = useLocation();
  const active = item.match ? item.match(loc.pathname) : loc.pathname === item.to || loc.pathname.startsWith(`${item.to}/`);
  return (
    <RouterLink to={item.to} className="fpt-nav-item" data-active={active} aria-current={active ? 'page' : undefined} onClick={onNavigate}>

      {item.icon}<span className="fpt-nav-label">{item.label}</span>

      {!!badge && <span className="fpt-nav-badge" title={`${badge} waiting for you`}>{badge}<span className="fpt-sr-only">, waiting for you</span></span>}

    </RouterLink>
  );
}

type Group = { key: string; title: string; runs: RunSummary[] };


/** The latest test runs, newest first: a square in the area's colour and the run's readable name. */
function RecentRuns({ items, onNavigate }: { items: RunSummary[]; onNavigate?: () => void }) {
  const loc = useLocation();
  const latest = [...items].sort((a, b) => (a.created_at < b.created_at ? 1 : -1)).slice(0, 4);
  if (!latest.length) return null;
  return (
    <section className="pw-sb-recent" aria-labelledby="pw-sb-recent-h">

      <h6 id="pw-sb-recent-h">Recent test runs</h6>

      <ul>

        {latest.map((r) => {

          const to = `/runs/${r.run_id}`;

          const active = loc.pathname === to || loc.pathname.startsWith(`${to}/`);

          return (

            <li key={r.run_id}>

              <RouterLink to={to} className="pw-sb-recent-item" aria-current={active ? 'page' : undefined} onClick={onNavigate} title={runTitle(r)}>

                <span className="pw-icon-sq" data-tone={areaTone(r.modules[0])} aria-hidden />

                <span className="pw-sb-recent-label">{runTitle(r)}</span>

              </RouterLink>

            </li>

          );

        })}

      </ul>

    </section>
  );
}

/** Needs you (all of them) first, then Running, then Recent to fill up to `max` rows. */
export function groupRuns(items: RunSummary[], max = 12, mine: (r: RunSummary) => boolean = isWaiting): Group[] {
  const needs = items.filter(mine);
  const running = items.filter((r) => !needs.includes(r) && ['queued', 'running'].includes(r.status));
  const recent = items.filter((r) => !needs.includes(r) && !running.includes(r))
    .sort((a, b) => (a.created_at < b.created_at ? 1 : -1));
  let room = Math.max(0, max - needs.length);
  const run2 = running.slice(0, room); room -= run2.length;
  const rec2 = recent.slice(0, room);
  return [{ key: 'needs', title: 'Waiting for you', runs: needs }, { key: 'running', title: 'Running', runs: run2 }, { key: 'recent', title: 'Recent', runs: rec2 }]
    .filter((g) => g.runs.length);
}

const weekCount = (items: RunSummary[]) => items.filter((r) => Date.now() - new Date(r.created_at).getTime() < 7 * 86_400_000).length;

/** The sidebar: brand, the environment switcher (the honesty cue), one level of navigation with two small group labels,

 * the emergency-stop flag, and only the account row at the bottom. */
export function AppSidebar({ onNavigate }: { onNavigate?: () => void }) {
  const { can } = useAuth();
  const health = useHealth();
  const env = useChosenEnv().pod;
  const kill = useKill();
  const runs = useRuns(40, 0);
  const brand = useBrand();
  const mine = useWaitsOnMe();
  const waiting = (runs.data?.items ?? []).filter(mine).length;
  const name = brand.data?.product_name ?? 'Patchwise';

  return (
    <div className="fpt-sb">

      <div className="fpt-sb-top">

        <div className="fpt-sb-brand" data-testid="brand">

          <img className="trio-logo" data-for="light" src="/favicon-graphite.svg" alt="" width={30} height={30} />

          <img className="trio-logo" data-for="dark" src="/favicon-paper.svg" alt="" width={30} height={30} />

          <span className="fpt-sb-brand-name" title={name}><b className="fpt-sb-name">{name}</b>{brand.data?.org_name ? <small>{brand.data.org_name}</small> : null}</span>

        </div>

        <EnvSwitcher />

        <nav className="fpt-sb-nav" aria-label="Pages">

          <h6>Workspace</h6>

          {MAIN.map((it) => <NavLink key={it.to} item={it} onNavigate={onNavigate} badge={it.to === '/runs' ? waiting : undefined} />)}

          <h6>Library</h6>

          {LIBRARY.map((it) => <NavLink key={it.to} item={it} onNavigate={onNavigate} />)}

          <h6>Setup</h6>

          {SETUP.map((it) => <NavLink key={it.to} item={it} onNavigate={onNavigate} />)}

          {can('admin') && <NavLink item={INTEGRATIONS} onNavigate={onNavigate} />}

          {can('admin') && <NavLink item={SETTINGS} onNavigate={onNavigate} />}

        </nav>

        <RecentRuns items={runs.data?.items ?? []} onNavigate={onNavigate} />

      </div>



      <div className="fpt-sb-foot">

        {(runs.data?.items.length ?? 0) > 0 && (

          <div className="pw-sb-usage" data-testid="sb-usage">

            <b>{weekCount(runs.data?.items ?? [])} test {weekCount(runs.data?.items ?? []) === 1 ? 'run' : 'runs'}</b>

            <span>started in the last 7 days{waiting ? `, ${waiting} waiting for you` : ''}</span>

          </div>

        )}

        {kill.data?.engaged && (

          <div className="fpt-kill" data-testid="kill-indicator" role="status"><IconHandStop size={16} aria-hidden />Emergency stop is on</div>

        )}

        {health.data && !health.data.mock_up && envKind(env?.kind) === 'mock' && !!env && (

          <Tooltip label="The practice app is not answering"><div className="fpt-warnrow" aria-label="practice app down"><IconAlertTriangle size={16} aria-hidden />Practice app not answering</div></Tooltip>

        )}

        <AccountMenu />

      </div>

    </div>
  );
}

/** The account row's menu: your account, light or dark, sign out. `compact`: the avatar alone (the icon rail). */
export function AccountMenu({ compact = false }: { compact?: boolean }) {
  const { user, logout } = useAuth();
  const { colorScheme, setColorScheme } = useMantineColorScheme();
  const whoami = `${user?.username} (${user?.role})`;
  const scheme = [
    { v: 'auto', label: 'Match the system', aria: 'Match the system theme', icon: <IconDeviceDesktop size={15} /> },
    { v: 'light', label: 'Light', aria: 'Switch to light theme', icon: <IconSun size={15} /> },
    { v: 'dark', label: 'Dark', aria: 'Switch to dark theme', icon: <IconMoon size={15} /> },
  ] as const;
  return (
        <Menu position={compact ? 'right-end' : 'top-start'} width={248} withinPortal>

          <Menu.Target>

            <button type="button" className="fpt-me" data-compact={compact || undefined} aria-label={compact ? `Account: ${whoami}` : undefined}>

              <span className="fpt-avatar" aria-hidden>{initials(user?.username)}</span>

              <span className="fpt-me-text" hidden={compact}>

                <b aria-hidden>{user?.username}</b><small aria-hidden>{user?.role}</small>

                <span className="fpt-sr-only" data-testid="whoami">{whoami}</span>

              </span>

            </button>

          </Menu.Target>

          <Menu.Dropdown>

            <Menu.Label>{whoami}</Menu.Label>

            <Menu.Item component={RouterLink} to="/account" data-testid="menu-account">Your account</Menu.Item>

            <Menu.Divider />

            <Menu.Label>Appearance</Menu.Label>

            {scheme.map((s) => (

              <Menu.Item key={s.v} leftSection={s.icon} aria-label={s.aria} onClick={() => setColorScheme(s.v)} rightSection={colorScheme === s.v ? <IconCheck size={14} aria-label="chosen" /> : undefined}>{s.label}</Menu.Item>

            ))}

            <Menu.Divider />

            {desktop() && <Menu.Item onClick={() => desktop()?.openSettings()}>Desktop settings</Menu.Item>}

            <Menu.Item leftSection={<IconLogout size={15} />} aria-label="Sign out" onClick={() => void logout()}>Sign out</Menu.Item>

          </Menu.Dropdown>

        </Menu>
  );
}