File size: 12,048 Bytes
f9c7101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a73107f
 
 
 
f9c7101
 
a73107f
 
 
f9c7101
 
 
 
 
 
 
 
 
a73107f
bcc4b86
f9c7101
 
 
 
 
 
a73107f
 
 
 
f9c7101
 
f56442a
f9c7101
 
a73107f
 
 
bcc4b86
f9c7101
 
 
 
 
 
 
a73107f
 
f9c7101
a73107f
f9c7101
bcc4b86
a73107f
 
bcc4b86
f9c7101
a73107f
f9c7101
 
 
 
 
 
 
a73107f
 
 
 
 
 
 
 
f9c7101
 
 
 
 
 
 
 
 
bcc4b86
 
f9c7101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ceab56c
 
f9c7101
 
 
ceab56c
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import { Drawer, Tabs, Tooltip } from '@mantine/core';
import { useViewportSize } from '@mantine/hooks';
import { IconBroadcast, IconFileReport, IconFileSpreadsheet, IconLayoutSidebarRightCollapse, IconListNumbers, IconPhoto, IconX } from '@tabler/icons-react';
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useShell, useUiPrefs, type PanelTab } from './prefs';

export const PANEL_LABEL: Record<PanelTab, string> = { live: 'Live', screens: 'Screens', report: 'Report', excel: 'Excel', steps: 'Steps' };
export const PANEL_NAME: Record<PanelTab, string> = { live: 'Live browser', screens: 'Screens', report: 'Report', excel: 'Excel & script', steps: 'Steps' };
const PANEL_ICON: Record<PanelTab, ReactNode> = {
  live: <IconBroadcast size={17} />, screens: <IconPhoto size={17} />, report: <IconFileReport size={17} />, excel: <IconFileSpreadsheet size={17} />, steps: <IconListNumbers size={17} />,
};

const STRIP = 44;
const UNTOUCHED_MS = 60_000;

export interface SidePanelApi {
  /** Inline: open (true) or folded to its 44px strip (false). Drawer/sheet: shown or not. */
  open: boolean;
  tab: PanelTab;
  width: number;
  min: number;
  max: number;
  inline: boolean;
  scenario: string | null;
  show: (tab: PanelTab, opts?: { scenario?: string }) => void;
  hide: () => void;
  toggle: () => void;
  setTab: (tab: PanelTab) => void;
  setWidth: (px: number, save?: boolean) => void;
  resetWidth: () => void;
  /** Switch tab for a run event, unless the person chose a tab in the last minute. Never opens or closes the panel. */
  autoShow: (tab: PanelTab) => void;
  /** Choose the tab for a run the person just opened (not saved; never opens or closes the panel). */
  pick: (tab: PanelTab, opts?: { scenario?: string }) => void;
  /** The person picked a panel tab in this run during this session. */
  chosenInRun: () => boolean;
}

// Runs in which the person picked a panel tab themselves, this session only (never saved).
const chosenRuns = new Set<string>();

const Ctx = createContext<SidePanelApi | null>(null);
export const useSidePanel = () => {
  const v = useContext(Ctx);
  if (!v) throw new Error('useSidePanel outside SidePanelProvider');
  return v;
};
/** The panel, when the current screen has one (run workspace); null elsewhere. */
export const useSidePanelOptional = () => useContext(Ctx);

