diff --git a/src/App.css b/src/App.css index 9766a43..7427f30 100644 --- a/src/App.css +++ b/src/App.css @@ -397,6 +397,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 +459,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 1156a91..9d3d62e 100644 --- a/src/components/PlotArea.tsx +++ b/src/components/PlotArea.tsx @@ -13,15 +13,27 @@ import { formatValue, useChartTheme, } from '@slaclab/canopy-charts'; +import { + Add, + Close, + ColumnDependency, + Grid, + Launch, + Login, + Maximize, + Redo, + Undo, + ZoomReset, +} from '@carbon/icons-react'; import { effectiveBackground } from '../plotBackground'; import { registerPlotChart } from '../capturePlot'; -import { Add, Close, ColumnDependency, Grid, Launch, Login, Maximize } 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, isMac } from '../hooks/useKeyboardShortcuts'; import { echartsLineType, echartsSymbol } from '../curveStyle'; import { isFollowing } from '../hooks/useAutoScrollTimers'; import { useFollowNow } from '../hooks/useFollowNow'; @@ -103,6 +115,14 @@ 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; + canReset?: (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. @@ -166,6 +186,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 { @@ -301,6 +323,7 @@ export function SinglePlot({ onUpdateAxis, fullscreen, onChartInstance, + zoomTarget, }: SinglePlotProps) { // Carbon g10/g100 chart colors for the current canopy-shell color mode. const theme = useChartTheme(); @@ -599,6 +622,32 @@ 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 = liveChart(); + if (!inst) 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); + // eslint-disable-next-line react-hooks/exhaustive-deps -- fire only on generation bump, not on window content changes + }, [zoomTarget?.generation, 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 // ignore a chart without a model (not built yet, or disposed), so neither @@ -1149,6 +1198,13 @@ export function PlotArea({ onAxisRangesChange, onUpdateAxis, onChartInstance, + onViewBack, + onViewForward, + onResetZoom, + canGoBack, + canGoForward, + canReset, + zoomTargetByPlot, }: PlotAreaProps) { const activePlot = plots.find((p) => p.id === activePlotId) ?? plots[0]; const isDetached = (id: string) => detachedPlotIds.includes(id); @@ -1215,6 +1271,34 @@ export function PlotArea({
+ + + +
+ {plots.length > 1 && (
@@ -1342,6 +1490,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 +1592,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..b62d85e 100644 --- a/src/hooks/useKeyboardShortcuts.test.ts +++ b/src/hooks/useKeyboardShortcuts.test.ts @@ -61,6 +61,66 @@ describe('resolveShortcut', () => { }); }); + describe('view history shortcuts', () => { + describe('macOS: ⌥← / ⌥→', () => { + it('maps Alt+ArrowLeft to viewBack', () => { + expect(resolveShortcut(ev({ key: 'ArrowLeft', altKey: true }), true)).toBe('onViewBack'); + }); + + it('maps Alt+ArrowRight to viewForward', () => { + expect(resolveShortcut(ev({ key: 'ArrowRight', altKey: true }), true)).toBe( + 'onViewForward' + ); + }); + + it('does not bind Alt+Arrow on non-Mac (browser Back/Forward conflict)', () => { + expect(resolveShortcut(ev({ key: 'ArrowLeft', altKey: true }), false)).toBeNull(); + expect(resolveShortcut(ev({ key: 'ArrowRight', altKey: true }), false)).toBeNull(); + }); + + it('does not match Alt+Arrow when primary modifier is also held', () => { + expect( + resolveShortcut(ev({ key: 'ArrowLeft', altKey: true, metaKey: true }), true) + ).toBeNull(); + }); + + it('does not match arrow keys without Alt', () => { + expect(resolveShortcut(ev({ key: 'ArrowLeft' }), true)).toBeNull(); + expect(resolveShortcut(ev({ key: 'ArrowRight' }), true)).toBeNull(); + }); + }); + + describe('non-Mac: Ctrl+[ / Ctrl+]', () => { + it('maps Ctrl+[ to viewBack', () => { + expect(resolveShortcut(ev({ key: '[', ctrlKey: true }), false)).toBe('onViewBack'); + }); + + it('maps Ctrl+] to viewForward', () => { + expect(resolveShortcut(ev({ key: ']', ctrlKey: true }), false)).toBe('onViewForward'); + }); + + it('does not bind Ctrl+[/] on macOS (⌥Arrow is used instead)', () => { + expect(resolveShortcut(ev({ key: '[', metaKey: true }), true)).toBeNull(); + expect(resolveShortcut(ev({ key: ']', metaKey: true }), true)).toBeNull(); + }); + }); + + describe('reset zoom: Alt+0 (all platforms)', () => { + it('maps Alt+0 to resetZoom', () => { + expect(resolveShortcut(ev({ key: '0', altKey: true }), false)).toBe('onResetZoom'); + expect(resolveShortcut(ev({ key: '0', code: 'Digit0', altKey: true }), true)).toBe( + 'onResetZoom' + ); + }); + + it('maps Alt+0 via code when Option changes key on macOS', () => { + expect(resolveShortcut(ev({ key: 'º', code: 'Digit0', altKey: true }), true)).toBe( + 'onResetZoom' + ); + }); + }); + }); + 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..4b2ffb5 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. */ @@ -37,7 +40,8 @@ export function formatShortcut(mod: Mod, key: string): string { } // Bindings: (modifier group, lowercase key) → the handler it invokes. -const BINDINGS: { mod: Mod; key: string; action: Action }[] = [ +// `platform` restricts a binding to macOS ('mac') or non-Mac ('other'). +const BINDINGS: { mod: Mod; key: string; action: Action; platform?: 'mac' | 'other' }[] = [ { mod: 'primary', key: 's', action: 'onSave' }, { mod: 'primary', key: 'p', action: 'onPrint' }, { mod: 'primary', key: 'e', action: 'onPostElog' }, @@ -45,6 +49,13 @@ 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' }, + // Alt+Arrow is browser Back/Forward on Windows/Linux → macOS only. + // Non-Mac gets Ctrl+[ / Ctrl+] instead (no browser conflict). + { mod: 'alt', key: 'arrowleft', action: 'onViewBack', platform: 'mac' }, + { mod: 'alt', key: 'arrowright', action: 'onViewForward', platform: 'mac' }, + { mod: 'primary', key: '[', action: 'onViewBack', platform: 'other' }, + { mod: 'primary', key: ']', action: 'onViewForward', platform: 'other' }, + { mod: 'alt', key: '0', action: 'onResetZoom' }, ]; /** The event fields a shortcut match depends on. */ @@ -66,13 +77,18 @@ export interface KeyEventLike { export function resolveShortcut(e: KeyEventLike, mac: boolean): Action | null { if (e.shiftKey) return null; const primary = mac ? e.metaKey : e.ctrlKey; - // Option/Alt can change e.key on some keyboard layouts (e.g. Option+T => † - // on macOS). Prefer physical letter keys via e.code when available. - const keyFromCode = - typeof e.code === 'string' && /^Key[A-Z]$/.test(e.code) ? e.code.slice(3).toLowerCase() : ''; + // Option/Alt can change e.key on some keyboard layouts (e.g. Option+T => †, + // Option+0 => º on macOS). Prefer physical keys via e.code when available. + let keyFromCode = ''; + if (typeof e.code === 'string') { + if (/^Key[A-Z]$/.test(e.code)) keyFromCode = e.code.slice(3).toLowerCase(); + else if (/^Digit[0-9]$/.test(e.code)) keyFromCode = e.code.slice(5); + } const key = keyFromCode || e.key.toLowerCase(); for (const b of BINDINGS) { if (b.key !== key) continue; + if (b.platform === 'mac' && !mac) continue; + if (b.platform === 'other' && mac) continue; const modMatches = b.mod === 'primary' ? primary && !e.altKey : e.altKey && !primary; if (modMatches) return b.action; } diff --git a/src/hooks/useViewHistory.test.ts b/src/hooks/useViewHistory.test.ts new file mode 100644 index 0000000..a335b2a --- /dev/null +++ b/src/hooks/useViewHistory.test.ts @@ -0,0 +1,452 @@ +// @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('seeds a baseline so the first zoom can be undone', () => { + const { result } = renderHook(() => useViewHistory()); + const baseline = snapAt(0, 100); + const zoom = snapAt(50, 75); + + act(() => { + result.current.push('p1', zoom, baseline); + vi.advanceTimersByTime(300); + }); + + expect(result.current.canGoBack('p1')).toBe(true); + + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goBack('p1'); + }); + expect(restored!.timeWindow).toEqual({ fromNs: 0, toNs: 100 }); + }); + + it('seedBaseline seeds once on an empty history', () => { + const { result } = renderHook(() => useViewHistory()); + const baseline = snap({ autoScroll: true, timeWindow: { fromNs: 0, toNs: 100 } }); + + act(() => { + result.current.seedBaseline('p1', baseline); + }); + + // Baseline is entry 0 — nothing to go back to yet + expect(result.current.canGoBack('p1')).toBe(false); + + // Push a zoom; going back should return the seeded baseline + act(() => { + result.current.push('p1', snapAt(50, 75)); + vi.advanceTimersByTime(300); + }); + + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goBack('p1'); + }); + expect(restored!.timeWindow).toEqual({ fromNs: 0, toNs: 100 }); + expect(restored!.autoScroll).toBe(true); + }); + + it('seedBaseline is a no-op when history already exists', () => { + const { result } = renderHook(() => useViewHistory()); + + act(() => { + result.current.push('p1', snapAt(0, 100)); + vi.advanceTimersByTime(300); + }); + + // Attempt to seed after history exists — should be ignored + act(() => { + result.current.seedBaseline( + 'p1', + snap({ autoScroll: true, timeWindow: { fromNs: 999, toNs: 1000 } }) + ); + }); + + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goBack('p1'); + }); + // No second entry was added, so goBack returns null + expect(restored).toBeNull(); + }); + + it('seedBaseline is a no-op when a pending push exists', () => { + const { result } = renderHook(() => useViewHistory()); + + // Push without waiting for coalesce — creates a pending entry + act(() => { + result.current.push('p1', snapAt(50, 75)); + }); + + // seedBaseline should be skipped because pending exists + act(() => { + result.current.seedBaseline( + 'p1', + snap({ autoScroll: true, timeWindow: { fromNs: 0, toNs: 100 } }) + ); + }); + + // Let the coalesce timer fire + act(() => { + vi.advanceTimersByTime(300); + }); + + // Only one entry (the pushed one), no baseline was added + expect(result.current.canGoBack('p1')).toBe(false); + }); + + it('does not seed baseline when history already exists', () => { + const { result } = renderHook(() => useViewHistory()); + + act(() => { + result.current.push('p1', snapAt(0, 100)); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p1', snapAt(100, 200), snapAt(50, 150)); + vi.advanceTimersByTime(300); + }); + + // Go back should return entry 0, not the baseline (which was ignored) + let restored: ViewSnapshot | null = null; + act(() => { + restored = result.current.goBack('p1'); + }); + expect(restored!.timeWindow).toEqual({ fromNs: 0, toNs: 100 }); + }); + + it('clearAll removes history for all plots', () => { + 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(0, 50)); + vi.advanceTimersByTime(300); + }); + act(() => { + result.current.push('p2', snapAt(50, 100)); + vi.advanceTimersByTime(300); + }); + + act(() => { + result.current.clearAll(); + }); + + expect(result.current.canGoBack('p1')).toBe(false); + expect(result.current.canGoBack('p2')).toBe(false); + expect(result.current.goBack('p1')).toBeNull(); + expect(result.current.goBack('p2')).toBeNull(); + }); + + 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..149f717 --- /dev/null +++ b/src/hooks/useViewHistory.ts @@ -0,0 +1,215 @@ +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, baseline?: ViewSnapshot): void; + seedBaseline(plotId: string, baseline: ViewSnapshot): void; + goBack(plotId: string): ViewSnapshot | null; + goForward(plotId: string): ViewSnapshot | null; + canGoBack(plotId: string): boolean; + canGoForward(plotId: string): boolean; + clear(plotId: string): void; + clearAll(): 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 seedBaseline = useCallback( + (plotId: string, baseline: ViewSnapshot) => { + const h = getOrCreate(plotId); + if (h.stack.length > 0 || pendingRef.current.has(plotId)) return; + h.stack.push(baseline); + h.cursor = 0; + updateNav(plotId, h); + }, + [getOrCreate, updateNav] + ); + + const push = useCallback( + (plotId: string, snapshot: ViewSnapshot, baseline?: ViewSnapshot) => { + if (baseline) seedBaseline(plotId, baseline); + + 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, seedBaseline] + ); + + 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; + }); + }, []); + + const clearAll = useCallback(() => { + for (const timer of timerRef.current.values()) { + clearTimeout(timer); + } + timerRef.current.clear(); + pendingRef.current.clear(); + historyRef.current.clear(); + setNav(new Map()); + }, []); + + return { push, seedBaseline, goBack, goForward, canGoBack, canGoForward, clear, clearAll }; +}