# Undo/Redo Module data flow

## What It Does
Undo/Redo provides coordinated capture, storage and replay of spreadsheet-changing operations so users can reverse or reapply actions. Two cooperating pieces: **UndoRedo (UI service)** records action snapshots and performs undo/redo replay, and **ActionEvents (dispatcher)** normalizes and emits `beginAction`/`completeAction` lifecycle notifications and wires high-level event triggers.

## Entry Points

**UndoRedo (UI Layer)**
- `setActionData(options)` - capture "before" state for an upcoming action.
- `updateUndoRedoCollection(options)` - push an action into the undo stack after completion.
- `performUndoRedo(args)` - core entry to execute an undo or redo operation; replays the recorded CollaborativeEditArgs and refreshes UI.
- `getBeforeActionData(args)` - supply stored before-action details to other handlers.
- `clearUndoRedoCollection()` / `clearUndoRedoCollection()` - reset stacks.
- `undoForSorting()`, `undoForClipboard()`, `undoForResize()` - specialized undo helpers for complex action types.
- `performOperation(args)` - internal helper that applies the saved changes back to cells/sheets and triggers refreshes.
- Event hooks wired: `performUndoRedo`, `updateUndoRedoCollection`, `setActionData`, `getBeforeActionData`, `clearUndoRedoCollection`, `setUndoRedo`, `sheetRenameUpdate`.

**ActionEvents (UI Dispatcher)**
- `actionBeginHandler(args)` - invoked on `beginAction` to trigger `actionBegin` event and capture action context (and call `setActionData` when needed).
- `actionCompleteHandler(args)` - invoked on `completeAction` to trigger `actionComplete`, notify data change and enqueue undo/redo collection updates.
- Wired listeners: listens to `beginAction`, `completeAction` and `spreadsheetDestroyed` to manage lifecycle.

**Workbook / Core Layer** (helpers used by Undo/Redo)
- Address and sheet helpers: `getRangeIndexes`, `getRangeAddress`, `getSheet`, `getSheetIndex`, `getCellIndexes`.
- Cell access & mutation: `getCell`, `setCell`, `updateCell`, `setRow`, `setColumn`, `applyCellFormat`, `setPosition` and cell renderer refresh APIs used to re-materialize changes.
- Structural operations: helpers for `hidden`/`merge`/`charts` and `renderModule.refreshUI` used during replay when layout changes occur.
- Notifications & events used: `beginAction`, `completeAction`, `performUndoRedo`, `updateUndoRedoCollection`, `setActionData`, `getBeforeActionData`, `triggerDataChange`, `refreshRibbonIcons`, `refreshOverlayElem`, `showAggregate`, `workbookEditOperation` and many domain-specific events.

## Core Logic Flow

```
User performs workspace action (format/clipboard/autofill/resize/hideShow/insert/delete/…)
    ↓
Action begins → components call `beginAction` with eventArgs
    ↓
`ActionEvents.actionBeginHandler` fires: triggers `actionBegin` event and calls `setActionData` (via notify) to capture before-state when appropriate
    ↓
Operation completes → components call `completeAction` with eventArgs
    ↓
`ActionEvents.actionCompleteHandler` fires: notifies data change, triggers `actionComplete`, and calls `updateUndoRedoCollection` to add a serialized action record to UndoRedo undo stack
    ↓
User triggers undo/redo → `performUndoRedo({ isUndo: true/false })`
    ↓
UndoRedo pops appropriate record from `undoCollection` or `redoCollection` and calls `performOperation()`
    ↓
`performOperation()` applies stored deltas or full cell snapshots using core helpers (`setCell`, `setRow`, `setColumn`, renderer refresh, etc.), firing `beginAction`/`completeAction` around the replay where appropriate
    ↓
UI refresh: cell/row/col rendering refreshed, selection/aggregate/wrapper states updated; undo/redo icons updated
```

## Operations Handled

1. Cell-level edits: save/restore of values, formulas, formats, wrap and hyperlink changes.
2. Clipboard operations: cut/copy/paste including images and shapes, tracking pasted ranges and external copy metadata.
3. Structural changes: insert/delete rows/columns/sheets, hide/show, resize, merge and unmerge.
4. Autofill and series generation: record and replay data + formatting variants (autofillWithCF vs autofill).
5. Sorting and filter operations: store before/after snapshots for multi-row sorts and support undo sorting with cell-level data reinstatement.
6. Chart and image ops: insert/delete/refresh and anchoring updates during replay.
7. Note/comment operations and replies: add/edit/delete operations recorded and replayed.
8. Conditional formatting and validation changes: record rules and reapply on undo/redo when needed.

## Undo/Redo Modes

| Mode | Behavior |
|------|----------|
| Single-step Undo | Pop last action from `undoCollection`, replay it, push into `redoCollection`. |
| Redo | Pop last action from `redoCollection`, replay it, push into `undoCollection`. |
| Grouped/Compound Actions | Some actions carry `beforeActionData` and multiple internal changes (e.g., sort); replay applies grouped modifications atomically. |
| Public vs Internal Replay | `isPublic` flag controls whether events are re-fired to end-users or treated as internal updates to avoid double-eventing. |

## Validation & Safety

- **Begin/Complete lifecycle:** Each user action wraps begin/complete events so other subsystems can cancel or record `before` state; undo uses these markers when replaying.
- **Cancelable actions:** `beginAction` may set `cancel` to abort operations; `ActionEvents` respects cancellation.
- **Undo stack limits:** `undoRedoStep` bounds number of stored entries; stacks trimmed to avoid unbounded memory growth.
- **Before-state capture:** `setActionData` captures minimal and necessary before-state (cell snapshots, cut/copy metadata) to enable precise reversal.
- **Manual calculation mode:** When workbook is in manual calculation mode, undo/redo defers heavy recalculations appropriately to avoid inconsistent state.
- **Cross-sheet references:** `sheetRenameUpdate` handler updates stored action references if sheets are renamed so replay targets remain valid.
- **Partial replay protection:** Many action types include specialized undo helpers (clipboard/sort/resize) to handle edge cases (images, merged cells, virtualization) and avoid corrupting layout.
- **Event suppression:** During internal replays `preventEventTrigger` / internal flags can suppress external event firing to avoid duplicate user notifications.

## Desired Outputs

**User-Facing:**
- Responsive, accurate Undo/Redo toolbar icons reflecting stack availability.
- Seamless reversal of edits, structural changes, formats, autofill, and other sheet transformations.
- No data loss for complex actions (sorts, clipboard image pastes, merged cells).

**System-Level:**
- `undoCollection` and `redoCollection` store serializable action records (CollaborativeEditArgs) with `beforeActionData` for precise restoration.
- `completeAction` and `beginAction` events coordinate recording and replay.
- Core editors/renderers invoked to refresh only the necessary ranges after undo/redo to minimize reflow.
- Notifications: `triggerDataChange`, `updateUndoRedoCollection`, `performUndoRedo`, `refreshRibbonIcons`, `workbookEditOperation`, and selection/aggregate refreshes are emitted as applicable.
