# Show/Hide Module data flow

## What It Does
The Show/Hide module performs hiding and showing of rows and columns (including filter-driven hide), manages DOM updates for virtualized and frozen panes, and coordinates related layout changes (borders, charts, merged cells, and viewport translation). Two-layer architecture: **ShowHide (UI)** handles event dispatch, DOM fragment manipulation and visual insertion/removal; **Workbook (Core)** updates the sheet model (`row.hidden` / `column.hidden`) and provides helpers for sizes, ranges, and merge/chart metadata.

## Entry Points

**ShowHide (UI Layer)**
- `hideShow(args: HideShowEventArgs)` - main entry that normalizes args, runs beginAction/completeAction, and splits work for frozen panes.
- `hideRow(args)` - hide/unhide a sequence of rows: updates model, detaches/appends row DOM, handles merges, charts and viewport updates.
- `hideCol(args)` - hide/unhide a sequence of columns: updates model, removes/appends column `colgroup`/cells, and triggers column-part or full refresh.
- `removeCell(sheet, indexes, rowIdxs, table, hTable)` - low-level removal logic for hidden columns within rendered rows (handles merge adjustments and border fixes).
- `appendCell(sheet, indexes, rowIdxs, table, hTable, skip)` - low-level append logic for un-hiding columns and re-rendering cells/colgroups.
- `updateIndexOnlyForHiddenColumnsAndRows(args, sheet)` - prune start/end to first visible index when actionUpdate is true.
- `refreshChart(index, showHide)` / `refreshChartCellModel(prev, current)` - notify chart subsystem to update chart positions when hiding/unhiding affects chart anchors.
- `addEventListener()` / `destroy()` - wire/unwire `hideShow` and lifecycle events.

**Workbook (Core Layer)**
- `getSheet(parent, sheetIndex)` - fetch sheet model for operations.
- `setRow(sheet, rowIdx, rowModel)` / `setColumn(sheet, colIdx, colModel)` - persist hidden flags and custom properties on sheet model.
- `isHiddenRow(sheet, idx)` / `isHiddenCol(sheet, idx)` - query hidden status used throughout UI logic.
- `getRowHeight(sheet, idx, includeHidden?)` / `getColumnWidth(sheet, idx, skipHidden?, includeHidden?)` - return pixel sizes used when computing translate heights or detached sizes.
- `skipHiddenIdx(sheet, idx, fromStart, type?)` / `hiddenCount()` - helpers for mapping logical indexes across hidden items.
- `getRangeAddress(range)` / `getCellIndexes()` / `getCellAddress()` - address helpers used when calculating refresh ranges.
- `applyCellFormat` & `CellRender` helpers - used to repair border style and re-render cell fragments.
- `renderModule.refreshUI(...)` / `renderModule.refreshSheet(...)` - invoked to re-render parts of the sheet when DOM fragment operations are insufficient.
- Events/notifications used: `beginAction`, `completeAction`, `autoFit`, `virtualContentLoaded`, `updateTranslate`, `updateTableWidth`, `hiddenMerge`, `setMerge`, `refreshChart`, `refreshChartCellModel`, `readonlyAlert`.

## Core Logic Flow

```
Request: hideShow(args) (user action or programmatic)
    ↓
Normalize args (start/end order) and validate readonly via isReadOnlyCells/beginAction
    ↓
If freeze-pane boundary crosses range → split range and call hide/show for top-left and frozen parts
    ↓
For each part:
  - If hiding:
      • iterate indexes, skip already-hidden; update model via setRow/setColumn; collect removed DOM fragments or mark viewport translation
      • handle merges, charts, and border repairs; detach rows/cols or mark virtual translate change
      • if DOM removal is simple and within thresholds → detach individual elements; else → call renderModule.refreshUI/refreshSheet
  - If showing:
      • iterate indexes, update model to visible; create DocumentFragments with rendered rows/cols using cell/row renderers
      • insert fragments at calculated insert index, fix borders and merges, refresh charts
      • if content growth crosses thresholds or virtualization state prevents append → full refresh
    ↓
If actionUpdate: updateIndexOnlyForHiddenColumnsAndRows(), emit `completeAction`, focus host
    ↓
Notify dependent systems: `autoFit` (row autofit), `virtualContentLoaded`, `updateTranslate` (adjust translate/offsets), `updateTableWidth` (column width adjustments)
```

