# Keyboard Module data flow

## What It Does
Keyboard module provides keyboard navigation and shortcut handling for the Spreadsheet UI. It maps raw key events to navigation, selection, formatting, clipboard, ribbon and workbook commands, maintains focus and viewport scrolling, and protects against invalid actions during edit or dialog states.

## Entry Points

**KeyboardNavigation (UI)**
- `keyDownHandler(e: KeyboardEvent)` - Main navigation handler that processes navigation keys (arrows, Home/End, PageUp/PageDown, Tab/Enter) and updates selection, scrolls viewport, and triggers `cellNavigate`/`selectionComplete` events.
- Navigation helpers: `shiftSelection()`, `scrollNavigation()`, `getNextNonEmptyCell()`, `getNextUnlockedCell()`, `updateSelection()`, `setFocus()`, `focusEle()`.

**KeyboardShortcut (UI)**
- `keyDownHandler(e: KeyboardEvent)` - Handles keyboard shortcuts (Ctrl/Cmd combinations, Alt shortcuts, Shift combos) and maps them to workbook operations via `this.parent.notify(...)`.
- `ribbonShortCuts(e: KeyboardEvent)` - Handles Alt+letter ribbon navigation and active tab focus.
- `keyUpHandler(e: KeyboardEvent)` - Minor focus fixes after key releases.

## Core Logic Flow

1. Browser receives a key event; Spreadsheet registers listeners in `KeyboardNavigation` and `KeyboardShortcut`.
2. Early checks run: ignore when selection mode is `None`, dialogs open, in-cell edit mode, or when target is a form/control (find, filter, name box, comment input, formula bar, etc.).
3. If navigation keys are used:
   - `KeyboardNavigation` computes new active cell or expanded selection using index helpers and hidden/frozen-aware helpers (`skipHiddenIdx`, `getRangeIndexes`, `getCellIndexes`).
   - It prevents default when appropriate and updates selection via `parent.notify(cellNavigate, ...)` or `updateSelection()`.
   - It calls `scrollNavigation()` to ensure the active cell is visible, using virtualization offsets and `getRowsHeight`/`getColumnsWidth` helpers.
   - Special navigation behaviors: Home/End (with/without Ctrl/Shift), page navigation, next/previous non-empty cell, and navigation while editing formulas (shift-selection while editing formula).
4. If modifier shortcuts are used (Ctrl/Cmd, Alt, Shift):
   - `KeyboardShortcut` maps combinations to workbook actions via notifications: clipboard actions (`copy`, `cut`, `paste`), undo/redo (`performUndoRedo`), file actions (`exportDialog`, open/upload), find/goto, auto-fill, format toggles (`setCellFormat`), hyperlink dialogs (`initiateHyperlink`, `editHyperlink`), insert sheet (`insertModel` via Shift+F11), and others.
   - Ribbon shortcuts (`ribbonShortCuts`) select ribbon tabs and optionally focus controls; Alt+letter combinations are converted to tab selections and focus changes.
5. Contextual actions: Comment/note input fields, filter popup interactions, and other UI controls receive special handling (Escape to close, Tab navigation, Alt+Down for filter), which defer to comment/note handlers or notify appropriate events.
6. After actions complete, the handlers emit UI updates and notifications (`selectionComplete`, `refreshRibbonIcons`, `triggerDataChange`, etc.) as needed.

## Operations Handled

- Navigation
  - Arrow keys, Home/End, PageUp/PageDown, Tab, Enter
  - Shift+arrows for range expansion, Ctrl+arrows for jump/navigation, navigation skipping hidden rows/columns
  - Focus management across sheet area, sheet tabs, ribbon and formula bar

- Selection
  - Single-cell movement, multi-cell selection (Shift), select-all and row/column full selections
  - Ctrl+Shift selection to extend to usedRange when virtualization is disabled

- Shortcuts & Commands
  - Clipboard: `copy`, `cut`, `paste`
  - Undo/Redo: `performUndoRedo` (Ctrl+Z / Ctrl+Y)
  - File: open/upload, save/export dialogs
  - Find/Goto: `findToolDlg`, `gotoDlg`
  - Hyperlink: `initiateHyperlink`, `editHyperlink` (Ctrl+K)
  - AutoFill and fill operations (Ctrl+R / Ctrl+D)
  - Format toggles: bold/italic/underline and number formats
  - Insert sheet: `insertModel` (Shift+F11)
  - Ribbon navigation via Alt shortcuts

- Comments & Notes
  - Special handling for comment/note input areas (Esc, Enter) to end edit or post replies

- Accessibility & Focus
  - Shift+F10 context menu handling, tab-order management, and focus redirection after key operations

## Validation & Safety

- Context checks: handlers bail out when dialogs are open, when in edit mode, or when target is an input/control to avoid interfering with typing.
- Protection checks: many shortcuts and navigation actions respect sheet protection and locked cells before notifying actions that would mutate data.
- Virtualization safety: scroll/viewport updates consider `scrollSettings.enableVirtualization` and use virtualization-aware refresh paths.
- PreventDefault usage: handlers prevent default browser behavior for keys they manage to keep spreadsheet interactions consistent.

## Desired Outputs (Post-Key Event)

- Correct `activeCell` and `selectedRange` values in the `SheetModel` and visible selection in the UI.
- Focus moved to the appropriate UI element (cell, formula bar, ribbon tab, sheet tab) depending on the shortcut.
- Expected notifications emitted to the workbook layer (`copy`, `paste`, `performUndoRedo`, `initiateHyperlink`, `insertModel`, etc.).
- Viewport scrolled so the active cell is visible; virtualization refreshes triggered when required.

## System-Level

- Important types & events referenced:
  - `keyDown`, `keyUp`, `cellNavigate`, `selectionComplete`, `copy`, `cut`, `paste`, `performUndoRedo`, `exportDialog`, `findToolDlg`, `gotoDlg`, `initiateHyperlink`, `editHyperlink`, `insertModel`, `renderInsertDlg`, `triggerDataChange`, `refreshRibbonIcons`.

- Modules:
  - UI: `src/spreadsheet/actions/keyboard-navigation.ts` (`KeyboardNavigation`)
  - UI: `src/spreadsheet/actions/keyboard-shortcut.ts` (`KeyboardShortcut`)
  - Many workbook notifications invoked from UI map into `src/workbook/*` handlers (format, clipboard, undo/redo, insertModel, etc.).

## Test / Verification Actions

- Arrow navigation: verify arrow, Home/End, PageUp/PageDown move active cell correctly with hidden/frozen rows/cols.
- Shift selection: verify expanding and contracting selection with shift+arrows and shift+tab behavior.
- Clipboard shortcuts: verify Ctrl+C/Ctrl+X/Ctrl+V perform copy/cut/paste and respect protected sheets.
- Undo/Redo: verify Ctrl+Z and Ctrl+Y revert/reapply changes when not editing.
- Ribbon shortcuts: Alt+letter selects correct ribbon tab and focuses expected control.
- Insert sheet: verify Shift+F11 triggers `insertModel` notification and creates a new sheet.
- Comments/Notes: verify Esc/Enter behavior while editing comments or notes does not trigger navigation and correctly posts/cancels edits.

---