From 862bea22c58ff45ad23b97790102c400fc2671d0 Mon Sep 17 00:00:00 2001 From: tiffany-slac Date: Wed, 4 Nov 2026 17:48:00 -0800 Subject: [PATCH 1/6] DEV: add back/forward view history and reset zoom for plots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Per-plot undo/redo stack for view states (time window + Y-axis ranges) - Back/Forward buttons in the tab bar with Undo/Redo icons - Reset zoom button that restores full range, re-enables autoscroll, and resets all Y-axes to auto-scale (fixes #109) - Keyboard shortcuts: Alt+←/→ for back/forward, Alt+0 for reset zoom - 300ms coalesce timer so rapid zoom adjustments merge into one history entry - Reset zoom button per grid cell - Programmatic zoom restore via ECharts dispatchAction with zoomTarget prop - Session-only history, not persisted to workspaces --- src/App.css | 20 ++ src/components/PlotArea.tsx | 97 +++++++- src/components/TraceApp.tsx | 113 +++++++++ src/hooks/useKeyboardShortcuts.test.ts | 28 +++ src/hooks/useKeyboardShortcuts.ts | 6 + src/hooks/useViewHistory.test.ts | 309 +++++++++++++++++++++++++ src/hooks/useViewHistory.ts | 190 +++++++++++++++ 7 files changed, 757 insertions(+), 6 deletions(-) create mode 100644 src/hooks/useViewHistory.test.ts create mode 100644 src/hooks/useViewHistory.ts diff --git a/src/App.css b/src/App.css index a9dafa5..a9bb7ee 100644 --- a/src/App.css +++ b/src/App.css @@ -383,6 +383,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; @@ -432,6 +445,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/components/PlotArea.tsx b/src/components/PlotArea.tsx index 35972cf..5379557 100644 --- a/src/components/PlotArea.tsx +++ b/src/components/PlotArea.tsx @@ -1,13 +1,25 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import ReactECharts from 'echarts-for-react'; import { DARK_CHART_THEME, LIGHT_CHART_THEME, effectiveBackground } from '../chartTheme'; -import { Add, Close, ColumnDependency, Grid, Launch, Login, Maximize } from '@carbon/icons-react'; +import { + Add, + Close, + ColumnDependency, + Grid, + Launch, + Login, + Maximize, + Redo, + Undo, + ZoomReset, +} from '@carbon/icons-react'; import type { Axis, Plot, PVTrace } from '../types'; import type { ArchiveSeriesResult } from '../hooks/useArchiveSeries'; import type { LiveSeriesResult } from '../hooks/useLiveSeries'; import type { FormulaSeriesResult } from '../hooks/useFormulaSeries'; import type { TimeWindowNs } from '../api/time'; import { msToNs, nsToMs, resolveTimeWindow } from '../api/time'; +import { formatShortcut } from '../hooks/useKeyboardShortcuts'; import { echartsLineType, echartsSymbol } from '../curveStyle'; import { isFollowing } from '../hooks/useAutoScrollTimers'; import { useFollowNow } from '../hooks/useFollowNow'; @@ -76,6 +88,13 @@ interface PlotAreaProps { onUpdateAxis?: (plotId: string, axisId: string, updates: Partial) => void; /** Publishes each plot's ECharts instance for PNG capture (active=false on unmount). */ onChartInstance?: (plotId: string, instance: PngSource, active: boolean) => void; + onViewBack?: (plotId: string) => void; + onViewForward?: (plotId: string) => void; + onResetZoom?: (plotId: string) => void; + canGoBack?: (plotId: string) => boolean; + canGoForward?: (plotId: string) => boolean; + /** Per-plot zoom target for programmatic navigation (back/forward/reset). */ + zoomTargetByPlot?: Map; } // Shown in the main window where a detached plot's chart would otherwise be. @@ -139,6 +158,8 @@ interface SinglePlotProps { * match by identity (a plot can be mounted twice, e.g. grid + fullscreen). */ onChartInstance?: (instance: PngSource, active: boolean) => void; + /** When generation bumps, programmatically zoom to window (null = full range). */ + zoomTarget?: { window: TimeWindowNs | null; generation: number }; } function formatCrosshairTime(ms: number): string { @@ -251,6 +272,7 @@ export function SinglePlot({ onUpdateAxis, fullscreen, onChartInstance, + zoomTarget, }: SinglePlotProps) { const { colorMode } = useColorMode(); const theme = colorMode === 'dark' ? DARK_CHART_THEME : LIGHT_CHART_THEME; @@ -368,16 +390,14 @@ export function SinglePlot({ }); } + const useTyped = !tracesWithInvalid.has(trace.id); series.push({ id: trace.id, name: labels.get(trace.id), type: 'line', yAxisIndex, - // Typed unless it has to break at an INVALID sample: the nulls and - // step-line hold points need plain point data. - data: tracesWithInvalid.has(trace.id) - ? gappedLineData(points, (p) => p.value, step) - : xyData(points), + data: useTyped ? xyData(points) : gappedLineData(points, (p) => p.value, step), + ...(useTyped ? { dimensions: ['x', 'y'] } : {}), step: step ? 'end' : false, lineStyle: { color: trace.color, @@ -525,6 +545,31 @@ export function SinglePlot({ } : null; + // Navigate to a specific view when the parent bumps `zoomTarget.generation` + // (back/forward/reset). Uses the same programmaticZoomRef guard so the + // resulting datazoom event isn't mistaken for a user pan. + const zoomGenRef = useRef(zoomTarget?.generation ?? 0); + useEffect(() => { + if (!zoomTarget || zoomTarget.generation === zoomGenRef.current) return; + zoomGenRef.current = zoomTarget.generation; + const inst = chartRef.current?.getEchartsInstance(); + if (!inst || !inst.getDom()) return; + programmaticZoomRef.current = true; + if (zoomTarget.window) { + inst.dispatchAction({ + type: 'dataZoom', + startValue: nsToMs(zoomTarget.window.fromNs), + endValue: nsToMs(zoomTarget.window.toNs), + }); + } else { + inst.dispatchAction({ type: 'dataZoom', start: 0, end: 100 }); + } + const clearTimer = window.setTimeout(() => { + programmaticZoomRef.current = false; + }, 0); + return () => window.clearTimeout(clearTimer); + }, [zoomTarget]); + const handleFinished = useCallback(() => { if (!onAxisRangesChange) return; const inst = chartRef.current?.getEchartsInstance(); @@ -837,6 +882,7 @@ export function SinglePlot({ type: 'line', yAxisIndex, data, + dimensions: ['x', 'y'], lineStyle: { color: trace.color, width: trace.lineWidth, @@ -1082,6 +1128,12 @@ export function PlotArea({ onAxisRangesChange, onUpdateAxis, onChartInstance, + onViewBack, + onViewForward, + onResetZoom, + canGoBack, + canGoForward, + zoomTargetByPlot, }: PlotAreaProps) { const activePlot = plots.find((p) => p.id === activePlotId) ?? plots[0]; const isDetached = (id: string) => detachedPlotIds.includes(id); @@ -1148,6 +1200,30 @@ export function PlotArea({
+ + + +
+ {plots.length > 1 && (
diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index e9c1752..2f545e9 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -38,6 +38,7 @@ import { capturePlots, type PngSource, type CapturedPlot } from '../io/exportPlo import { PostToElogModal } from './PostToElogModal'; import { useElogConfig } from '../hooks/useElogConfig'; import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts'; +import { useViewHistory, type ViewSnapshot, type AxisSnapshot } from '../hooks/useViewHistory'; const BUG_REPORT_URL = 'https://forms.office.com/r/qV7BmK2xi9'; const DOCS_URL = 'https://fuzzy-adventure-4qvly8m.pages.github.io/'; @@ -137,6 +138,10 @@ export function TraceApp() { const [viewWindowByPlot, setViewWindowByPlot] = useState>( () => new Map() ); + const viewHistory = useViewHistory(); + const [zoomTargetByPlot, setZoomTargetByPlot] = useState< + Map + >(() => new Map()); const leftPanelRef = usePanelRef(); const rightPanelRef = usePanelRef(); // In-flight units lookups per trace, so a rapid PV re-selection aborts the @@ -185,6 +190,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); @@ -194,6 +206,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, @@ -337,6 +354,7 @@ 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); if (activePlotId === plotId) { const remaining = plots.filter((p) => p.id !== plotId); setActivePlotId(remaining[0].id); @@ -401,6 +419,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 ───────────────────────────────────────────────────────── const addTrace = (plotId: string, axisId: string) => { @@ -713,6 +804,15 @@ export function TraceApp() { : p ) ); + const plot = plots.find((p) => p.id === plotId); + const axisRanges = snapshotAxes(plot); + const existing = axisRanges.get(axisId); + if (existing) axisRanges.set(axisId, { ...existing, ...updates }); + viewHistory.push(plotId, { + timeWindow: viewWindowByPlot.get(plotId) ?? null, + axisRanges, + autoScroll: plot?.autoScroll !== false, + }); }; const liveCount = activePlot.traces.filter((t) => t.useLive).length; @@ -910,6 +1010,9 @@ export function TraceApp() { onPostElog: elogConfig?.enabled ? openElogPost : undefined, onDataInsight: () => openInsight(), onToggleTheme: toggleTheme, + onViewBack: () => handleViewBack(activePlotId), + onViewForward: () => handleViewForward(activePlotId), + onResetZoom: () => handleResetZoom(activePlotId), }); return ( @@ -1011,6 +1114,12 @@ export function TraceApp() { onAxisRangesChange={handleAxisRangesChange} onUpdateAxis={updateAxisInPlot} onChartInstance={handleChartInstance} + onViewBack={handleViewBack} + onViewForward={handleViewForward} + onResetZoom={handleResetZoom} + canGoBack={viewHistory.canGoBack} + canGoForward={viewHistory.canGoForward} + zoomTargetByPlot={zoomTargetByPlot} />
{insight.open && !insight.detached && insight.minimized && ( @@ -1159,11 +1268,14 @@ 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)} // eslint-disable-next-line react-hooks/refs -- ref is written on mount/unmount, not during render onChartInstance={(inst, active) => handleChartInstance(plot.id, inst, active)} + zoomTarget={zoomTargetByPlot.get(plot.id)} /> @@ -1262,6 +1374,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 }; +} From a9f643e296d781856369a8a035d806214c4f71df Mon Sep 17 00:00:00 2001 From: tiffany-slac Date: Thu, 5 Nov 2026 15:01:58 -0800 Subject: [PATCH 2/6] FIX: view history cleanup, stale state, & effect dependency - Clean up zoomTargetByPlot entries when a plot is removed - Read post-update plots inside setPlots updater in updateAxisInPlot so the history snapshot reflects the actual axis state - Narrow useEffect dependency from full zoomTarget object to zoomTarget?.generation to avoid unnecessary effect runs --- src/components/PlotArea.tsx | 2 +- src/components/TraceApp.tsx | 29 +++++++++++++++++------------ 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/components/PlotArea.tsx b/src/components/PlotArea.tsx index 5379557..9e29229 100644 --- a/src/components/PlotArea.tsx +++ b/src/components/PlotArea.tsx @@ -568,7 +568,7 @@ export function SinglePlot({ programmaticZoomRef.current = false; }, 0); return () => window.clearTimeout(clearTimer); - }, [zoomTarget]); + }, [zoomTarget?.generation]); const handleFinished = useCallback(() => { if (!onAxisRangesChange) return; diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index 2f545e9..31dd553 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -355,6 +355,12 @@ export function TraceApp() { 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); @@ -794,24 +800,23 @@ 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 = plots.find((p) => p.id === plotId); - const axisRanges = snapshotAxes(plot); - const existing = axisRanges.get(axisId); - if (existing) axisRanges.set(axisId, { ...existing, ...updates }); - viewHistory.push(plotId, { - timeWindow: viewWindowByPlot.get(plotId) ?? null, - axisRanges, - autoScroll: plot?.autoScroll !== false, + ); + 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; }); }; From 4cb0e1c4422791905c6671ed5250247040a769d0 Mon Sep 17 00:00:00 2001 From: tiffany-slac Date: Mon, 9 Nov 2026 13:56:06 -0800 Subject: [PATCH 3/6] DEV: per-trace time offset for historical comparison MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add timeOffset field to PVTrace for offsets like "-1d", "-7d" - Offset traces fetch [from+offset, to+offset] and shift timestamps onto the plot's axis - Legend and tooltip show the offset, e.g. "PV:TEST (−1 d)" - "Duplicate with offset" action via clock icon on trace rows with preset and custom offsets - Offset traces are archive-only (live data disabled) - Offset traces use dashed line style to distinguish from the original - Time Offset input in RightPanel General tab with validation --- src/api/time.test.ts | 31 +++++- src/api/time.ts | 27 +++++ src/components/LeftPanel.test.tsx | 1 + src/components/LeftPanel.tsx | 167 ++++++++++++++++++++++++++++++ src/components/PlotArea.tsx | 64 ++++++++---- src/components/RightPanel.tsx | 22 +++- src/components/TraceApp.tsx | 48 ++++++++- src/traceLabel.test.ts | 18 ++++ src/traceLabel.ts | 20 ++-- src/types.ts | 4 + 10 files changed, 368 insertions(+), 34 deletions(-) create mode 100644 src/traceLabel.test.ts 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 486587a..0641c48 100644 --- a/src/api/time.ts +++ b/src/api/time.ts @@ -46,6 +46,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 f71f842..491b2e8 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()} onDeleteAxis={vi.fn()} onMoveTrace={vi.fn()} diff --git a/src/components/LeftPanel.tsx b/src/components/LeftPanel.tsx index d2c0b18..d8881b0 100644 --- a/src/components/LeftPanel.tsx +++ b/src/components/LeftPanel.tsx @@ -23,8 +23,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'; @@ -55,6 +57,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; onDeleteAxis: (plotId: string, axisId: string) => void; onMoveTrace: ( @@ -102,6 +105,118 @@ 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 validCustom = !!custom && parseOffsetMs(custom) != null; + const submitCustom = () => { + if (validCustom) { + onSelect(custom); + onClose(); + } + }; + + return ( +
e.stopPropagation()} + onKeyDown={(e) => { + if (e.key === 'Escape') onClose(); + }} + style={{ + position: 'absolute', + top: '100%', + right: 0, + zIndex: 100, + background: 'var(--cds-layer)', + border: '1px solid var(--cds-border-subtle)', + borderRadius: 4, + padding: 8, + boxShadow: '0 2px 6px rgba(0,0,0,0.2)', + minWidth: 140, + }} + > +
+ Compare with +
+ {OFFSET_PRESETS.map((preset) => ( + + ))} +
+ setCustom(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') submitCustom(); + }} + style={{ + flex: 1, + fontSize: 11, + padding: '2px 4px', + border: '1px solid var(--cds-border-strong)', + borderRadius: 2, + background: 'var(--cds-field)', + color: 'var(--cds-text-primary)', + minWidth: 0, + }} + /> + +
+
+ ); +} + interface TraceRowProps { trace: PVTrace; label: string; @@ -110,6 +225,7 @@ interface TraceRowProps { isSelected: boolean; onSelect: () => void; onDelete: () => void; + onDuplicateWithOffset?: (offset: string) => void; } function TraceRow({ @@ -120,7 +236,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}`, @@ -132,6 +250,8 @@ function TraceRow({ transition, }; + const canDuplicate = onDuplicateWithOffset && trace.kind !== 'formula' && !!trace.pvName; + return (
+ {canDuplicate && ( +
+ + {showOffsetPopover && ( + onDuplicateWithOffset!(offset)} + onClose={() => setShowOffsetPopover(false)} + /> + )} +
+ )} ))} -
+
setCustom(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') submitCustom(); }} - style={{ - flex: 1, - fontSize: 11, - padding: '2px 4px', - border: '1px solid var(--cds-border-strong)', - borderRadius: 2, - background: 'var(--cds-field)', - color: 'var(--cds-text-primary)', - minWidth: 0, - }} /> -
@@ -279,33 +265,14 @@ function TraceRow({
{canDuplicate && ( -
+
e.stopPropagation()}> diff --git a/src/components/TraceApp.tsx b/src/components/TraceApp.tsx index 6b30e0b..3c7e5cb 100644 --- a/src/components/TraceApp.tsx +++ b/src/components/TraceApp.tsx @@ -63,6 +63,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[] = [ { @@ -649,17 +656,15 @@ export function TraceApp() { const source = plot?.traces.find((t) => t.id === sourceTraceId); if (!plot || !source) return; const id = makeId('trace'); - const newTrace: PVTrace = { + const newTrace: PVTrace = enforceOffsetArchiveOnly({ ...source, id, color: colorForIndex(getPalette(paletteId), plot.traces.length), - displayName: '', + displayName: source.displayName, timeOffset: offset, lineStyle: 'dashed', - useLive: false, - useArchive: true, data: [], - }; + }); setPlots((prev) => prev.map((p) => (p.id === plotId ? { ...p, traces: [...p.traces, newTrace] } : p)) ); @@ -667,15 +672,17 @@ export function TraceApp() { }; const updateTrace = (traceId: string, updates: Partial) => { - if (updates.timeOffset && parseOffsetMs(updates.timeOffset) != null) { - updates = { ...updates, useLive: false, useArchive: true }; + 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 ) @@ -908,7 +915,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)); From 6443471b527be2c5394f25ea758c8182e558b64f Mon Sep 17 00:00:00 2001 From: tiffany-slac Date: Thu, 19 Nov 2026 14:51:15 -0800 Subject: [PATCH 5/6] DOC: add time offset comparison to user guide - Document the "Compare with a Time Offset" feature: creating offset traces, how they display, editing/removing offsets --- docs/users/user_guide.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/docs/users/user_guide.md b/docs/users/user_guide.md index af0a577..afaa6cc 100644 --- a/docs/users/user_guide.md +++ b/docs/users/user_guide.md @@ -223,6 +223,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. From 5ee52e93536272fe312fd2c9ca40e7ecaa0388b4 Mon Sep 17 00:00:00 2001 From: tiffany-slac Date: Thu, 19 Nov 2026 15:49:00 -0800 Subject: [PATCH 6/6] FIX: formatting for PlotArea zoom target effect - Add missing zoomTarget and liveChart dependencies to useEffect - Run prettier on PlotArea.tsx --- src/components/PlotArea.tsx | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/components/PlotArea.tsx b/src/components/PlotArea.tsx index 7a55cdd..3c02bea 100644 --- a/src/components/PlotArea.tsx +++ b/src/components/PlotArea.tsx @@ -15,7 +15,18 @@ import { } from '@slaclab/canopy-charts'; import { effectiveBackground } from '../plotBackground'; import { registerPlotChart } from '../capturePlot'; -import { Add, Close, ColumnDependency, Grid, Launch, Login, Maximize, Redo, Undo, ZoomReset } from '@carbon/icons-react'; +import { + Add, + Close, + ColumnDependency, + Grid, + Launch, + Login, + Maximize, + Redo, + Undo, + ZoomReset, +} from '@carbon/icons-react'; import type { Axis, Plot, PVTrace } from '../types'; import type { ArchiveSeriesResult } from '../hooks/useArchiveSeries'; import type { LiveSeriesResult } from '../hooks/useLiveSeries'; @@ -649,7 +660,7 @@ export function SinglePlot({ programmaticZoomRef.current = false; }, 0); return () => window.clearTimeout(clearTimer); - }, [zoomTarget?.generation]); + }, [zoomTarget, liveChart]); // Chart event handlers get the chart that fired the event. CanopyChart drops // events from a disposed chart before they reach us; both handlers also @@ -668,7 +679,6 @@ export function SinglePlot({ [onAxisRangesChange, visibleAxes] ); - const handleDataZoom = useCallback( (_params: unknown, chart: ECharts) => { // An event from a chart without a model isn't the user's pan: don't let