# Selection Module data flow

## What It Does
The Selection module manages user and programmatic cell/row/column selection, multi-range selection, formula reference selection, touch/drag selection, and integration with notes/comments and autofill. Two-layer architecture: **Selection (UI)** handles pointer/touch/keyboard interactions, visual selection overlays and indicators; **Workbook (Core)** maintains selected ranges, active cell, and persists selection-related state.

## Entry Points

**Selection (UI Layer)**
- `addEventListener()` / constructor - registers multiple spreadsheet-level events.
- `mouseDownHandler()` - entry for clicks/touches: starts selection, handles notes/comment containers, edit state and context-menu conditions.
- `mouseMoveHandler()` - drag-to-select, autoscroll while dragging, formula edit range updates, and auto-fill drag detection.
- `mouseUpHandler()` - finalize selection, trigger autofill, cleanup touch listeners and notify selection completion.
- `selectRange()` / `selectMultiRange()` - public entrypoints to select by address string and manage multi-range parsing.
- `selectRangeByIdx()` - internal worker that computes selection geometry, triggers beforeSelect, and sets final selected range.
- `getColIdxFromClientX()` / `getRowIdxFromClientY()` - convert client coordinates to logical row/column indexes, considering frozen panes, headers, DPI and virtualization.
- `getSelectionElement()` / `getActiveCell()` / `createSelectionElement()` - create/obtain DOM overlays used to render selection and active-cell outlines.
- `updateActiveCell()` - update workbook active cell and reposition the active-cell overlay.
- `highlightHdr()` - highlight row/column headers for full-row or full-column selections.
- `rowHeightChanged()` / `colWidthChanged()` - adjust selection overlays and active cell visuals when sizes change.
- `virtualContentLoadedHandler()` - re-evaluate header highlights and selection positions after virtual content shifts.
- `init()` - initialize selection on contentLoaded.
- `processFormulaEditRange()` / `initFormulaReferenceIndicator()` - draw formula reference visual indicators while editing formulas.
- `protectHandler()` - re-apply selection constraints when protection rules change.

**Workbook (Core Layer)**
- `getCell(row,col,sheet)` / `getCellIndexes(address)` / `getRangeIndexes(range)` / `getRangeAddress(range)` - core helpers for mapping addresses and reading cell metadata used by UI checks.
- `updateSelectedRange(workbook, range, sheet, isMultiRange?)` - persist selected ranges on the workbook model.
- `setPosition(parent, element, range, className?, preventAnimation?)` - core positioning helper to place overlays based on current viewport/offsets.
- `updateCell(parent, sheet, args)` - used when saving notes/notes state changes during selection interactions.
- `skipHiddenIdx`, `isHiddenRow`, `isColumnSelected`, `isRowSelected`, `isSingleCell` - core utilities consulted by selection logic.
- `getRowHeight`, `getColumnWidth` - used to calculate pixel offsets and adjust overlay metrics.
- Events/notifications used: `editOperation`, `performAutoFill`, `positionAutoFillElement`, `hideAutoFillElement`, `selectionComplete`, `beforeSelect`, `activeCellChanged`, `refreshOverlayElem`, `removeCommentContainer`, `removeNoteContainer`, `completeAction`.

## Core Logic Flow

```
User input (mousedown/touch/keyboard) → Selection.mouseDownHandler()
    ↓
Validate context (edit mode, protected sheet, notes/comments) → early exit or proceed
    ↓
Compute initial target indexes via getColIdxFromClientX/getRowIdxFromClientY
    ↓
If drag selection: attach mousemove handler → mouseMoveHandler() computes live range, autoscrolls, updates overlays
    ↓
On mouseup: mouseUpHandler() clears handlers, finalizes range
    ↓
selectRangeByIdx() → validate via `beforeSelect` → updateSelectedRange() (Core)
    ↓
updateActiveCell() → setPosition() to move active-cell overlay → notify `selectionComplete` and `positionAutoFillElement`
    ↓
row/col size changes or virtualization events → rowHeightChanged()/colWidthChanged()/virtualContentLoadedHandler() adjust overlays and header highlights
```

## Operations Handled

1. Single-cell and multi-range selection (mouse, touch, keyboard).
2. Full-row and full-column selection detection and header highlighting.
3. Drag selection with auto-scroll when pointer leaves viewport.
4. Selection while editing formulas: draw formula-range indicators, update reference ranges, and support mixed-sheet references.
5. Interaction with notes and comments: save/update note content, open/close note containers, and avoid selection conflicts with active note/comment UI.
6. Autofill integration: detect autofill drag start and notify `performAutoFill` on mouseup.
7. Frozen panes and virtualization: calculate coordinates and offsets correctly when panes are frozen or content is virtualized.
8. Selection state under protection: respect sheet protectSettings and optionally cancel selection changes.
9. Touch vs mouse behavior: differentiate touch long-press context menus and touch selection start/stop.

## Selection Modes

| Mode | Behavior |
|------|----------|
| SingleCell | Normal single cell selection and active cell update. |
| MultiRange | Ctrl-click or programmatic multi-range selection; overlays for multiple ranges. |
| FullRow | Row headers highlight and selection spans entire row. |
| FullColumn | Column headers highlight and selection spans entire column. |
| DragSelect | Mouse/touch drag to expand selection with autoscroll support. |
| FormulaRefSelect | While editing formulas, draw reference indicators and update formula ranges. |

## Validation & Safety

- **Edit-state checks:** Query `editOperation` to determine if cell edit is active; manage formula-edit-specific selection behavior and avoid interfering with in-cell edits.
- **Protection checks:** Honor `sheet.protectSettings` and cancel or restrict selection changes when protection disallows selection.
- **Notes/comments concurrency:** Ensure active note/comment containers are saved or closed before changing selection; avoid losing user edits inside note containers.
- **Merged ranges:** Use `mergedRange` notifications and adjustments so selections align with merged cells; selection may expand to encompass merge boundaries.
- **Viewport & frozen panes:** Convert client coordinates to logical indexes considering `viewport` offsets, beforeFreeze widths/heights, and frozen row/column positions.
- **Virtualization:** Use `virtualContentLoaded` to re-attach/adjust visual overlays after virtualized content changes.
- **Event cancellation:** Fire `beforeSelect` and respect `cancel` to allow higher-level logic to veto selection changes.

## Desired Outputs

**User-Facing:**
- Accurate selection rectangles and active-cell outline that follow user interactions.
- Clear header highlighting for full-row/column selections.
- Smooth drag selection with autoscroll and touch-friendly behavior.
- Formula reference indicators during in-cell formula editing.
- Safe behavior around notes/comments and protection rules.

**System-Level:**
- Workbook `selectedRange` and `activeCell` updated via `updateSelectedRange` / `setSheetPropertyOnMute`.
- Notifications emitted: `beforeSelect`, `selectionComplete`, `activeCellChanged`, `positionAutoFillElement`, `performAutoFill`.
- Visual overlays positioned via `setPosition` to remain in sync with scroll/viewport offsets.
- Selection adjustments triggered on `rowHeightChanged`, `colWidthChanged`, and `virtualContentLoaded` to maintain alignment.
- Compatibility with frozen panes, virtualization, touch input, and formula-editing workflows.
