# Insert Module data flow

## What It Does
Insert module handles inserting cells, rows, columns and sheets across both the core workbook model and the spreadsheet UI. It updates data structures (rows/columns/sheets), maintains ranges/usedRange, preserves styles/merges/conditional formats, repositions images and charts, and triggers UI refreshes and related notifications.

## Entry Points

**WorkbookInsert (Core)**
- `insertModel(args: InsertDeleteModelArgs)` - Primary core method that mutates `SheetModel`/`Workbook` data for Row/Column/Sheet insert operations. Handles model-level bookkeeping including `usedRange`, merges, conditional formats, comments, notes, and frozen pane adjustments.

**Insert (Spreadsheet / UI)**
- `insert(actionArgs: ActionEventArgs)` - UI-side handler that responds to the `insert` event, performs rendering updates, scroll/viewport adjustments, triggers comment/note pane refreshes, and completes user-facing actions.

## Core Logic Flow

1. User invokes an insert (API/UI menu/keyboard). UI creates `InsertDeleteEventArgs` and triggers the workflow.
2. `beginAction` may be raised (undo/redo and cancellation support). If cancelled, the flow stops.
3. Core: `WorkbookInsert.insertModel` runs and:
   - Normalizes `start`/`end` and builds `model` array to insert.
   - Emits `refreshInsertDelete` and prepares `insertArgs` describing start/end and isInsert flag.
   - For Rows:
     - Adjusts `rows`, `maxHgts`, frozen rows (`frozenRows`) and `usedRange`.
     - Inserts empty RowModels and shifts existing row-level data.
     - Propagates styles/format/wrap from adjacent cells into new rows where applicable.
     - Handles merged cells that cross the insertion boundary.
   - For Columns:
     - Adjusts `columns`, `rows[].cells`, frozen columns (`frozenColumns`) and `usedRange`.
     - Inserts column cell placeholders per row, shifting cell arrays and preserving adjacent styles.
     - Collects merge adjustments to re-emit as `insertMerge` notifications.
   - For Sheets:
     - Creates new `SheetModel` instances and inserts them into `parent.sheets`.
     - Updates `activeSheetIndex` and calls `createSheet` on workbook.
     - Updates data-source ranges and notifies formula engine (`workbookFormulaOperation`) for sheet additions.
   - Inserts conditional formats, comments and notes by adjusting addresses via `insertFormatRange` and re-indexing threaded comments/notes.
   - Sends `refreshClipboard`, `refreshChart` notifications where appropriate.
4. Core emits the `insert` action event with `ActionEventArgs` to indicate the model change completed.
5. UI: `Insert.insert` listens for `insert` and:
   - Calls `insertSheetTab` and triggers `renderModule.refreshSheet()` for sheets insertion.
   - For Row/Column inserts, decides between full refresh or partial virtualization-aware refresh using viewport/frozen indexes.
   - Adjusts scroll position using `updateScrollValue` if the top/left of the viewport needs shifting after insert.
   - Re-selects current selection and refreshes comments/note panes via `refreshCommentsPane` and `updateNoteContainer`.
   - Triggers `triggerDataChange` or `completeAction` depending on `isAction`/`isUndoRedo` flags and focuses the spreadsheet element.
6. UI also calls helper to reposition images/charts: `refreshImgChartElement` which iterates sheet cells and emits `refreshImagePosition` or chart refresh events when chart cell indices change.

## Operations Handled

- Insert Rows
  - Inserts `RowModel` elements into `sheet.rows` at `index`.
  - Updates `maxHgts` and `rowCount` and notifies UI via `updateRowColCount`.
  - Transfers cell-level styles and wrap/format metadata from adjacent parent cell into new rows.
  - Handles merged-cell rowSpan adjustments and emits merge notifications.

- Insert Columns
  - Inserts column descriptors into `sheet.columns` and per-row cell placeholders into `rows[i].cells`.
  - Updates `colCount` and notifies UI via `updateRowColCount`.
  - Preserves adjacent cell styles and manages `colSpan` merge edge cases via `insertMerge` notifications.

- Insert Sheets
  - Creates new `SheetModel` objects through `createSheet`.
  - Updates `activeSheetIndex` and informs formula subsystem to register new sheet ids/names.
  - Updates data ranges on sheets imported from data source.

- Conditional Formats
  - Recomputes CF ranges using `insertFormatRange` when rows/columns are inserted.

- Comments & Notes
  - Re-indexes existing `comments`/`notes` addresses when rows/columns are inserted.
  - Restores previously deleted comments/notes when `prevAction === 'delete'` by re-inserting stored items.

- Merged Cells
  - Detects merge cells adjacent to insertion boundaries and issues `insertMerge` events to adjust merge ranges.

- Images & Charts
  - After model changes, UI iterates cells and emits `refreshImagePosition` for images and `refreshChartCellOnInit` for charts that moved.

## Validation & Safety

- Cancellation: `beginAction`/`eventArgs.cancel` allows intercepting insert operations.
- Undo/Redo: Flags `isUndoRedo` / `isRedo` control whether certain re-indexing or style-copy operations run.
- Count checks: `checkCount` prevents inserts when length matches expected values (defensive early return).
- Freeze/pane adjustments: Inserts that cross frozen boundaries update `frozenRows`/`frozenColumns` and set `freezePane` in event args so UI can refresh panes correctly.
- Boundary/usedRange updates: Core ensures `usedRange` is updated to avoid out-of-bounds issues after insertion.

## Desired Outputs (Post-Insert)

- Model: Updated `SheetModel` and `Workbook` state (rows, columns, sheets, `usedRange`, merges, conditional formats, comments, notes).
- Events: `insert` action emitted with `ActionEventArgs`; supporting notifications: `refreshInsertDelete`, `insertMerge`, `refreshClipboard`, `refreshChart`, `workbookFormulaOperation`.
- UI: Refreshed sheet/tab UI, updated viewport and scroll positions, updated comments pane and note container, repositioned images/charts.
- Undo/Redo entry: Proper action recorded for undo/redo stacks when `isAction` is true.

## System-Level

- Important types & models touched:
  - `InsertDeleteEventArgs`, `ActionEventArgs`, `SheetModel`, `RowModel`, `CellModel`, `MergeArgs`, `ExtendedThreadedCommentModel`, `ExtendedNoteModel`.

- Key events/notifications used across layers:
  - beginAction, insert, beforeInsert, refreshInsertDelete, insertMerge, refreshClipboard, refreshChart,
    refreshCommentsPane, updateNoteContainer, refreshImagePosition, updateScrollValue, triggerDataChange, completeAction,
    workbookFormulaOperation, updateRowColCount.

- Modules:
  - Core: `src/workbook/actions/insert.ts` (`WorkbookInsert`)
  - UI: `src/spreadsheet/actions/insert.ts` (`Insert`)

## Test / Verification Actions

- Insert a single row/column inside and outside frozen panes and verify `frozenRows`/`frozenColumns` changes and UI pane refresh.
- Insert multiple rows/columns with merged cells crossing the insert boundary and verify merges updated and no visual overlap occurs.
- Insert sheets and verify `activeSheetIndex` and formula engine notifications for sheet registration.
- Insert when comments/notes exist and verify their addresses were incremented and review pane reflects changes.
- Verify images and charts move with rows/columns and that `refreshImagePosition` / `refreshChartCellOnInit` are invoked.

---