File size: 7,952 Bytes
4545bb3
 
 
33ce28f
 
a289b2a
 
bcc4b86
33ce28f
 
4545bb3
33ce28f
 
f56442a
144145d
a289b2a
 
 
 
 
 
 
 
 
 
 
 
 
33ce28f
 
 
 
 
 
 
 
 
 
 
 
 
4545bb3
 
33ce28f
 
 
4545bb3
 
33ce28f
 
 
 
4545bb3
33ce28f
 
 
 
f9c7101
33ce28f
a289b2a
f9c7101
 
144145d
f9c7101
a289b2a
f9c7101
33ce28f
bcc4b86
33ce28f
 
 
 
 
 
f9c7101
33ce28f
 
 
 
 
 
 
f9c7101
 
33ce28f
f9c7101
33ce28f
 
 
 
 
 
 
 
 
 
 
 
f9c7101
 
 
33ce28f
f9c7101
33ce28f
144145d
33ce28f
 
f9c7101
a289b2a
 
f9c7101
bcc4b86
f56442a
 
 
 
 
 
 
 
 
 
 
 
144145d
 
f9c7101
33ce28f
 
f9c7101
 
144145d
 
33ce28f
 
4545bb3
144145d
33ce28f
 
 
a289b2a
f9c7101
a289b2a
 
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
import { envKind, useChosenEnv } from './shell/EnvSwitcher';
import { Center, Drawer, Loader } from '@mantine/core';
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Outlet, useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { useHealth, useKill, useRuns, useSavedState } from '../api/hooks';
import { useAuth } from '../auth/AuthContext';
import { desktop, statusTransitions } from '../desktop';
import { useAsk } from '../chat/useAsk';
import { StartRunSheet } from '../pages/StartRunWizard';
import { CommandPalette } from './CommandPalette';
import { ScreenErrorBoundary } from './ErrorPages';
import { KeyboardSheet } from './KeyboardSheet';
import { AppSidebar } from './shell/AppSidebar';
import { IconRail } from './shell/IconRail';
import { ShellCtx, UiPrefsProvider, useShellSize, useUiPrefs, type ShellState } from './shell/prefs';

function DesktopNotifier() {
  const runs = useRuns(30, 0);
  const prev = useRef<Record<string, string> | null>(null);
  useEffect(() => {
    if (!runs.data) return;
    const next = Object.fromEntries(runs.data.items.map((r) => [r.run_id, r.attention ? `${r.status}|${r.attention}` : r.status]));
    if (prev.current) for (const n of statusTransitions(prev.current, next)) desktop()?.notify(n.title, n.body);
    prev.current = next;
  }, [runs.data]);
  return null;
}

/** Shown only when saving to backup storage has stopped: the person must know before a restart can lose their work. */
function SavedStateNotice() {
  const s = useSavedState().data;
  if (!s || !s.on || (s.ok !== false && !s.paused)) return null;
  return (
    <div className="fpt-savednotice" role="alert" data-testid="saved-state-notice">

      {s.paused

        ? 'Saving is paused: this instance could not read its saved data when it started, so it will not overwrite it. Restart the Space to try again; nothing you do now is saved.'

        : 'The latest changes could not be saved to backup storage. They will be lost if the app restarts before this clears.'}

    </div>
  );
}

/** Banners that belong to the whole app: the emergency stop, and the practice app not answering (only when the practice

 * app is the chosen or default test environment: it says nothing about an Oracle Fusion pod). */
function GlobalBanners() {
  const kill = useKill();
  const health = useHealth();
  const env = useChosenEnv().pod;
  const down = !!health.data && !health.data.mock_up && !!env && envKind(env.kind) === 'mock';
  if (!kill.data?.engaged && !down) return null;
  return (
    <div className="trio-globalbanners">

      {kill.data?.engaged && <div className="trio-banner" data-tone="red" role="status"><b>Emergency stop is on.</b> New test runs are refused until an administrator releases it.</div>}

      {down && <div className="trio-banner" data-tone="orange" role="status"><b>The practice app is not answering.</b> Test runs on the practice app cannot start until it is back.</div>}

    </div>
  );
}

const typing = (el: EventTarget | null) => el instanceof HTMLElement && (el.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName));
const GO: Record<string, string> = { h: '/', r: '/runs', s: '/scenarios', d: '/tickets', e: '/pods', p: '/reports' };

