EnergyVenom's picture
Tidy the web app: pages by area, CSS in load order, web/README.md (b2a039d)
fb43301 verified
Raw History Blame Contribute Delete
12 kB
import { Drawer, Tabs, Tooltip } from '@mantine/core';
import { useViewportSize } from '@mantine/hooks';
import { IconBroadcast, IconFileReport, IconFileSpreadsheet, IconLayoutSidebarRightCollapse, IconListNumbers, IconPhoto, IconX } from '@/components/icons';
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>
);
}