# Number Format Module data flow

## What It Does
Number Format subsystem handles parsing, localization, display and persistence of numeric/date/time/currency formats. The Workbook layer performs the core formatting logic, localized mapping and format IDs; the Spreadsheet layer applies formatted text to cell DOM, measures space for fill/padding, and provides UI refresh hooks.

Primary implementation files: `src/workbook/integrations/number-format.ts` (Core/WorkbookNumberFormat) and `src/spreadsheet/integrations/number-format.ts` (UI/NumberFormat).

## Entry Points (UI)
**Class:** `NumberFormat` (Spreadsheet layer)
- Listens: `refreshCellElement`, `rowFillHandler`, `getTextSpace`.
- Key handlers:
  - `refreshCellElement(args: NumberFormatArgs)` — refresh a cell node using formatting arguments.
  - `rowFillHandler(args)` — render repeated-fill text (custom format `*`) and measure available width to compute repeat count.
  - `getTextSpace(args)` — wrapper for measuring text width via `getTextWidth` and cell styles.
  - Lifecycle: `addEventListener()` / `removeEventListener()` register UI hooks.

## Entry Points (Core)
**Class:** `WorkbookNumberFormat` (Workbook layer)
- Listens / notifies: localized format actions, number formatting requests and related events (via notify hooks in code).
- Key handlers:
  - `numberFormatting(args)` — apply a requested number format across a range; iterates cells, sets `cell.format` via `setCell` and calls UI refresh paths.
  - `getFormattedCell(args)` — central formatter that returns the formatted string for a cell value, delegating to type-specific helpers.
  - `updateLocalizedFormats(dependables)` / `localizedFormatAction()` / `parseToLocalizedFormat()` / `parseToDefaultFormat()` — map between localized format codes and default format IDs; support culture-specific decimal/group symbols and currency symbols.
  - Type-specific processors: `processCustomDateTime()`, `processCustomNumberFormat()`, `processCustomText()`, `applyNumberFormat()`, `currencyFormat()`, `percentageFormat()`, `accountingFormat()`, `scientificFormat()`, `fractionFormat()` — implement formatting rules and color/conditional segments.
  - Helpers: `isCustomType()`, `removeFormatColor()`, `getFormatForOtherCurrency()`, `convertToDefaultFormat()` and `configureLocalizedFormat()` for external mapping.
  - Validation: `checkDateFormat()` and `checkCustomTimeFormat()` for date/time format detection.

## ASCII Core Logic Flow
User or API requests format change → UI or Core issues `numberFormatting`/format change
         ↓
`WorkbookNumberFormat.numberFormatting()` validates range, iterates target cells, computes formatted text via `getFormattedCell()`
         ↓
`getFormattedCell()` delegates to appropriate processor (date/time/number/text/currency) and returns `formattedText` and alignment info
         ↓
Core persists `cell.format` via `setCell()` and triggers UI refresh (render pipeline)
         ↓
Spreadsheet `NumberFormat.refreshCellElement()` or `rowFillHandler()` updates DOM (`td`) with formatted text, handles fill/padding icons and measurements

## Operations (functions & responsibilities)
- `numberFormatting(args)` (Core)
  - Resolve sheet and range, compute `selectedRange`, iterate rows/cols, set `cell.format` using `setCell()` and trigger refresh or notify other subsystems (charts/conditional formats).

- `getFormattedCell(args)` (Core)
  - Entry to format a single cell value.
  - Uses `Internationalization` for locale formatting when appropriate and calls helper functions for custom patterns and special formats.

- `parseToLocalizedFormat()` / `parseToDefaultFormat()` / `updateLocalizedFormats()` (Core)
  - Translate format codes between localized culture representations and internal/default representations, update `localizedFormats` and `defaultFormats` maps.
  - Used by UI and export/import to ensure consistent format serialization.

- `applyNumberFormat()` and type helpers (Core)
  - Compute final string for numbers, percentages, currencies, accounting, scientific and fractions, honoring color/conditional segments and placeholders.

- `processCustomDateTime()` (Core)
  - Interpret custom date/time tokens, handle AM/PM variants and localized separators, return locale-correct date/time string.

- `rowFillHandler()` (UI)
  - Render repeated character fill for custom formats containing `*` by measuring available text width and inserting repeated characters with adjusted letter-spacing if necessary.

- `refreshCellElement()` (UI)
  - Called when a cell must be re-rendered; passes `NumberFormatArgs` to `parent.refreshNode()` to update DOM.

- `configureLocalizedFormat()` / `convertToDefaultFormat()` (public API functions)
  - Allow external mapping of format ids/codes and convert culture-specific formats to the default format representation.

## Validation & Safety
- Range validation: `numberFormatting()` checks target range against usedRange and skips out-of-range cells.
- Locale correctness: `updateLocalizedFormats()` and dependent functions adapt formats to the workbook's `locale` and numeric separators; decimal/group changes are detected and parsed.
- Readonly/Protection: callers should validate write permission before invoking `numberFormatting` (format application uses `setCell()` which triggers usual protection checks elsewhere).
- Date/time validation: `checkDateFormat()` and `checkCustomTimeFormat()` ensure values interpreted as dates/times are valid before formatting.
- Performance: heavy operations (formatting many cells) rely on batch updates and the UI layer refresh paths to avoid per-cell full reflows.

## Desired Outputs

User-facing
- Formatted cell text (numbers, currencies, dates, times, percentages, scientific, fractions, custom text) displayed correctly per locale and cell format rules.
- Visual fill effects for formats with `*` and correct alignment (right/left) depending on detected type.
- Proper behavior when editing: `isCustomType()` returns true in edit mode to preserve expected display.

System-level
- Events & Notifications:
  - Core format actions trigger internal notify flows to refresh views and related modules (charts, conditional formats).
  - Public notifications for localized format mapping: `localizedFormatAction` used to parse/convert localized formats.

- Model artifacts:
  - `cell.format` persisted in `CellModel`; `defaultFormats` / `localizedFormats` maps maintained in `WorkbookNumberFormat` for id/code mapping.

- DOM / CSS hooks:
  - UI expects to update cell content via `refreshCellElement` and uses classes like `.e-fill`, `.e-fill-before`, `.e-fill-sec` for fill rendering; filter buttons and iconset spans are considered when measuring space.

- API:
  - `getFormatFromType(type)` and `getTypeFromFormat(format)` utilities map semantic types to format codes and vice versa.
  - `convertToDefaultFormat(context, format)` and `configureLocalizedFormat(context, formatOptions)` expose localization mapping for external consumers.

## Implementation Notes (short)
- Maintain strict separation: Core owns format parsing/mapping and returning formatted strings; UI is responsible for DOM insertion, measuring and visual fill behavior.
- Reuse `Internationalization` for culture-aware number/date formatting; always consider `localeObj.decimal` and `localeObj.group` when parsing user-input values.
- Ensure batch updates when applying formats to ranges to avoid repeated DOM thrashing; use `parent.renderModule.refreshSheet()` or equivalent when needed.
- Keep `localizedFormats` and `defaultFormats` synchronized when workbook locale changes; expose `configureLocalizedFormat()` to allow host apps to provide culture-specific mappings.

---