# Sort Module data flow

## What It Does
Implements sorting of cell ranges. The Workbook layer (`WorkbookSort`) performs the data retrieval, comparison and cell updates for sorted results; the Spreadsheet layer (`Sort`) manages dialogs, user validation, and UI-level orchestration (spinner, dialogs, and applying visual indicators).

Primary implementation files: `src/workbook/integrations/sort.ts` (Core/WorkbookSort) and `src/spreadsheet/integrations/sort.ts` (UI/Sort).

## Entry Points (UI)
**Class:** `Sort` (Spreadsheet layer)
- Listens: `applySort`, `sortComplete`, `initiateCustomSort`, `sortImport`.
- Key handlers:
  - `applySortHandler(args)` — validate range, coerce filter-range context, emit `beforeSort`, show spinner and call `initiateSort` (core) with a promise.
  - `initiateCustomSortHandler()` — build and present custom sort dialog (multi-column), validate user input and then call `applySortHandler` with constructed `SortOptions`.
  - `sortRangeAlertHandler({ error })` — present localized error dialogs for invalid ranges or multi-range errors.
  - `sortCompleteHandler(args)` — after core finishes, refresh affected cells, trigger formula recalculation notifications and reapply conditional formats; hide spinner.
  - Helpers: `customSortContent()`, `getFields()`, `getCustomListview()`, `renderListItem()` — constructs dialog widgets (DropDownList, RadioButton, ListView) and validation flows.

## Entry Points (Core)
**Class:** `WorkbookSort` (Workbook layer)
- Listens: `initiateSort`, `updateSortedDataOnCell`.
- Key handlers:
  - `initiateSortHandler(eventArgs)` — main sorter: resolve sheet and address, determine containsHeader semantics, build `Query` with one or more `SortDescriptor`s, fetch cell data via `getData`, execute `DataManager` query to produce ordered results, and call `updateSortedDataOnCell()` to write results back.
  - `updateSortedDataOnCell(args)` — iterate target rows, map sorted records to sheet cells, update formulas (using `getUpdatedFormula`), preserve validations, wrap settings and borders as needed, and call `setCell()` to persist cells.
  - Helpers: `isHeaderRow()`, `isSameStyle()`, `skipBorderOnSorting()`, `sortComparer()` — header detection, style heuristics, border preservation, and locale-aware comparison (Intl.Collator) with number handling.

## ASCII Core Logic Flow
UI triggers sort → `Sort.applySortHandler()` validates and shows spinner → emits `initiateSort` → `WorkbookSort.initiateSortHandler()`
         ↓
Core computes actual range and header presence → builds sort `Query` and fetches cell data via `getData` → `DataManager.executeQuery()` sorts rows → `updateSortedDataOnCell()` writes sorted rows back to sheet (preserving formulas/validation/borders)
         ↓
Core resolves promise → UI `sortCompleteHandler()` refreshes cell render, triggers recalculation (`workbookFormulaOperation`) and hides spinner

## Operations (functions & responsibilities)
- `applySortHandler(args)` (UI)
  - Validate selected range and filters, emit `beforeSort`, call `parent.notify(beginAction, ...)`, then fire `initiateSort` and handle returned promise (success → `sortCompleteHandler`, failure → `sortRangeAlertHandler`).

- `initiateSortHandler(eventArgs)` (Core)
  - Translate human range to normalized indices, detect header row heuristically or via `containsHeader`, construct `SortDescriptor`(s) for single/multi-column sorts, create `Query` and call `getData()` to retrieve records for sorting.

- `updateSortedDataOnCell(args)` (Core)
  - For each target row, map sorted record values into `CellModel`s, preserve cell border styling, validation and wrapping, update formulas with `getUpdatedFormula`, and call `setCell()` to persist changes.

- `sortComparer(sortDescriptor, caseSensitive, x, y)` (Core)
  - Compare two cells honoring direction, numeric detection (including imported numeric strings), hyperlinks, and locale-rules using `Intl.Collator` when comparing strings.

- `initiateCustomSortHandler()` (UI)
  - Build the custom multi-column sort dialog with listview rows, DropDowns and radio buttons for order, validate duplicates/empty fields, and call back into `applySortHandler()`.

## Validation & Safety
- Range validation: `isValidSortRange()` and checks in core reject ranges outside `usedRange` or multi-range sorting when not supported; UI shows localized error dialogs.
- Merge/merge-alerts: core inspects fetched data for merge-related flags and will abort with `AutoFillMergeAlertMsg` when merges conflict with sort.
- Header detection: heuristics compare cell styles and data types of first two rows, and respect explicit `containsHeader` when provided.
- Formula correctness: `updateSortedDataOnCell()` updates formulas using `getUpdatedFormula()` to maintain references after row moves.
- Border preservation: `skipBorderOnSorting()` maintains previous cell borders on newly set cells to avoid losing visual separators.

## Desired Outputs
- User-facing: sorted sheet content reflecting requested ordering, updated sort icons/indicators in filter UI, responsive dialogs for custom sorts and clear error messages for invalid ranges.
- System-level: `sortComplete` event emitted with metadata; workbook model updated (`setCell` calls) and formula recalculation notifications issued for affected ranges.

## Implementation Notes (short)
- Use `DataManager` + `Query` for in-memory sort operations to leverage comparator chaining for multi-column sorts.
- Keep UI and core roles separate: UI composes dialog and validates user intent; core executes deterministic data transformations and writes to model.
- Preserve validation, wrapping and conditional formats after sorting by invoking appropriate notifications (e.g., `applyCF`) and by copying preserved attributes when writing cells.
- Use `Intl.Collator` configured with `parent.locale` for consistent string comparisons across locales; fall back to numeric comparators when values are numeric-like.
- Ensure promise rejection paths carry localized error strings so UI can render appropriate dialogs.

## Key Events & Hooks
- spreadsheet → workbook: `initiateSort` (with args & promise) to request sorting.
- workbook → spreadsheet: `sortComplete` (emitted when sorting finished) and `refreshFilterRange` notifications to keep filter UI in-sync.
- cross-cutting: `beginAction` / `completeAction` lifecycle notifications and `workbookFormulaOperation` for recalculation.

---