Skip to content

DEV: add back/forward view history and reset zoom for plots - #172

Merged
tiffany-slac merged 8 commits into
mainfrom
tiffany/view-history
Nov 20, 2026
Merged

tiffany-slac merged 8 commits into
mainfrom
tiffany/view-history

Conversation

@YektaY

@YektaY YektaY commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator

Originally opened by tiffany-slac as slaclab/react-trace-archive#172. Its review history and CI runs stay in the archive.

Description

Snapshots are captured after each zoom or pan settles. Each snapshot stores the visible time window and every Y-axis range (min, max, auto-scale). History is held in-memory (React refs). Reset zoom restores the default state: autoscroll on, all Y-axes auto-scaled, full time range visible

  • 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 [BUG] - Switching Autoscroll back on doesn't undo a pan or zoom #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

Motivation

Closes #125

Screenshots

Screenshot 2026-11-05 at 9 01 04 AM
Screen.Recording.2026-11-05.at.8.53.52.AM.mov

Pre-merge checklist

  • Code works interactively in the browser
  • New/changed components are covered in the test suite where possible
  • Test suite passes locally (npm test)
  • Linting passes (npm run lint)
  • Test suite passes on GitHub Actions

tiffany-slac and others added 3 commits November 4, 2026 17:48
- 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
- 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
@YektaY
YektaY requested a review from a team as a code owner November 12, 2026 06:33

@jbellister-slac jbellister-slac left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! I tested the new functionality myself, as well as having Claude look over it. Notes from it below, confirmed most of what it said manually as well.

Comment thread src/components/TraceApp.tsx Outdated
// 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, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The first zoom cannot be undone. This pushes the state after the zoom, and nothing ever records the view the plot had before the first interaction. After one zoom the stack is [z1] with the cursor at 0, so Back stays disabled. The hook test "deduplicates identical consecutive snapshots" shows the same shape: one committed entry means canGoBack is false.

The same applies to the first Y-axis change through updateAxisInPlot: the original auto-scale state is not in the stack.

One way to fix it: when a plot has no history yet, seed a baseline entry with the pre-change state (current view window or null, current axes, current autoScroll) before pushing the new one. The baseline must bypass the coalesce timer, otherwise the second push replaces it.

Comment thread src/components/TraceApp.tsx Outdated

const handleResetZoom = (plotId: string) => {
const plot = plots.find((p) => p.id === plotId);
viewHistory.push(plotId, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Back after Reset skips an entry, and Reset cannot be undone. Every other call site pushes the state after the change; this one pushes the state before the reset and never pushes the reset view.

  • Zoom A, zoom B, Reset: the stack is [A, B] and this push equals B, so it is deduplicated. Back then moves the cursor to A, not to B (the view that was on screen before Reset).
  • Zoom A, Reset: the stack is [A], the push is deduplicated, and Back is disabled. Reset also clears every manual Y min/max, so those limits cannot be recovered.
  • The reset view is never an entry, so Forward can never return to it.

With a baseline entry in place (see the comment on L233), pushing the post-reset state here (timeWindow: null, all axes auto-scaled, autoScroll: true) makes Reset an ordinary undoable step.

setPlots((prev) => prev.filter((p) => p.id !== plotId));
if (poppedOutPlot === plotId) setPoppedOutPlot(null);
setDetachedPlotIds((prev) => prev.filter((id) => id !== plotId));
viewHistory.clear(plotId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

History is cleared when a plot is removed, but not when a workspace is applied. applyWorkspace resets everything else keyed by plot id (viewWindowByPlot, detach state, selection, axisRangesRef), and its comment explains why: ids collide across workspaces (plot-1). viewHistory and zoomTargetByPlot are not reset there, so after a load the new plot-1 has Back enabled and restoring applies the previous workspace's time window and axis ranges (axis ids collide as well).

The hook could have a clearAll() (cancel all timers, drop pending and history, reset nav) called from applyWorkspace, together with setZoomTargetByPlot(new Map()).

{ mod: 'alt', key: 't', action: 'onToggleTheme' },
{ mod: 'alt', key: 'arrowleft', action: 'onViewBack' },
{ mod: 'alt', key: 'arrowright', action: 'onViewForward' },
{ mod: 'alt', key: '0', action: 'onResetZoom' },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This binding does not match on macOS. Option+0 produces e.key === 'º' on a US layout, and the e.code fallback in resolveShortcut only covers Key[A-Z], so Digit0 falls through. The tooltip still advertises ⌥0. The test "maps Alt+0 to resetZoom" passes for mac = true only because it supplies a synthetic key: '0'.

Extending the fallback to /^Digit[0-9]$/ fixes it; the test should pass code: 'Digit0' with the real key value.

Comment thread src/hooks/useKeyboardShortcuts.ts Outdated
{ mod: 'primary', key: 'i', action: 'onExportImage' },
{ mod: 'alt', key: 'd', action: 'onDataInsight' },
{ mod: 'alt', key: 't', action: 'onToggleTheme' },
{ mod: 'alt', key: 'arrowleft', action: 'onViewBack' },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: Alt+Left and Alt+Right are browser Back/Forward in Chrome and Firefox on Windows and Linux. The handlers are always wired, so preventDefault always fires outside form fields and the browser shortcut is lost. Inside a form field the listener returns early, so the same keys navigate the browser away from the app instead.

Comment thread src/components/PlotArea.tsx Outdated
programmaticZoomRef.current = false;
}, 0);
return () => window.clearTimeout(clearTimer);
}, [zoomTarget?.generation]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: eslint reports react-hooks/exhaustive-deps here (missing zoomTarget). Depending on the generation only is deliberate, so this needs an eslint-disable-next-line with a reason, like the other intentional cases in this file.