## Operations Handled

1. Hide rows/columns: mark model hidden, remove DOM rows/colgroups and adjust viewport counts.
2. Show rows/columns: unmark model hidden, re-render necessary rows/columns and re-insert into table fragments.
3. Filter-driven hiding: support `isFiltering` flag to hide rows as filter results change and set `isFiltered` metadata.
4. Frozen pane split: split hide/show across freeze boundary and treat each pane portion separately.
5. Virtualized handling: if virtualization is enabled, prefer viewport translation updates or partial `refreshUI` calls instead of full DOM ops.
6. Merge-safe operations: detect merged cells spanning hidden indexes and either defer DOM removal or trigger merge-aware re-rendering and `hiddenMerge` notifications.
7. Chart anchoring: calculate and refresh chart cell models when rows/columns move due to hide/show.
8. Border and style repair: re-apply `borderTop` / `borderLeft` styles when insertion/removal exposes new neighbors.

## Show/Hide Modes

| Mode | Behavior |
|------|----------|
| HideRows | Set `row.hidden=true`, detach row DOM, update viewport/bottomIndex/translate. |
| ShowRows | Set `row.hidden=false`, build row fragments and insert into DOM, repair merges/borders. |
| HideColumns | Set `column.hidden=true`, remove `colgroup` children and cell children, adjust viewport and table width. |
| ShowColumns | Set `column.hidden=false`, append column `colgroup` entries and cell elements; may trigger `virtualContentLoaded`. |
| FilterHide | Hide rows marked by filtering and set `isFiltered` metadata without a full UI refresh where possible. |

## Validation & Safety

- **Read-only checks:** When `actionUpdate` is requested, verify range is not read-only with `isReadOnlyCells`; abort and optionally notify `readonlyAlert`.
- **Begin/Complete actions:** Emit `beginAction` and respect `cancel` to allow higher-level veto of hide/show operations.
- **Merge and hidden-merge detection:** If merged cells overlap the hide range, avoid simple detach; either refresh sheet or issue `hiddenMerge` notifications so merges are preserved.
- **Virtualization bounds:** When virtualization or finite scrolling is enabled, prefer translate updates (`updateTranslate`) or partial refreshes to avoid heavy DOM ops.
- **Frozen panes:** Split operations at freeze boundaries and correctly target frozen vs scrollable tables to avoid inconsistent DOM updates.
- **Chart safety:** Capture `prevChartIndexes` and `currentChartIndexes` to update chart models after structural changes, preserving data anchors.
- **Threshold checks:** Use parent thresholds to decide between granular DOM operations and full re-render to limit jank and ensure correctness.

## Desired Outputs

**User-Facing:**
- Smooth hide/show UX: headers reflect hide-start/hide-end markers; rows/columns disappear or reappear without broken borders.
- Correct behavior with filters, merged cells, charts and frozen panes.
- Reasonable performance with virtualization: minimal full-refreshes and stable viewport after hide/show.

**System-Level:**
- Sheet model updated via `setRow` / `setColumn` with `hidden` and `isFiltered` flags.
- Notifications emitted: `beginAction`, `completeAction`, `updateTranslate`, `virtualContentLoaded`, `autoFit`, `updateTableWidth`, `refreshChart`, `refreshChartCellModel`.
- Viewport indexes (`viewport.topIndex/bottomIndex/leftIndex/rightIndex`) adjusted as needed; `renderModule.refreshUI` invoked for non-trivial layout changes.
- Merge and chart models updated to reflect the new layout and anchored positions.
- Focus restored to the host after action completion when `actionUpdate` is true.
