diff --git a/docs/users/user_guide.md b/docs/users/user_guide.md index a9c493e..6986858 100644 --- a/docs/users/user_guide.md +++ b/docs/users/user_guide.md @@ -233,6 +233,37 @@ _Note: Variables can refer only to PV traces on the same plot, not to other form --- +## Compare with a Time Offset + +Overlay a trace's past data on the current time axis to see how a signal has changed. For example, compare today's beam current with the same signal one day or one week ago. + +**Workflow:** + +1. In the **Layers** panel, hover over a trace row to reveal the clock icon (①). +2. Click the clock icon to open the offset menu. +3. Choose a preset (**-1h**, **-1d**, **-7d**, **-30d**) or type a custom offset such as `-2h` or `-3d` and click **Go**. + +Trace duplicates the trace, shifts its archive data by the offset, and draws it on the same axis. The offset trace uses a **dashed line** so you can tell it apart from the original, and its name in the legend and tooltip includes the offset, for example **Beam current (−1 d)**. + +**How it works:** + +- The offset trace fetches archive data from the shifted time window (for example, yesterday's data for a **-1d** offset) and moves the timestamps onto the current axis so the two traces line up. +- Offset traces are **archive-only** — live data is automatically disabled because live values have no meaningful shifted equivalent. +- If the original trace has a custom **Display Name**, the offset trace keeps it. + +### Edit or Remove an Offset + +Select the offset trace in **Layers** and open the **General** tab in **Properties**: + +- **Time Offset** — change the offset by typing a new value (for example `-12h`). Invalid values show an error below the field. +- **Clear the offset** — delete the text in the **Time Offset** field. The trace goes back to normal and live data is re-enabled. + +You can also delete the offset trace like any other trace. + +_Note: Offset values use the same units as **Span**: `h` (hours), `d` (days), `w` (weeks), and so on. The offset must start with `-` to look into the past._ + +--- + ## Multiple Plots Add more plots to view different groups of PVs side by side. Each plot has its own axes, traces, time range, and settings. diff --git a/src/App.css b/src/App.css index 9766a43..25db14f 100644 --- a/src/App.css +++ b/src/App.css @@ -271,6 +271,97 @@ transition: background-color 0.15s; } +/* Clock button (duplicate-with-offset trigger) */ +.layer-row__offset-trigger { + display: flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border: none; + background: transparent; + color: var(--cds-text-helper); + cursor: pointer; + padding: 0; + border-radius: 2px; + transition: background-color 0.15s; +} + +.layer-row__offset-trigger:hover { + background-color: var(--cds-layer-hover); +} + +/* Offset popover */ +.offset-popover { + position: absolute; + top: 100%; + right: 0; + z-index: 100; + background: var(--cds-layer); + border: 1px solid var(--cds-border-subtle); + border-radius: 4px; + padding: 8px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); + min-width: 140px; +} + +.offset-popover__heading { + font-size: 11px; + color: var(--cds-text-helper); + margin-bottom: 4px; +} + +.offset-popover__preset { + display: block; + width: 100%; + text-align: left; + padding: 4px 8px; + border: none; + background: transparent; + color: var(--cds-text-primary); + font-size: 12px; + cursor: pointer; + border-radius: 2px; + transition: background-color 0.15s; +} + +.offset-popover__preset:hover { + background-color: var(--cds-layer-hover); +} + +.offset-popover__custom-row { + display: flex; + gap: 4px; + margin-top: 4px; +} + +.offset-popover__input { + flex: 1; + font-size: 11px; + padding: 2px 4px; + border: 1px solid var(--cds-border-strong); + border-radius: 2px; + background: var(--cds-field); + color: var(--cds-text-primary); + min-width: 0; +} + +.offset-popover__submit { + font-size: 11px; + padding: 2px 6px; + border: 1px solid var(--cds-border-strong); + border-radius: 2px; + background: var(--cds-button-tertiary); + color: var(--cds-text-inverse); + cursor: pointer; + transition: opacity 0.15s; +} + +.offset-popover__submit:disabled { + cursor: not-allowed; + opacity: 0.5; +} + .axis-drop-zone { border-radius: 2px; transition: background-color 0.15s; @@ -397,6 +488,19 @@ color: var(--cds-text-primary); } +.view-mode-btn:disabled { + opacity: 0.25; + pointer-events: none; +} + +.plot-tab-bar__separator { + width: 1px; + height: 16px; + background-color: var(--cds-border-subtle); + margin: 0 4px; + flex-shrink: 0; +} + .plot-content { flex: 1; overflow: hidden; @@ -446,6 +550,13 @@ z-index: 10; } +.plot-grid__cell-btn--reset { + position: absolute; + top: 8px; + left: 80px; + z-index: 10; +} + .plot-grid__cell-btn--close { position: absolute; top: 8px; diff --git a/src/api/time.test.ts b/src/api/time.test.ts index 2497c15..1880117 100644 --- a/src/api/time.test.ts +++ b/src/api/time.test.ts @@ -1,5 +1,13 @@ import { describe, it, expect } from 'vitest'; -import { parseSpanMs, relativeRangeMs, resolveTimeWindow, toDatetimeLocal, msToNs } from './time'; +import { + parseSpanMs, + relativeRangeMs, + resolveTimeWindow, + toDatetimeLocal, + msToNs, + parseOffsetMs, + formatOffsetLabel, +} from './time'; const SEC = 1000; const MIN = 60 * SEC; @@ -141,6 +149,27 @@ describe('resolveTimeWindow', () => { }); }); +describe('parseOffsetMs', () => { + it('parses signed and bare offsets, rejects invalid input', () => { + expect(parseOffsetMs('-1d')).toBe(-DAY); + expect(parseOffsetMs('-7d')).toBe(-7 * DAY); + expect(parseOffsetMs('+2h')).toBe(2 * HOUR); + expect(parseOffsetMs('30s')).toBe(30 * SEC); + expect(parseOffsetMs('')).toBeNull(); + expect(parseOffsetMs('abc')).toBeNull(); + expect(parseOffsetMs('-0h')).toBeNull(); + }); +}); + +describe('formatOffsetLabel', () => { + it('picks the largest whole unit with the correct sign', () => { + expect(formatOffsetLabel(-DAY)).toBe('−1 d'); + expect(formatOffsetLabel(-14 * DAY)).toBe('−2 w'); + expect(formatOffsetLabel(2 * HOUR)).toBe('+2 h'); + expect(formatOffsetLabel(-500)).toBe('−500 ms'); + }); +}); + describe('toDatetimeLocal', () => { it('round-trips through Date in local time', () => { const ms = new Date('2024-03-04T05:06').getTime(); diff --git a/src/api/time.ts b/src/api/time.ts index df80a75..d71def2 100644 --- a/src/api/time.ts +++ b/src/api/time.ts @@ -37,6 +37,33 @@ export function relativeRangeMs(range: string): number | null { return parseSpanMs(range.slice(1)); } +// Parse a signed offset like "-1d", "+2h" into milliseconds. Returns null if invalid. +export function parseOffsetMs(offset: string): number | null { + const trimmed = offset.trim(); + if (!trimmed) return null; + const neg = trimmed.startsWith('-'); + const raw = neg || trimmed.startsWith('+') ? trimmed.slice(1) : trimmed; + const ms = parseSpanMs(raw); + return ms != null ? (neg ? -ms : ms) : null; +} + +// Human-readable label for a millisecond offset, e.g. "−1 d", "+2 h". +export function formatOffsetLabel(offsetMs: number): string { + const sign = offsetMs < 0 ? '−' : '+'; + const abs = Math.abs(offsetMs); + const units: [number, string][] = [ + [SPAN_UNIT_MS.w, 'w'], + [SPAN_UNIT_MS.d, 'd'], + [SPAN_UNIT_MS.h, 'h'], + [SPAN_UNIT_MS.m, 'm'], + [SPAN_UNIT_MS.s, 's'], + ]; + for (const [ms, label] of units) { + if (abs >= ms && abs % ms === 0) return `${sign}${abs / ms} ${label}`; + } + return `${sign}${abs} ms`; +} + // Format an epoch-ms instant as a datetime-local value ("YYYY-MM-DDTHH:mm") in // local time, suitable for seeding the From/To inputs from an absolute time. export function toDatetimeLocal(ms: number): string { diff --git a/src/components/LeftPanel.test.tsx b/src/components/LeftPanel.test.tsx index 162afdd..450e905 100644 --- a/src/components/LeftPanel.test.tsx +++ b/src/components/LeftPanel.test.tsx @@ -67,6 +67,7 @@ function panel(plots: Plot[]) { onAddTrace={vi.fn()} onAddFormula={vi.fn()} onDeleteTrace={vi.fn()} + onDuplicateWithOffset={vi.fn()} onAddAxis={vi.fn()} onSearchPvs={vi.fn()} onDeleteAxis={vi.fn()} diff --git a/src/components/LeftPanel.tsx b/src/components/LeftPanel.tsx index bfd5299..d8935d8 100644 --- a/src/components/LeftPanel.tsx +++ b/src/components/LeftPanel.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { DndContext, DragOverlay, @@ -24,8 +24,10 @@ import { Archive, TrashCan, Function as FunctionIcon, + Time, } from '@carbon/icons-react'; import { Button, Tag } from '@carbon/react'; +import { parseOffsetMs } from '../api/time'; import type { Plot, PVTrace, Axis } from '../types'; import { traceLabel } from '../traceLabel'; import type { SelectedItem } from './TraceApp'; @@ -56,6 +58,7 @@ interface LeftPanelProps { onAddTrace: (plotId: string, axisId: string) => void; onAddFormula: (plotId: string, axisId: string) => void; onDeleteTrace: (plotId: string, traceId: string) => void; + onDuplicateWithOffset: (plotId: string, sourceTraceId: string, offset: string) => void; onAddAxis: (plotId: string) => void; onSearchPvs: (plotId: string) => void; onDeleteAxis: (plotId: string, axisId: string) => void; @@ -104,6 +107,104 @@ function ArchiveStatusChip({ result }: { result: ArchiveSeriesResult | undefined return null; } +const OFFSET_PRESETS = ['-1h', '-1d', '-7d', '-30d']; + +function OffsetPopover({ + onSelect, + onClose, +}: { + onSelect: (offset: string) => void; + onClose: () => void; +}) { + const [custom, setCustom] = useState(''); + const popoverRef = useRef(null); + const validCustom = !!custom && parseOffsetMs(custom) != null; + const submitCustom = () => { + if (validCustom) { + onSelect(custom); + onClose(); + } + }; + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') { + e.stopPropagation(); + onClose(); + } + }; + const onClick = (e: MouseEvent) => { + if (popoverRef.current && !popoverRef.current.contains(e.target as Node)) { + onClose(); + } + }; + document.addEventListener('keydown', onKey); + document.addEventListener('mousedown', onClick); + return () => { + document.removeEventListener('keydown', onKey); + document.removeEventListener('mousedown', onClick); + }; + }, [onClose]); + + const navigateMenu = (e: React.KeyboardEvent) => { + const items = popoverRef.current?.querySelectorAll('[role="menuitem"]'); + if (!items?.length) return; + const list = Array.from(items); + const idx = list.indexOf(e.target as HTMLElement); + let next: number | null = null; + if (e.key === 'ArrowDown') next = idx < list.length - 1 ? idx + 1 : 0; + else if (e.key === 'ArrowUp') next = idx > 0 ? idx - 1 : list.length - 1; + else if (e.key === 'Home') next = 0; + else if (e.key === 'End') next = list.length - 1; + if (next != null) { + e.preventDefault(); + list[next].focus(); + } + }; + + return ( +
e.stopPropagation()} + onPointerDown={(e) => e.stopPropagation()} + onKeyDown={navigateMenu} + > +
Compare with
+ {OFFSET_PRESETS.map((preset, i) => ( + + ))} +
+ setCustom(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') submitCustom(); + }} + /> + +
+
+ ); +} + interface TraceRowProps { trace: PVTrace; label: string; @@ -112,6 +213,7 @@ interface TraceRowProps { isSelected: boolean; onSelect: () => void; onDelete: () => void; + onDuplicateWithOffset?: (offset: string) => void; } function TraceRow({ @@ -122,7 +224,9 @@ function TraceRow({ isSelected, onSelect, onDelete, + onDuplicateWithOffset, }: TraceRowProps) { + const [showOffsetPopover, setShowOffsetPopover] = useState(false); const data: DragData = { plotId, axisId: trace.axisId, traceId: trace.id }; const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: `${plotId}::${trace.id}`, @@ -134,6 +238,8 @@ function TraceRow({ transition, }; + const canDuplicate = onDuplicateWithOffset && trace.kind !== 'formula' && !!trace.pvName; + return (
+ {canDuplicate && ( +
e.stopPropagation()}> + + {showOffsetPopover && ( + onDuplicateWithOffset!(offset)} + onClose={() => setShowOffsetPopover(false)} + /> + )} +
+ )} + + +
+ {plots.length > 1 && (
+ {trace.kind !== 'formula' && + (() => { + const offsetInvalid = !!trace.timeOffset && parseOffsetMs(trace.timeOffset) == null; + return ( +
+ onUpdate({ timeOffset: e.target.value || undefined })} + size="sm" + /> +
+ ); + })()}
onUpdate({ useLive: checked })} size="sm" hideLabel + disabled={!!trace.timeOffset && parseOffsetMs(trace.timeOffset) != null} />
{trace.useLive && ( diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index a80dff5..1a25522 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -23,7 +23,7 @@ import { archiveStore } from '../state/archiveStore'; import { axisEndMs, isFollowing, useAutoScrollTimers } from '../hooks/useAutoScrollTimers'; import { useFormulaSeries, type FormulaSeriesResult } from '../hooks/useFormulaSeries'; import type { TimeWindowNs } from '../api/time'; -import { resolveTimeWindow } from '../api/time'; +import { resolveTimeWindow, parseOffsetMs, msToNs } from '../api/time'; import { fetchMetadata } from '@slaclab/canopy-client'; import { useCanopyConnection } from '@slaclab/canopy-react'; import { @@ -57,6 +57,7 @@ import { getConfig } from '../api/magpie'; import { errorInfo } from '../api/errorInfo'; import { useElogConfig } from '../hooks/useElogConfig'; import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts'; +import { useViewHistory, type ViewSnapshot, type AxisSnapshot } from '../hooks/useViewHistory'; function generateMockData( points: number, @@ -70,6 +71,13 @@ function generateMockData( })); } +function enforceOffsetArchiveOnly(trace: PVTrace): PVTrace { + if (trace.timeOffset && parseOffsetMs(trace.timeOffset) != null) { + return { ...trace, useLive: false, useArchive: true }; + } + return trace; +} + // The app starts with a single empty plot so users begin from a clean slate. const INITIAL_PLOTS: Plot[] = [ { @@ -192,6 +200,10 @@ export function TraceApp() { const [viewWindowByPlot, setViewWindowByPlot] = useState>( () => new Map() ); + const viewHistory = useViewHistory(); + const [zoomTargetByPlot, setZoomTargetByPlot] = useState< + Map + >(() => new Map()); const [workspaceGeneration, setWorkspaceGeneration] = useState(0); const leftPanelRef = usePanelRef(); const rightPanelRef = usePanelRef(); @@ -225,11 +237,27 @@ export function TraceApp() { const win = viewWindowByPlot.get(plot.id) ?? resolveTimeWindow(plot.xAxis, clock.nowFor(plot.id)).window; fetchWindowByPlot.set(plot.id, win); + // Quantize the clock to 30s buckets so offset trace windows don't shift + // on every autoscroll tick and thrash the archive store with refetches. + const OFFSET_BUCKET_MS = 30_000; + const quantizedNow = Math.floor(clock.nowFor(plot.id) / OFFSET_BUCKET_MS) * OFFSET_BUCKET_MS; + const offsetBaseWin = + viewWindowByPlot.get(plot.id) ?? resolveTimeWindow(plot.xAxis, quantizedNow).window; + for (const trace of plot.traces) { - if (trace.useArchive) windowByTrace.set(trace.id, win); + const offsetMs = trace.timeOffset ? parseOffsetMs(trace.timeOffset) : null; + const traceWin = + offsetMs != null + ? { + fromNs: offsetBaseWin.fromNs + msToNs(offsetMs), + toNs: offsetBaseWin.toNs + msToNs(offsetMs), + } + : win; + + if (trace.useArchive) windowByTrace.set(trace.id, traceWin); plotArchiverByTrace.set(trace.id, plot.archiver); if (trace.kind === 'formula') { - windowByTrace.set(trace.id, win); + windowByTrace.set(trace.id, traceWin); formulaSpecByTrace.set(trace.id, resolveFormulaSpec(trace, plot.traces)); } } @@ -242,6 +270,13 @@ export function TraceApp() { const liveResults = useLiveSeries(allTraces); const formulaResults = useFormulaSeries(allTraces, formulaSpecByTrace, windowByTrace); + const snapshotAxes = (plot: Plot | undefined): Map => { + const m = new Map(); + for (const a of plot?.axes ?? []) + m.set(a.id, { min: a.min, max: a.max, autoScale: a.autoScale }); + return m; + }; + const handleViewWindowChange = (plotId: string, window: TimeWindowNs) => { setViewWindowByPlot((prev) => { const next = new Map(prev); @@ -251,6 +286,11 @@ export function TraceApp() { // A manual pan/zoom takes over the window, so stop tracking "now". Picking a // time range re-enables it (see updatePlot). setPlots((prev) => prev.map((p) => (p.id === plotId ? { ...p, autoScroll: false } : p))); + viewHistory.push(plotId, { + timeWindow: window, + axisRanges: snapshotAxes(plots.find((p) => p.id === plotId)), + autoScroll: false, + }); }; // Split the flat result maps per plot. Memoized on (plots, archiveResults, @@ -392,6 +432,13 @@ export function TraceApp() { setPlots((prev) => prev.filter((p) => p.id !== plotId)); if (poppedOutPlot === plotId) setPoppedOutPlot(null); setDetachedPlotIds((prev) => prev.filter((id) => id !== plotId)); + viewHistory.clear(plotId); + setZoomTargetByPlot((prev) => { + if (!prev.has(plotId)) return prev; + const next = new Map(prev); + next.delete(plotId); + return next; + }); if (activePlotId === plotId) { const remaining = plots.filter((p) => p.id !== plotId); setActivePlotId(remaining[0].id); @@ -456,6 +503,79 @@ export function TraceApp() { // Autoscroll toggle does, before the view window is debounced in. const handleFollowStop = (plotId: string) => updatePlot(plotId, { autoScroll: false }); + const restoreSnapshot = (plotId: string, snapshot: ViewSnapshot) => { + if (snapshot.timeWindow) { + setViewWindowByPlot((prev) => { + const next = new Map(prev); + next.set(plotId, snapshot.timeWindow!); + return next; + }); + } else { + clearViewWindow(plotId); + } + setPlots((prev) => + prev.map((p) => { + if (p.id !== plotId) return p; + return { + ...p, + autoScroll: snapshot.autoScroll, + axes: p.axes.map((a) => { + const saved = snapshot.axisRanges.get(a.id); + if (!saved) return a; + return { ...a, min: saved.min, max: saved.max, autoScale: saved.autoScale }; + }), + }; + }) + ); + setZoomTargetByPlot((prev) => { + const next = new Map(prev); + const gen = (prev.get(plotId)?.generation ?? 0) + 1; + next.set(plotId, { window: snapshot.timeWindow, generation: gen }); + return next; + }); + if (snapshot.autoScroll && !snapshot.timeWindow) { + clock.resync([plotId]); + } + }; + + const handleViewBack = (plotId: string) => { + const snapshot = viewHistory.goBack(plotId); + if (snapshot) restoreSnapshot(plotId, snapshot); + }; + + const handleViewForward = (plotId: string) => { + const snapshot = viewHistory.goForward(plotId); + if (snapshot) restoreSnapshot(plotId, snapshot); + }; + + const handleResetZoom = (plotId: string) => { + const plot = plots.find((p) => p.id === plotId); + viewHistory.push(plotId, { + timeWindow: viewWindowByPlot.get(plotId) ?? null, + axisRanges: snapshotAxes(plot), + autoScroll: plot?.autoScroll !== false, + }); + clearViewWindow(plotId); + setPlots((prev) => + prev.map((p) => + p.id !== plotId + ? p + : { + ...p, + autoScroll: true, + axes: p.axes.map((a) => ({ ...a, autoScale: true, min: undefined, max: undefined })), + } + ) + ); + clock.resync([plotId]); + setZoomTargetByPlot((prev) => { + const next = new Map(prev); + const gen = (prev.get(plotId)?.generation ?? 0) + 1; + next.set(plotId, { window: null, generation: gen }); + return next; + }); + }; + // ── Trace operations ───────────────────────────────────────────────────────── // The defaults every new PV trace starts from, shared by Add Trace and the @@ -593,13 +713,38 @@ export function TraceApp() { if (selectedItem?.id === traceId && selectedItem.plotId === plotId) setSelectedItem(null); }; + const duplicateTraceWithOffset = (plotId: string, sourceTraceId: string, offset: string) => { + const plot = plots.find((p) => p.id === plotId); + const source = plot?.traces.find((t) => t.id === sourceTraceId); + if (!plot || !source) return; + const id = makeId('trace'); + const newTrace: PVTrace = enforceOffsetArchiveOnly({ + ...source, + id, + color: colorForIndex(getPalette(paletteId), plot.traces.length), + displayName: source.displayName, + timeOffset: offset, + lineStyle: 'dashed', + data: [], + }); + setPlots((prev) => + prev.map((p) => (p.id === plotId ? { ...p, traces: [...p.traces, newTrace] } : p)) + ); + selectItem({ type: 'trace', id, plotId }); + }; + const updateTrace = (traceId: string, updates: Partial) => { + if ('timeOffset' in updates && !updates.timeOffset) { + updates = { ...updates, useLive: true }; + } setPlots((prev) => prev.map((p) => p.id === activePlotId ? { ...p, - traces: p.traces.map((t) => (t.id === traceId ? { ...t, ...updates } : t)), + traces: p.traces.map((t) => + t.id === traceId ? enforceOffsetArchiveOnly({ ...t, ...updates }) : t + ), } : p ) @@ -800,16 +945,24 @@ export function TraceApp() { // plot (grid cells and popouts aren't necessarily the active plot), so route // by the plot id rather than assuming activePlotId. const updateAxisInPlot = (plotId: string, axisId: string, updates: Partial) => { - setPlots((prev) => - prev.map((p) => + setPlots((prev) => { + const next = prev.map((p) => p.id === plotId ? { ...p, axes: p.axes.map((a) => (a.id === axisId ? { ...a, ...updates } : a)), } : p - ) - ); + ); + const plot = next.find((p) => p.id === plotId); + const axisRanges = snapshotAxes(plot); + viewHistory.push(plotId, { + timeWindow: viewWindowByPlot.get(plotId) ?? null, + axisRanges, + autoScroll: plot?.autoScroll !== false, + }); + return next; + }); }; const liveCount = activePlot.traces.filter((t) => t.useLive).length; @@ -835,7 +988,7 @@ export function TraceApp() { throw new Error('Workspace contains no plots'); } abortUnitLookups(); - setPlots(result.plots); + setPlots(result.plots.map((p) => ({ ...p, traces: p.traces.map(enforceOffsetArchiveOnly) }))); setWorkspaceGeneration((generation) => generation + 1); setActivePlotId(result.plots[0].id); resyncClock(result.plots.map((p) => p.id)); @@ -1071,6 +1224,9 @@ export function TraceApp() { onPostElog: elogConfig?.enabled ? openElogPost : undefined, onDataInsight: () => openInsight(), onToggleTheme: toggleTheme, + onViewBack: () => handleViewBack(activePlotId), + onViewForward: () => handleViewForward(activePlotId), + onResetZoom: () => handleResetZoom(activePlotId), }); return ( @@ -1121,6 +1277,7 @@ export function TraceApp() { onAddTrace={addTrace} onAddFormula={addFormula} onDeleteTrace={deleteTrace} + onDuplicateWithOffset={duplicateTraceWithOffset} onAddAxis={addAxis} onSearchPvs={openPvSearch} onDeleteAxis={deleteAxis} @@ -1166,6 +1323,12 @@ export function TraceApp() { onAxisRangesChange={handleAxisRangesChange} onUpdateAxis={updateAxisInPlot} onChartInstance={handleChartInstance} + onViewBack={handleViewBack} + onViewForward={handleViewForward} + onResetZoom={handleResetZoom} + canGoBack={viewHistory.canGoBack} + canGoForward={viewHistory.canGoForward} + zoomTargetByPlot={zoomTargetByPlot} /> @@ -1335,6 +1498,8 @@ export function TraceApp() { archiveResults={archiveResultsByPlot.get(plot.id) ?? new Map()} liveResults={liveResultsByPlot.get(plot.id) ?? new Map()} formulaResults={formulaResultsByPlot.get(plot.id) ?? new Map()} + onViewWindowChange={(w) => handleViewWindowChange(plot.id, w)} + initialViewWindowNs={viewWindowByPlot.get(plot.id)} // eslint-disable-next-line react-hooks/refs -- ref is written from ECharts' finished event, not during render onAxisRangesChange={(r) => handleAxisRangesChange(plot.id, r)} onUpdateAxis={(id, u) => updateAxisInPlot(plot.id, id, u)} @@ -1342,6 +1507,7 @@ export function TraceApp() { // eslint-disable-next-line react-hooks/refs -- ref is written on mount/unmount, not during render handleChartInstance(plot.id, inst, active, true) } + zoomTarget={zoomTargetByPlot.get(plot.id)} /> @@ -1443,6 +1609,7 @@ export function TraceApp() { onAxisRangesChange={(r) => handleAxisRangesChange(plot.id, r)} onUpdateAxis={(id, u) => updateAxisInPlot(plot.id, id, u)} onChartInstance={(inst, active) => handleChartInstance(plot.id, inst, active)} + zoomTarget={zoomTargetByPlot.get(plot.id)} /> diff --git a/src/hooks/useKeyboardShortcuts.test.ts b/src/hooks/useKeyboardShortcuts.test.ts index 542cf79..3dca9dc 100644 --- a/src/hooks/useKeyboardShortcuts.test.ts +++ b/src/hooks/useKeyboardShortcuts.test.ts @@ -61,6 +61,34 @@ describe('resolveShortcut', () => { }); }); + describe('view history shortcuts (alt group)', () => { + it('maps Alt+ArrowLeft to viewBack', () => { + expect(resolveShortcut(ev({ key: 'ArrowLeft', altKey: true }), false)).toBe('onViewBack'); + expect(resolveShortcut(ev({ key: 'ArrowLeft', altKey: true }), true)).toBe('onViewBack'); + }); + + it('maps Alt+ArrowRight to viewForward', () => { + expect(resolveShortcut(ev({ key: 'ArrowRight', altKey: true }), false)).toBe('onViewForward'); + expect(resolveShortcut(ev({ key: 'ArrowRight', altKey: true }), true)).toBe('onViewForward'); + }); + + it('maps Alt+0 to resetZoom', () => { + expect(resolveShortcut(ev({ key: '0', altKey: true }), false)).toBe('onResetZoom'); + expect(resolveShortcut(ev({ key: '0', altKey: true }), true)).toBe('onResetZoom'); + }); + + it('does not match arrow keys without Alt', () => { + expect(resolveShortcut(ev({ key: 'ArrowLeft' }), false)).toBeNull(); + expect(resolveShortcut(ev({ key: 'ArrowRight' }), false)).toBeNull(); + }); + + it('does not match Alt+Arrow when primary modifier is also held', () => { + expect( + resolveShortcut(ev({ key: 'ArrowLeft', altKey: true, ctrlKey: true }), false) + ).toBeNull(); + }); + }); + describe('non-matches pass through to the browser', () => { it('ignores a bare key with no modifier', () => { expect(resolveShortcut(ev({ key: 's' }), false)).toBeNull(); diff --git a/src/hooks/useKeyboardShortcuts.ts b/src/hooks/useKeyboardShortcuts.ts index b09aaf0..0360f3d 100644 --- a/src/hooks/useKeyboardShortcuts.ts +++ b/src/hooks/useKeyboardShortcuts.ts @@ -13,6 +13,9 @@ export interface ShortcutHandlers { onPostElog?: () => void; onDataInsight?: () => void; onToggleTheme?: () => void; + onViewBack?: () => void; + onViewForward?: () => void; + onResetZoom?: () => void; } /** Handler keys, in binding order. */ @@ -45,6 +48,9 @@ const BINDINGS: { mod: Mod; key: string; action: Action }[] = [ { mod: 'primary', key: 'i', action: 'onExportImage' }, { mod: 'alt', key: 'd', action: 'onDataInsight' }, { mod: 'alt', key: 't', action: 'onToggleTheme' }, + { mod: 'alt', key: 'arrowleft', action: 'onViewBack' }, + { mod: 'alt', key: 'arrowright', action: 'onViewForward' }, + { mod: 'alt', key: '0', action: 'onResetZoom' }, ]; /** The event fields a shortcut match depends on. */ diff --git a/src/hooks/useViewHistory.test.ts b/src/hooks/useViewHistory.test.ts new file mode 100644 index 0000000..9f12865 --- /dev/null +++ b/src/hooks/useViewHistory.test.ts @@ -0,0 +1,309 @@ +// @vitest-environment jsdom +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { useViewHistory, type ViewSnapshot } from './useViewHistory'; + +function snap(overrides: Partial = {}): ViewSnapshot { + return { + timeWindow: { fromNs: 1000, toNs: 2000 }, + axisRanges: new Map(), + autoScroll: false, + ...overrides, + }; +} + +function snapAt(fromNs: number, toNs: number): ViewSnapshot { + return snap({ timeWindow: { fromNs, toNs } }); +} + +describe('useViewHistory', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it('starts with no history', () => { + const { result } = renderHook(() => useViewHistory()); + expect(result.current.canGoBack('p1')).toBe(false); + expect(result.current.canGoForward('p1')).toBe(false); + }); + + it('push then goBack returns the previous snapshot', () => { + const { result } = renderHook(() => useViewHistory()); + const s1 = snapAt(0, 100); + const s2 = snapAt(100, 200); + + act(() => { + result.current.push('p1', s1); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', s2); + vi.advanceTimersByTime(300); + }); + + expect(result.current.canGoBack('p1')).toBe(true); + expect(result.current.canGoForward('p1')).toBe(false); + + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goBack('p1'); + }); + expect(restored).not.toBeNull(); + expect(restored!.timeWindow).toEqual({ fromNs: 0, toNs: 100 }); + expect(result.current.canGoForward('p1')).toBe(true); + }); + + it('goForward after goBack returns to the later snapshot', () => { + const { result } = renderHook(() => useViewHistory()); + const s1 = snapAt(0, 100); + const s2 = snapAt(100, 200); + + act(() => { + result.current.push('p1', s1); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', s2); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.goBack('p1'); + }); + + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goForward('p1'); + }); + expect(restored!.timeWindow).toEqual({ fromNs: 100, toNs: 200 }); + expect(result.current.canGoForward('p1')).toBe(false); + }); + + it('push after goBack truncates forward entries', () => { + const { result } = renderHook(() => useViewHistory()); + + act(() => { + result.current.push('p1', snapAt(0, 100)); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', snapAt(100, 200)); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', snapAt(200, 300)); + vi.advanceTimersByTime(300); + }); + + // Go back to entry 1 + act(() => { + result.current.goBack('p1'); + }); + act(() => { + result.current.goBack('p1'); + }); + + // Push new entry — forward stack (entries 2,3) should be gone + act(() => { + result.current.push('p1', snapAt(999, 1000)); + vi.advanceTimersByTime(300); + }); + + expect(result.current.canGoForward('p1')).toBe(false); + + // Going back should get entry 0 + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goBack('p1'); + }); + expect(restored!.timeWindow).toEqual({ fromNs: 0, toNs: 100 }); + }); + + it('deduplicates identical consecutive snapshots', () => { + const { result } = renderHook(() => useViewHistory()); + const s = snapAt(0, 100); + + act(() => { + result.current.push('p1', s); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', snapAt(0, 100)); // same values + vi.advanceTimersByTime(300); + }); + + expect(result.current.canGoBack('p1')).toBe(false); + }); + + it('coalesces rapid pushes within 300ms', () => { + const { result } = renderHook(() => useViewHistory()); + + act(() => { + result.current.push('p1', snapAt(0, 100)); + vi.advanceTimersByTime(100); // only 100ms — still pending + result.current.push('p1', snapAt(0, 200)); // replaces pending + vi.advanceTimersByTime(300); // now commits + }); + + // Only one entry — the second push replaced the first + expect(result.current.canGoBack('p1')).toBe(false); + + // Push a different one to verify the committed value + act(() => { + result.current.push('p1', snapAt(999, 1000)); + vi.advanceTimersByTime(300); + }); + + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goBack('p1'); + }); + expect(restored!.timeWindow).toEqual({ fromNs: 0, toNs: 200 }); + }); + + it('goBack flushes pending coalesce first', () => { + const { result } = renderHook(() => useViewHistory()); + + act(() => { + result.current.push('p1', snapAt(0, 100)); + vi.advanceTimersByTime(300); + }); + act(() => { + // Push but don't wait for coalesce + result.current.push('p1', snapAt(100, 200)); + }); + + // goBack should flush the pending push, then step back + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goBack('p1'); + }); + expect(restored!.timeWindow).toEqual({ fromNs: 0, toNs: 100 }); + expect(result.current.canGoForward('p1')).toBe(true); + }); + + it('caps history at 50 entries', () => { + const { result } = renderHook(() => useViewHistory()); + + act(() => { + for (let i = 0; i < 60; i++) { + result.current.push('p1', snapAt(i, i + 1)); + vi.advanceTimersByTime(300); + } + }); + + // Should be able to go back at most 49 times (50 entries, cursor at end) + let count = 0; + act(() => { + while (result.current.goBack('p1') !== null) count++; + }); + expect(count).toBe(49); + }); + + it('clear removes all history for a plot', () => { + const { result } = renderHook(() => useViewHistory()); + + act(() => { + result.current.push('p1', snapAt(0, 100)); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', snapAt(100, 200)); + vi.advanceTimersByTime(300); + }); + + act(() => { + result.current.clear('p1'); + }); + + expect(result.current.canGoBack('p1')).toBe(false); + expect(result.current.canGoForward('p1')).toBe(false); + expect(result.current.goBack('p1')).toBeNull(); + }); + + it('histories are independent per plot', () => { + const { result } = renderHook(() => useViewHistory()); + + act(() => { + result.current.push('p1', snapAt(0, 100)); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', snapAt(100, 200)); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p2', snapAt(500, 600)); + vi.advanceTimersByTime(300); + }); + + expect(result.current.canGoBack('p1')).toBe(true); + expect(result.current.canGoBack('p2')).toBe(false); + }); + + it('compares axis ranges in dedup', () => { + const { result } = renderHook(() => useViewHistory()); + const axes1 = new Map([['a1', { min: 0, max: 10, autoScale: false }]]); + const axes2 = new Map([['a1', { min: 5, max: 15, autoScale: false }]]); + + act(() => { + result.current.push('p1', snap({ axisRanges: axes1 })); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', snap({ axisRanges: axes2 })); + vi.advanceTimersByTime(300); + }); + + // Different axis ranges → two entries + expect(result.current.canGoBack('p1')).toBe(true); + }); + + it('goForward flushes pending coalesce so a zoom truncates forward stack', () => { + const { result } = renderHook(() => useViewHistory()); + + act(() => { + result.current.push('p1', snapAt(0, 100)); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', snapAt(100, 200)); + vi.advanceTimersByTime(300); + }); + + // Go back to entry 0 + act(() => { + result.current.goBack('p1'); + }); + + // Zoom (pending push) — should truncate forward when flushed + act(() => { + result.current.push('p1', snapAt(999, 1000)); + }); + + // goForward should flush the pending zoom (which truncates forward), then find nothing + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goForward('p1'); + }); + expect(restored).toBeNull(); + expect(result.current.canGoForward('p1')).toBe(false); + }); + + it('goBack/goForward return null at boundaries', () => { + const { result } = renderHook(() => useViewHistory()); + + expect(result.current.goBack('p1')).toBeNull(); + expect(result.current.goForward('p1')).toBeNull(); + + act(() => { + result.current.push('p1', snapAt(0, 100)); + vi.advanceTimersByTime(300); + }); + + expect(result.current.goBack('p1')).toBeNull(); + expect(result.current.goForward('p1')).toBeNull(); + }); +}); diff --git a/src/hooks/useViewHistory.ts b/src/hooks/useViewHistory.ts new file mode 100644 index 0000000..7eff91c --- /dev/null +++ b/src/hooks/useViewHistory.ts @@ -0,0 +1,190 @@ +import { useCallback, useRef, useState } from 'react'; +import type { TimeWindowNs } from '../api/time'; + +export interface AxisSnapshot { + min?: number; + max?: number; + autoScale: boolean; +} + +export interface ViewSnapshot { + timeWindow: TimeWindowNs | null; + axisRanges: Map; + autoScroll: boolean; +} + +interface PlotHistory { + stack: ViewSnapshot[]; + cursor: number; +} + +const MAX_ENTRIES = 50; +const COALESCE_MS = 300; + +function snapshotsEqual(a: ViewSnapshot, b: ViewSnapshot): boolean { + if (a.autoScroll !== b.autoScroll) return false; + if ((a.timeWindow === null) !== (b.timeWindow === null)) return false; + if (a.timeWindow && b.timeWindow) { + if (a.timeWindow.fromNs !== b.timeWindow.fromNs) return false; + if (a.timeWindow.toNs !== b.timeWindow.toNs) return false; + } + if (a.axisRanges.size !== b.axisRanges.size) return false; + for (const [id, ar] of a.axisRanges) { + const br = b.axisRanges.get(id); + if (!br) return false; + if (ar.min !== br.min || ar.max !== br.max || ar.autoScale !== br.autoScale) return false; + } + return true; +} + +export interface ViewHistoryAPI { + push(plotId: string, snapshot: ViewSnapshot): void; + goBack(plotId: string): ViewSnapshot | null; + goForward(plotId: string): ViewSnapshot | null; + canGoBack(plotId: string): boolean; + canGoForward(plotId: string): boolean; + clear(plotId: string): void; +} + +export function useViewHistory(): ViewHistoryAPI { + const historyRef = useRef>(new Map()); + const timerRef = useRef>>(new Map()); + const pendingRef = useRef>(new Map()); + + const [nav, setNav] = useState>( + () => new Map() + ); + + const updateNav = useCallback((plotId: string, h: PlotHistory) => { + setNav((prev) => { + const canBack = h.cursor > 0; + const canForward = h.cursor < h.stack.length - 1; + const old = prev.get(plotId); + if (old && old.canBack === canBack && old.canForward === canForward) return prev; + const next = new Map(prev); + next.set(plotId, { canBack, canForward }); + return next; + }); + }, []); + + const getOrCreate = useCallback((plotId: string): PlotHistory => { + let h = historyRef.current.get(plotId); + if (!h) { + h = { stack: [], cursor: -1 }; + historyRef.current.set(plotId, h); + } + return h; + }, []); + + const commitPending = useCallback( + (plotId: string) => { + const snapshot = pendingRef.current.get(plotId); + pendingRef.current.delete(plotId); + if (!snapshot) return; + + const h = getOrCreate(plotId); + + // Dedup: skip if identical to current entry. + if (h.cursor >= 0 && snapshotsEqual(h.stack[h.cursor], snapshot)) return; + + // Truncate forward entries. + h.stack.length = h.cursor + 1; + h.stack.push(snapshot); + + // Cap size. + if (h.stack.length > MAX_ENTRIES) { + const excess = h.stack.length - MAX_ENTRIES; + h.stack.splice(0, excess); + } + h.cursor = h.stack.length - 1; + + updateNav(plotId, h); + }, + [getOrCreate, updateNav] + ); + + const push = useCallback( + (plotId: string, snapshot: ViewSnapshot) => { + pendingRef.current.set(plotId, snapshot); + + const existing = timerRef.current.get(plotId); + if (existing !== undefined) clearTimeout(existing); + + timerRef.current.set( + plotId, + setTimeout(() => { + timerRef.current.delete(plotId); + commitPending(plotId); + }, COALESCE_MS) + ); + }, + [commitPending] + ); + + const goBack = useCallback( + (plotId: string): ViewSnapshot | null => { + // Cancel any pending coalesce — commit it first so "back" undoes the latest action. + const timer = timerRef.current.get(plotId); + if (timer !== undefined) { + clearTimeout(timer); + timerRef.current.delete(plotId); + commitPending(plotId); + } + + const h = historyRef.current.get(plotId); + if (!h || h.cursor <= 0) return null; + h.cursor -= 1; + updateNav(plotId, h); + return h.stack[h.cursor]; + }, + [commitPending, updateNav] + ); + + const goForward = useCallback( + (plotId: string): ViewSnapshot | null => { + // Flush pending coalesce (same as goBack) so a zoom right before forward + // correctly truncates the forward stack instead of being silently dropped. + const timer = timerRef.current.get(plotId); + if (timer !== undefined) { + clearTimeout(timer); + timerRef.current.delete(plotId); + commitPending(plotId); + } + + const h = historyRef.current.get(plotId); + if (!h || h.cursor >= h.stack.length - 1) return null; + h.cursor += 1; + updateNav(plotId, h); + return h.stack[h.cursor]; + }, + [commitPending, updateNav] + ); + + const canGoBack = useCallback( + (plotId: string): boolean => nav.get(plotId)?.canBack ?? false, + [nav] + ); + + const canGoForward = useCallback( + (plotId: string): boolean => nav.get(plotId)?.canForward ?? false, + [nav] + ); + + const clear = useCallback((plotId: string) => { + const timer = timerRef.current.get(plotId); + if (timer !== undefined) { + clearTimeout(timer); + timerRef.current.delete(plotId); + } + pendingRef.current.delete(plotId); + historyRef.current.delete(plotId); + setNav((prev) => { + if (!prev.has(plotId)) return prev; + const next = new Map(prev); + next.delete(plotId); + return next; + }); + }, []); + + return { push, goBack, goForward, canGoBack, canGoForward, clear }; +} diff --git a/src/traceLabel.test.ts b/src/traceLabel.test.ts new file mode 100644 index 0000000..97561d5 --- /dev/null +++ b/src/traceLabel.test.ts @@ -0,0 +1,18 @@ +import { describe, it, expect } from 'vitest'; +import { traceLabel } from './traceLabel'; + +function trace(overrides: Partial[0]> = {}) { + return { id: 't1', displayName: '', pvName: '', timeOffset: undefined, ...overrides }; +} + +describe('traceLabel with timeOffset', () => { + it('appends the formatted offset to the name', () => { + expect(traceLabel(trace({ pvName: 'PV:TEST', timeOffset: '-1d' }))).toBe('PV:TEST (−1 d)'); + expect(traceLabel(trace({ displayName: 'Sine', timeOffset: '-7d' }))).toBe('Sine (−1 w)'); + }); + + it('ignores invalid or missing offsets', () => { + expect(traceLabel(trace({ pvName: 'PV:TEST', timeOffset: 'bad' }))).toBe('PV:TEST'); + expect(traceLabel(trace({ pvName: 'PV:TEST' }))).toBe('PV:TEST'); + }); +}); diff --git a/src/traceLabel.ts b/src/traceLabel.ts index f112857..e610fd2 100644 --- a/src/traceLabel.ts +++ b/src/traceLabel.ts @@ -1,6 +1,7 @@ import type { PVTrace } from './types'; +import { parseOffsetMs, formatOffsetLabel } from './api/time'; -type TraceNames = Pick; +type TraceNames = Pick; // Stable numbering for unnamed traces. Once a trace ID is assigned a number it // keeps it for the session, so deleting a sibling doesn't shift labels. @@ -12,13 +13,20 @@ let nextNumber = 1; // displayName stays empty until the user types one, so a trace's label follows // its PV automatically until renamed. export function traceLabel(trace: TraceNames, siblings?: readonly TraceNames[]): string { - if (trace.displayName) return trace.displayName; - if (trace.pvName) return trace.pvName; - if (siblings) { + let base: string; + if (trace.displayName) base = trace.displayName; + else if (trace.pvName) base = trace.pvName; + else if (siblings) { if (!assignedNumbers.has(trace.id)) { assignedNumbers.set(trace.id, nextNumber++); } - return `New Trace ${assignedNumbers.get(trace.id)}`; + base = `New Trace ${assignedNumbers.get(trace.id)}`; + } else { + base = 'New Trace'; } - return 'New Trace'; + if (trace.timeOffset) { + const ms = parseOffsetMs(trace.timeOffset); + if (ms != null) return `${base} (${formatOffsetLabel(ms)})`; + } + return base; } diff --git a/src/types.ts b/src/types.ts index bf1b55e..97b464a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -23,6 +23,10 @@ export interface PVTrace { showArchiveBand?: boolean; // Per-curve archiver override; undefined means "use the global selection". archiver?: string; + // Relative time offset for historical comparison, e.g. "-1d", "-7d". + // When set, the trace fetches [from+offset, to+offset] and timestamps + // are shifted back onto the plot's axis. Implies archive-only (no live). + timeOffset?: string; // ── Formula curves (kind === 'formula') ────────────────────────────────── // Formula Engine expression with {var} placeholders, e.g. "{x1} + {x2}". expression?: string;