# Delete Module data flow

## What It Does
Provides delete support for the Spreadsheet/Workbook including:
- Delete rows, columns, cells ranges and whole sheets.
- Maintain model integrity: usedRange, row/column counts, frozen pane counts, max row heights.
- Handle merged ranges, conditional formats, threaded comments, legacy notes, charts and images.
- Coordinate core model changes (WorkbookDelete) with UI refresh and downstream updates (Delete in Spreadsheet).

## Entry Points

**WorkbookDelete (Core)**
- `constructor(parent: Workbook)` — registers listeners and initializes module.
- `deleteModel(args: InsertDeleteModelArgs)` — primary core entry that mutates sheet/workbook model.
- `setRowColCount(startIdx, endIdx, sheet, layout)` — updates sheet row/column counters and notifies row/col count updates.
- `deleteConditionalFormats(args, eventArgs)` — adjusts or removes affected conditional formats.
- `deleteComments(args, eventArgs)` — removes or re-maps threaded comments when rows/cols are deleted.
- `deletenotes(args, eventArgs)` — removes or re-maps legacy notes when rows/cols are deleted.
- Lifecycle: `addEventListener()`, `removeEventListener()`, `destroy()`, `getModuleName()`.

**Delete (Spreadsheet / UI)**
- `constructor(parent: Spreadsheet)` — hooks UI listeners.
- `delete(actionArgs: ActionEventArgs)` — receives the result of core delete (notification `deleteAction`) and performs UI updates.
- `refreshImgChartElement(count, sheetIdx, modelType, index)` — update repositioning or reinitialization of images and charts post-delete.
- Lifecycle: `addEventListener()`, `removeEventListener()`, `destroy()`, `getModuleName()`.

**Notifications / Events (used by modules)**
- Core triggers: `beginAction`, `refreshInsertDelete`, `beforeDelete`, `deleteAction`, `workbookFormulaOperation`, `setMerge`, `refreshClipboard`.
- UI consumes/produces: `deleteAction` (UI listens), `completeAction`, `triggerDataChange`, `refreshSheetTabs`, `refreshImagePosition`, `refreshChartCellOnInit`, `refreshCommentsPane`, `updateNoteContainer`, focus updates.

## Core Logic Flow

```
User/UI or API triggers delete -> DeleteModel (core) receives InsertDeleteModelArgs
            ↓
Validation & early bailouts:
  - Prevent deleting last sheet
  - Check virtualization/finite scroll boundaries and usedRange
  - Check checkCount / protection rules
  - If isAction: emit beginAction and honor cancel
            ↓
Normalize start/end, compute count, prepare InsertDeleteEventArgs & ActionEventArgs
            ↓
For Row/Column delete:
  - notify refreshInsertDelete
  - clamp start/end to rowCount/colCount or usedRange depending on isFinite
  - call setRowColCount to update counts + notify updateRowColCount
  - adjust usedRange when deletions affect it
  - adjust frozen rows/columns and set freezePane flag
  - iterate affected cells to handle merged ranges:
       * Query merge ranges via activeCellMergedRange
       * Update master merged cell spans or prepare merge adjustments
       * Collect mergeArgsCollection for subsequent merge updates
  - For Column delete collect deletedCells models (cell objects spliced from row cell arrays)
  - For Row delete handle merge-related adjustments similarly
  - Remove conditional formats, comments and notes via helper functions and record previous state into eventArgs
            ↓
For Sheet delete:
  - prevent deleting last remaining sheet
  - notify refreshInsertDelete
  - prepare deletedModel array and remove sheets from sheets collection
  - notify workbookFormulaOperation to detach sheet formulas/references
            ↓
Apply model removals (sheets/rows/cols), splice arrays, update max heights when needed
            ↓
Apply merge updates: notify `setMerge` for all mergeArgsCollection
            ↓
Notify `beforeDelete` with args; then notify `deleteAction` (ActionEventArgs) to broadcast deletion result
  - eventArgs passed include: deletedModel, deletedCellsModel, conditionalFormats, comments, notesCol, definedNames, sheetCount, activeSheetIndex, refreshSheet, isAction/isUndoRedo flags
            ↓
UI layer listens for `deleteAction` -> Spreadsheet `delete()` executes UI refresh and downstream updates
```

## UI / Post-Delete Flow (Spreadsheet)

- UI receives `deleteAction` with `InsertDeleteEventArgs` and `deletedModel`.
- If modelType is `Sheet`:
  - Update `activeSheetIndex` (skip hidden sheets), refresh sheet tabs and re-render active sheet if removed.
- If active sheet matches the operation:
  - Evaluate virtualization and viewport bounds to decide between `refreshSheet` full-rerender or `renderModule.refreshUI` optimized updates for row/column changes.
  - Update top-left cell when deletions affect pane anchors.
  - Re-select previous/adjusted `selectedRange`.
- Notify `refreshCommentsPane` and `updateNoteContainer` so comment/note panes reflect changes.
- Call `refreshImgChartElement` to adjust image and chart positions, and possibly trigger `refreshChartCellOnInit` if chart anchor cell changed.
- Fire `completeAction` and manage keyboard focus when `isAction` is true; otherwise for programmatic deletes trigger `triggerDataChange`.

## Operations Handled

- Full-sheet deletion and multi-sheet deletions (with safeguards for last sheet).
- Row deletion and Column deletion with virtualization-aware clamping.
- Merged range reconciliation (shrink, remove or reanchor merges) using merge queries and `setMerge` notifications.
- Conditional format removal or range-shift via `deleteConditionalFormats`.
- Threaded comments removal and address remapping via `deleteComments`.
- Legacy notes removal and address remapping via `deletenotes`.
- Charts/images repositioning and chart reinitialization when anchors move.
- Clipboard refresh when cells/rows/columns are deleted.
- Update of sheet-level metadata: `usedRange`, `rowCount`/`colCount`, `frozenRows`/`frozenColumns`, `maxHgts`.

## Validation & Safety

- Prevent deletion of the single remaining sheet.
- Respect `isFinite` scrollSettings and virtualization to avoid deleting past `rowCount`/`colCount`.
- Bail out when `checkCount` indicates the operation would invalidate usedRange boundaries.
- Event cancellation: when `isAction` is true, `beginAction` is emitted and `eventArgs.cancel` can stop the operation.
- Maintain undo/redo flags: `isUndoRedo` is preserved in event args when applicable.
- Avoid operations while editing (handled elsewhere) and ensure UI-level checks (e.g., protected sheets) occur before calling core delete.
- Carefully update merged ranges to avoid corrupting overlapping merges.

## Desired Outputs

User-Facing:
- Correct removal of selected rows/columns/sheets with model-accurate results.
- Visible UI refresh consistent with virtualization and frozen panes.
- Comments/Notes/ConditionalFormats removed or re-mapped correctly.
- Charts and images maintain visual anchors or are refreshed when their anchor moves.

System-Level:
- `deletedModel` payload describing removed sheets/rows/columns for history/undo and UI consumption.
- `deletedCellsModel` describing deleted cells for clipboard/restore.
- Notifications emitted: `beforeDelete`, `deleteAction`, and follow-ups like `refreshClipboard`, `refreshChart`, `refreshImagePosition`, `refreshCommentsPane`.
- Merge corrections applied via `setMerge` notifications.
- Row/Column counters updated and `updateRowColCount` notified for other subsystems.


## Quick integration notes

- Core module (`WorkbookDelete`) owns the authoritative model mutation; UI (`Delete`) only reacts and performs rendering/UX updates.
- Any future change to delete semantics should keep model mutation in core and only minimal UI logic in `Delete` to preserve separation of concerns.