function Shell() {
  const { can } = useAuth();
  const { prefs, set } = useUiPrefs();
  const size = useShellSize();
  const loc = useLocation();
  const nav = useNavigate();
  const [, setParams] = useSearchParams();
  const chat = useAsk();
  const [drawer, setDrawer] = useState(false);       // tablet / phone: the menu as a drawer
  const [palette, setPalette] = useState(false);
  const [keys, setKeys] = useState(false);
  useEffect(() => { setDrawer(false); }, [loc.pathname, loc.search]);
  const inline = size === 'desktop' || size === 'laptop';
  useEffect(() => { if (inline) setDrawer(false); }, [inline]);

  const toggleSidebar = useCallback(() => set({ sidebar: prefs.sidebar === 'expanded' ? 'rail' : 'expanded' }), [prefs.sidebar, set]);
  const newRun = useCallback((area?: string) => {
    setParams((p) => { const n = new URLSearchParams(p); n.set('new', '1'); if (area) n.set('area', area); return n; });
  }, [setParams]);

  // single-key shortcuts work when focus is not in a field and no sheet is open; Ctrl or Command + K works anywhere
  const pending = useRef<number | null>(null);   // "g" was pressed: the next letter goes somewhere
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && !e.altKey && e.key.toLowerCase() === 'k') { e.preventDefault(); setPalette((v) => !v); return; }
      if (e.ctrlKey || e.metaKey || e.altKey || typing(e.target) || document.querySelector('[role="dialog"]')) return;
      const k = e.key;
      if (pending.current) {
        window.clearTimeout(pending.current); pending.current = null;
        const to = GO[k.toLowerCase()];
        if (to) { e.preventDefault(); nav(to); }
        return;
      }
      if (k === 'g' || k === 'G') { pending.current = window.setTimeout(() => { pending.current = null; }, 1200); return; }
      if (k === '/') { e.preventDefault(); setPalette(true); }
      else if (k === '?') { e.preventDefault(); setKeys(true); }
      else if (k === '[') { e.preventDefault(); toggleSidebar(); }
      else if ((k === 'n' || k === 'N') && can('run.start')) { e.preventDefault(); newRun(); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [can, nav, newRun, toggleSidebar]);

  const sidebarOpen = inline && prefs.sidebar === 'expanded';
  const shell: ShellState = useMemo(() => ({
    size, sidebarExpanded: inline ? sidebarOpen : drawer, toggleSidebar, openNav: () => setDrawer(true), openPalette: () => setPalette(true), openShortcuts: () => setKeys(true), newRun, chat,
  }), [size, inline, sidebarOpen, drawer, toggleSidebar, newRun, chat]);
  const runRoute = /^\/(runs\/[^/]+|assistant)/.test(loc.pathname);

  return (
    <ShellCtx.Provider value={shell}>

      <div className="fpt-shell" data-size={size} data-sb={sidebarOpen ? 'open' : 'closed'}>

        {inline && (sidebarOpen

          ? (

            <aside className="fpt-sidebar" data-mode="open" aria-label="Main navigation">

              <AppSidebar />

            </aside>

          )

          // folded: the pages as icons, never nothing ([ or the toolbar button opens it again)

          : (

            <aside className="pw-rail-aside" aria-label="Main navigation">

              <IconRail />

            </aside>

          ))}

        {!inline && (

          <Drawer opened={drawer} onClose={() => setDrawer(false)} position="left" size={size === 'phone' ? 'min(300px, 86vw)' : 288} withCloseButton={false} padding={0}

            title={<span className="fpt-sr-only">Main navigation</span>}

            styles={{ header: { padding: 0, minHeight: 0 }, body: { height: '100%', padding: 0 }, content: { background: 'var(--mat-sidebar-solid)', borderRadius: 0 } }}>

            <AppSidebar onNavigate={() => setDrawer(false)} />

          </Drawer>

        )}

        <main className="fpt-main" data-reading={!runRoute || undefined}>

          {desktop() && <DesktopNotifier />}

          <SavedStateNotice />

          <GlobalBanners />

          <ScreenErrorBoundary resetKey={loc.pathname}><Suspense fallback={<Center py={80}><Loader aria-label="Loading the page" /></Center>}><Outlet /></Suspense></ScreenErrorBoundary>

        </main>

        <StartRunSheet />

        <CommandPalette opened={palette} onClose={() => setPalette(false)} />

        <KeyboardSheet opened={keys} onClose={() => setKeys(false)} />

      </div>

    </ShellCtx.Provider>
  );
}

export function Layout() {
  return <UiPrefsProvider><Shell /></UiPrefsProvider>;
}