# Sheet Tabs Module data flow

## What It Does
Manages the sheet tab UI (tabs + sheet list, add/rename/delete, hide/show, aggregation display) and synchronizes user actions with the Workbook model. This module lives in the Spreadsheet layer and coordinates dialogs, keyboard/mouse interactions and notifications to workbook subsystems.

Primary implementation file: `src/spreadsheet/integrations/sheet-tabs.ts` (class `SheetTabs`).

## Entry Points
**Class:** `SheetTabs` (Spreadsheet layer)
- Lifecycle: constructor → `addEventListener()` sets up handlers; `destroy()` cleans up.
- Listens to parent notifications: `sheetTabs`, `refreshSheetTabs`, `insertSheetTab`, `removeSheetTab`, `renameSheetTab`, `cMenuBeforeOpen`, `activeSheetChanged`, `activeCellChanged`, `focusRenameInput`, `sheetNameUpdate`, `hideSheet`, `showAggregate`, `goToSheet`, `showSheet`.

## Key Handlers & Responsibilities
- `createSheetTabs()`
  - Build DOM for sheet tab panel, add-button and sheet-list DropDownButton; create `Tab` instance, wire `selecting`/`selected` callbacks and register existing sheets with formula subsystem.

- `getSheetTabItems()`
  - Produce tab and dropdown item models from `parent.sheets`, escaping HTML for display and marking visibility.

- `goToSheet(args)`
  - Central navigation flow: end edit if needed, unregister visual charts, switch `activeSheetIndex`, call `parent.dataBind()`, notify formula registration and emit `completeAction`.

- `addSheetTab()` / `insertSheetTab(args)`
  - Trigger sheet insert by notifying `insertModel`; update dropdown and Tab UI, handle `preventUpdate` variant when caller already manages binding.

- `updateSheetTab(args)`
  - Select a sheet tab (unhide if hidden), update `Tab` selection and notify `protectSheet` to refresh protection-related UI.

- `removeSheetTab(args)` / `forceDelete(sheetIndex)` / `destroySheet(sheetIndex)`
  - Delete sheet flow: confirmation dialog when data exists, notify `refreshInsertDelete` and `workbookFormulaOperation` for cleanup, remove tab and dropdown, refresh active selection and render.

- Rename flow: `renameSheetTab()`, `renameInputFocusOut()`, `renameKeyDown()`
  - Replace tab text with input field, validate name (forbidden chars, uniqueness, max length), set sheet property and notify `sheetRenameUpdate` and `completeAction`.

- Aggregation: `showAggregate()` / `getAggregateItems()` / `updateAggregateContent()` / `removeAggregate()`
  - Query aggregate values via `aggregateComputation` notification and render a DropDownButton with computed summary (Sum/Avg/Count/Min/Max).

- Popup helpers: `beforeOpenHandler(instance, element, localeText?)` and `openHandler(instance, element, positionX, isDevice?)`
  - Ensure dropdowns fit viewport, compute collision-safe placement and set focus for accessibility.

## ASCII Flow (high-level)
User clicks tab/list/add/rename/delete → UI validates action (protection, name) → module notifies workbook (`insertModel`, `refreshInsertDelete`, `workbookFormulaOperation`) → workbook updates model → module updates Tab & DropDownButton models and calls `parent.renderModule.refreshSheet()` or `parent.dataBind()` as required → global completion events (`completeAction`) emitted.

## Validation & Safety
- Protection: operations check `parent.isProtected` and `parent.password` and disable/deny actions accordingly.
- Rename validation: forbids control characters and reserved chars (`[]*\/?:<>|"`), enforces uniqueness (case-insensitive) and max length; shows localized dialog on invalid input.
- Delete safety: prompts user when deleting non-empty sheets; prevents deleting last visible sheet and handles hidden/very-hidden states.
- Popup sizing: dropdown height is clamped to viewport; collision detection avoids off-screen rendering.

## Desired Outputs
- UI: updated sheet tabs and sheet-list reflecting sheet collection state, visible selection, and aggregate control when applicable.
- Model: `parent.sheets` updated, `activeSheetIndex` set correctly, and workbook-level notifications fired for formula/grid registration and insert/delete operations.
- Accessibility: focus restored to appropriate element after interactions; aria-labels set on popups.

## Implementation Notes
- Keep tab ids unique using `parent.element.id` prefix to avoid handler collisions.
- Batch UI updates where possible (update both Tab and DropDown items before calling `dataBind()`) to avoid flicker.
- Always remove event listeners, ripple handlers and component instances in `destroy()` to prevent leaks.
- Use `parent.notify(...)` channels for cross-module coordination (e.g., `workbookFormulaOperation`, `refreshInsertDelete`, `aggregateComputation`).
- When switching sheets while editing, call `parent.endEdit()` only after verifying the edit value is not a formula input that should persist across navigation.

## Key Events & Hooks (spreadsheet ↔ workbook)
- Outgoing notifications: `insertModel`, `refreshInsertDelete`, `removeDesignChart`, `workbookFormulaOperation`, `aggregateComputation`, `clearUndoRedoCollection`, `completeAction`, `sheetsDestroyed`, `refreshCommentsPane`.
- Incoming notifications handled by this module: `sheetTabs`, `refreshSheetTabs`, `insertSheetTab`, `removeSheetTab`, `renameSheetTab`, `activeSheetChanged`, `activeCellChanged`, `focusRenameInput`, `sheetNameUpdate`, `hideSheet`, `showAggregate`, `goToSheet`, `showSheet`.

---