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 efc2152cd0f48ac588cc40f74ba0c088ba1a960c Mon Sep 17 00:00:00 2001 From: tiffany-slac Date: Tue, 17 Nov 2026 10:42:54 -0800 Subject: [PATCH 3/6] FIX: address view history review feedback (PR #172) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Seed baseline entry on first zoom/axis change so it can be undone - Push post-reset state in handleResetZoom so reset is undoable - Add clearAll() to useViewHistory, call from applyWorkspace with zoomTargetByPlot reset to avoid stale history across workspace loads - Extend resolveShortcut to handle Digit[0-9] codes (fixes ⌥0 on macOS) - Platform-aware back/forward shortcuts: ⌥←/⌥→ on macOS, Ctrl+[/] on non-Mac to avoid browser Back/Forward conflict on Alt+Arrow - Add eslint-disable-next-line for intentional exhaustive-deps in PlotArea - Add aria-label to icon-only view history and reset zoom buttons - Move viewHistory.push out of setPlots updater in updateAxisInPlot --- src/components/PlotArea.tsx | 11 +++- src/components/TraceApp.tsx | 73 +++++++++++++++-------- src/hooks/useKeyboardShortcuts.test.ts | 82 ++++++++++++++++++-------- src/hooks/useKeyboardShortcuts.ts | 24 +++++--- src/hooks/useViewHistory.test.ts | 69 ++++++++++++++++++++++ src/hooks/useViewHistory.ts | 30 ++++++++-- 6 files changed, 224 insertions(+), 65 deletions(-) diff --git a/src/components/PlotArea.tsx b/src/components/PlotArea.tsx index cb85e71..3541b07 100644 --- a/src/components/PlotArea.tsx +++ b/src/components/PlotArea.tsx @@ -19,7 +19,7 @@ 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 { formatShortcut, isMac } from '../hooks/useKeyboardShortcuts'; import { echartsLineType, echartsSymbol } from '../curveStyle'; import { isFollowing } from '../hooks/useAutoScrollTimers'; import { useFollowNow } from '../hooks/useFollowNow'; @@ -589,6 +589,7 @@ export function SinglePlot({ programmaticZoomRef.current = false; }, 0); return () => window.clearTimeout(clearTimer); + // eslint-disable-next-line react-hooks/exhaustive-deps -- fire only on generation bump, not on window content changes }, [zoomTarget?.generation]); const handleFinished = useCallback(() => { @@ -1225,7 +1226,8 @@ export function PlotArea({