export function SidePanelProvider({ tabs, runId, children }: { tabs: PanelTab[]; runId?: string; children: ReactNode }) {
  const { size } = useShell();
  const { prefs, set } = useUiPrefs();
  const vp = useViewportSize();
  const [params, setParams] = useSearchParams();
  const [sheet, setSheet] = useState(false);
  const [liveWidth, setLiveWidth] = useState<number | null>(null);
  const touchedAt = useRef(0);
  // The tab chosen for the open run (by the person, by the run's state, or by a run event). The saved tab is only the fallback.
  const [override, setOverride] = useState<{ run?: string; tab: PanelTab } | null>(null);
  // /runs/new: the panel starts folded and its open state is not saved
  const [newOpen, setNewOpen] = useState(false);
  const inline = size === 'desktop' || size === 'laptop';
  const vw = vp.width || (typeof window !== 'undefined' ? window.innerWidth : 1440);
  const [min, max, def] = size === 'laptop' ? [320, 560, 360] : [360, Math.max(400, Math.min(720, Math.round(vw / 2))), 456];
  const clamp = useCallback((n: number) => Math.min(max, Math.max(min, Math.round(n))), [min, max]);
  const width = clamp(liveWidth ?? prefs.panel.width ?? def);
  const wanted = override && override.run === runId ? override.tab : runId ? prefs.panel.tab : 'steps';
  const tab: PanelTab = tabs.includes(wanted) ? wanted : tabs[0];
  const mark = useCallback(() => { touchedAt.current = Date.now(); if (runId) chosenRuns.add(runId); }, [runId]);
  const open = inline ? (runId ? prefs.panel.open : newOpen) : sheet;
  const scenario = params.get('scenario');

  const setScenario = useCallback((sid?: string) => {
    if (!sid) return;
    setParams((p) => { const n = new URLSearchParams(p); n.set('scenario', sid); return n; }, { replace: true });
  }, [setParams]);
  const show = useCallback((t: PanelTab, opts?: { scenario?: string }) => {
    mark();
    setOverride({ run: runId, tab: t });
    setScenario(opts?.scenario);
    if (runId) set({ panel: { open: true, tab: t } }); else setNewOpen(true);
    if (!inline) setSheet(true);
  }, [set, inline, setScenario, mark, runId]);
  const hide = useCallback(() => {
    if (inline) { if (runId) set({ panel: { open: false } }); else setNewOpen(false); } else setSheet(false);
  }, [inline, set, runId]);
  const toggle = useCallback(() => { if (open) hide(); else show(tab); }, [open, hide, show, tab]);
  const setTab = useCallback((t: PanelTab) => { mark(); setOverride({ run: runId, tab: t }); set({ panel: { tab: t } }); }, [set, mark, runId]);
  const setWidth = useCallback((px: number, save = true) => {
    const w = clamp(px);
    if (save) { setLiveWidth(null); set({ panel: { width: w } }); } else setLiveWidth(w);
  }, [clamp, set]);
  const resetWidth = useCallback(() => { setLiveWidth(null); set({ panel: { width: null } }); }, [set]);
  const autoShow = useCallback((t: PanelTab) => {
    if (Date.now() - touchedAt.current < UNTOUCHED_MS || !tabs.includes(t)) return;
    setOverride({ run: runId, tab: t });
  }, [tabs, runId]);
  const pick = useCallback((t: PanelTab, opts?: { scenario?: string }) => {
    if (!tabs.includes(t)) return;
    setScenario(opts?.scenario);
    setOverride({ run: runId, tab: t });
  }, [tabs, runId, setScenario]);
  const chosenInRun = useCallback(() => !!runId && chosenRuns.has(runId), [runId]);

  // Ctrl+\ toggles the panel
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => { if ((e.ctrlKey || e.metaKey) && e.key === '\\') { e.preventDefault(); toggle(); } };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [toggle]);
  useEffect(() => { if (inline) setSheet(false); }, [inline]);

  const value = useMemo<SidePanelApi>(() => ({ open, tab, width, min, max, inline, scenario, show, hide, toggle, setTab, setWidth, resetWidth, autoShow, pick, chosenInRun }),
    [open, tab, width, min, max, inline, scenario, show, hide, toggle, setTab, setWidth, resetWidth, autoShow, pick, chosenInRun]);
  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}

/** The drag handle on the panel's left edge: pointer drag, arrows (16px), Home/End, double-click resets. */
function ResizeHandle() {
  const p = useSidePanel();
  const start = useRef<{ x: number; w: number } | null>(null);
  const saveTimer = useRef<number | null>(null);
  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
    start.current = { x: e.clientX, w: p.width };
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
    if (!start.current) return;
    p.setWidth(start.current.w + (start.current.x - e.clientX), false);
  };
  const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
    if (!start.current) return;
    const w = start.current.w + (start.current.x - e.clientX);
    start.current = null;
    p.setWidth(w, true);
  };
  const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {
    let w: number | null = null;
    if (e.key === 'ArrowLeft') w = p.width + 16;      // the handle is on the left edge: left makes the panel wider
    else if (e.key === 'ArrowRight') w = p.width - 16;
    else if (e.key === 'Home') w = p.min;
    else if (e.key === 'End') w = p.max;
    if (w === null) return;
    e.preventDefault();
    p.setWidth(w, false);
    if (saveTimer.current) window.clearTimeout(saveTimer.current);
    const keep = w;
    saveTimer.current = window.setTimeout(() => p.setWidth(keep, true), 300);
  };
  return (
    <div className="fpt-panel-handle" role="separator" aria-orientation="vertical" aria-label="Resize the run details panel" tabIndex={0}

      aria-valuemin={p.min} aria-valuemax={p.max} aria-valuenow={p.width}

      onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onKeyDown={onKeyDown} onDoubleClick={p.resetWidth} />
  );
}