Comment thread src/components/PlotArea.tsx Outdated
<div className="plot-tab-bar__controls">
<button
className="view-mode-btn"
title={`Back (${formatShortcut('alt', '←')})`}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: the three new icon-only buttons (and the grid-cell reset button) have a title but no aria-label.

tiffany-slac and others added 3 commits November 17, 2026 10:42
- 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
@tiffany-slac

Copy link
Copy Markdown
Contributor

@jbellister-slac Thanks for the review! The feedback has been addressed in the most recent commits. The first zoom/axis change is now undoable, reset zoom now pushes the post-reset state, added clearAll() to view history hook to avoid stale history across workspace loads, extended keyboard shortcuts, and added labels to all icon-only buttons.

@jbellister-slac jbellister-slac left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thanks! One issue noted below you might want to look at, otherwise it looks good to go.

};

const handleViewWindowChange = (plotId: string, window: TimeWindowNs) => {
const baseline = currentSnapshot(plotId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: on a following plot, Back to the baseline restores the full range but can leave Autoscroll off.

handleFollowStop turns autoscroll off on the first datazoom event, and this baseline is captured later, after the 400 ms debounce in handleDataZoom. Which value it records depends on the gesture:

  • A single wheel notch still runs the callback from the render before the stop, so the baseline records autoScroll: true.
  • A multi-notch zoom or a drag replaces that callback with one from a later render, where the plot has already stopped following, so the baseline records autoScroll: false.

Reproduced in the browser on a live plot: zoom several notches in one go, press Back, and the range is restored but the Autoscroll switch stays off. With a single notch, Back turns it back on.

This is not a regression (before the baseline entry existed there was no way back to the starting view at all), and it only affects the baseline entry.

Suggested fix: seed the baseline from handleFollowStop, before its updatePlot call. The plot is still following at that point, so the snapshot records autoScroll: true however many events follow. That means splitting the seeding step out of push into its own method on the hook, which push keeps calling for plots that were not following:

// useViewHistory.ts
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]
);

// TraceApp.tsx
const handleFollowStop = (plotId: string) => {
  viewHistory.seedBaseline(plotId, currentSnapshot(plotId));
  updatePlot(plotId, { autoScroll: false });
};

A hook test for seedBaseline (seeds once, no-op when history or a pending push exists) would cover it.

- Extract seedBaseline from push in useViewHistory
- Call from handleFollowStop before autoScroll is flipped off
- Ensures Back restores autoScroll on following plots
- Add three hook tests for seedBaseline
- Add canReset callback in TraceApp checking viewWindow, autoScroll, and axis state
- Pass as prop to PlotArea, wire disabled on both Reset buttons (tab bar and grid cell)
@tiffany-slac
tiffany-slac merged commit 4a5e8ea into main Nov 20, 2026
9 checks passed
@tiffany-slac
tiffany-slac deleted the tiffany/view-history branch November 20, 2026 18:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] - Zoom back/forward history [BUG] - Switching Autoscroll back on doesn't undo a pan or zoom

3 participants