function PanelBody({ tabs, render, badges, sheet }: { tabs: PanelTab[]; render: Partial<Record<PanelTab, () => ReactNode>>; badges?: Partial<Record<PanelTab, ReactNode>>; sheet?: boolean }) {
  const p = useSidePanel();
  const list = useRef<HTMLDivElement>(null);
  useEffect(() => { list.current?.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]')?.scrollIntoView?.({ inline: 'center', block: 'nearest' }); }, [p.tab]);
  return (
    <Tabs value={p.tab} onChange={(v) => v && p.setTab(v as PanelTab)} keepMounted={false} className="fpt-panel-tabs" data-sheet={sheet || undefined}>

      <div className="fpt-panel-head">

        <Tabs.List ref={list} className="fpt-panel-tablist" aria-label="Run details">

          {tabs.map((t) => (

            <Tabs.Tab key={t} value={t} aria-label={PANEL_NAME[t]}>

              <span className="fpt-panel-tablabel">{PANEL_LABEL[t]}{badges?.[t]}</span>

            </Tabs.Tab>

          ))}

        </Tabs.List>

        <Tooltip label="Hide the run details panel (Ctrl+\)">

          <button type="button" className="fpt-iconbtn" aria-label="Hide the run details panel" onClick={p.hide}>{sheet ? <IconX size={15} /> : <IconLayoutSidebarRightCollapse size={15} />}</button>

        </Tooltip>

      </div>

      {tabs.map((t) => (

        <Tabs.Panel key={t} value={t} className="fpt-panel-content">{render[t]?.()}</Tabs.Panel>

      ))}

    </Tabs>
  );
}

/** The right context panel of a run: Live, Screens, Report, Excel, Steps. Inline (resizable, foldable to a strip) on

 * desktop and laptop, a right drawer on tablets and a bottom sheet on phones. */
export function SidePanel({ tabs, render, badges }: {

  tabs: PanelTab[]; runId?: string; scenarioId?: string | null;

  render: Partial<Record<PanelTab, () => ReactNode>>; badges?: Partial<Record<PanelTab, ReactNode>>;

}) {
  const p = useSidePanel();
  const { size } = useShell();
  if (!p.inline) {
    const phone = size === 'phone';
    return (
      <Drawer opened={p.open} onClose={p.hide} position={phone ? 'bottom' : 'right'} size={phone ? '92dvh' : 'min(420px, 92vw)'} withCloseButton={false} padding={0}

        title={<span className="fpt-sr-only">Run details</span>}

        styles={{ header: { padding: 0, minHeight: 0 }, body: { height: '100%', padding: 0, display: 'flex', flexDirection: 'column' } }}>

        {phone && <div className="fpt-grab" aria-hidden />}

        <PanelBody tabs={tabs} render={render} badges={badges} sheet />

      </Drawer>
    );
  }
  if (!p.open) {
    return (
      <aside className="fpt-panel" data-state="strip" aria-label="Run details" style={{ width: STRIP, flexBasis: STRIP }}>

        <div className="fpt-panel-strip">

          {tabs.map((t) => (

            <Tooltip key={t} label={PANEL_NAME[t]} position="left" withArrow>

              <button type="button" className="fpt-panel-stripbtn" aria-label={`Show the run details panel: ${PANEL_NAME[t]}`} onClick={() => p.show(t)} data-active={t === p.tab}>

                {PANEL_ICON[t]}{badges?.[t] && <span className="fpt-panel-stripbadge">{badges[t]}</span>}

              </button>

            </Tooltip>

          ))}

        </div>

      </aside>
    );
  }
  return (
    <aside className="fpt-panel" data-state="open" aria-label="Run details" style={{ width: p.width, flexBasis: p.width }}>

      <ResizeHandle />

      <PanelBody tabs={tabs} render={render} badges={badges} />

    </aside>
  );
}