# Hyperlink Module data flow

## What It Does
Provides hyperlink insertion, editing, rendering, navigation, and removal across UI and Core layers, including:
- Insert/Edit hyperlink dialogs (web URL, this document cell reference, defined names).
- Render hyperlink elements in cells with appropriate styles and click behavior.
- Open hyperlinks (external URLs, internal addresses, named ranges) with event hooks for cancelation.
- Bulk import/restore of hyperlinks from serialized sheet models.
- Remove hyperlinks from ranges and support undo/redo and action lifecycle notifications.

## Entry Points

**Spreadsheet UI Class (`SpreadsheetHyperlink`)**
- `constructor(parent: Spreadsheet)` — initializes UI state, dialog builders and event listeners.
- `addEventListener()` / `removeEventListener()` — wire UI notifications: `initiateHyperlink`, `editHyperlink`, `openHyperlink`, `click`, `createHyperlinkElement`, `keyUp`, `deleteHyperlink`, `removeHyperlink`.
- `initiateHyperlinkHandler()` / `editHyperlinkHandler()` — show Insert/Edit Link dialog (tabs for WebPage/This Document), prepare dialog content, and validate inputs.
- `hyperlinkContent()` / `hyperEditContent()` — build dialog contents including URL/text inputs, cell reference tree, defined names, and placeholders.
- `dlgClickHandler(displayText)` — gather selected dialog items and call `insertHyperlink` (UI -> core insertion helper via notification).
- `createHyperlinkEle(args)` — render anchor element (`<a>`) into a cell cell DOM with proper href, text and style.
- `hyperlinkClickHandler(e)` / `hlOpenHandler(trgt, isClick?, event?)` — handle user clicks, validate edit-mode state, trigger `beforeHyperlinkClick` and `afterHyperlinkClick`, open URLs or navigate to internal references.
- `removeHyperlinkHandler(args)` / `removeHyperlink(args)` — remove hyperlink metadata and update cell DOM/UI; notify begin/complete actions.
- `showDialog()` / `showInvalidHyperlinkDialog()` — present alerts and validation messages to the user.
- `destroy()` / `getModuleName()` — lifecycle helpers.

**Workbook Core Class (`WorkbookHyperlink`)**
- `constructor(parent: Workbook)` — registers core event listeners for hyperlink model updates.
- `addEventListener()` / `removeEventListener()` — listens to `setLinkModel` and `importModelUpdate`.
- `setLinkHandler(args)` — core handler to apply hyperlink model to a cell range: normalizes addresses, handles sheet-scoped addresses, applies hyperlink object or string, sets display text and link styles, calls `updateCell`.
- `updateHyperLinksFromSheet()` — apply hyperlinks restored from import into actual cell objects via `setCell`.
- `getModuleName()` — module identifier.

## Core Logic Flow

```
User Action (Insert/Edit/Delete hyperlink via UI or programmatic API)
               ↓
UI dialog collects inputs (display text, URL or document reference, defined name)
               ↓
UI validates inputs and triggers core insertion: notify `setLinkModel` or call `insertHyperlink` API
               ↓
`WorkbookHyperlink.setLinkHandler`:
  - normalize sheet and range (support 'Sheet!A1:B2')
  - add protocol prefix (`http://`) when needed
  - iterate cells in target range and skip protected/locked cells
  - prepare `CellModel` updates with `hyperlink`, optional `value`, and style overrides
  - call `updateCell` for each affected cell and update used range
               ↓
Rendering:
  - on cell render the UI `createHyperlinkElement` builds an `<a>` with appropriate href and text
  - style adjustments (underline, color) and handling of visited color change
               ↓
Open flow:
  - user clicks hyperlink → `hyperlinkClickHandler` → `hlOpenHandler`
  - trigger `beforeHyperlinkClick` (cancelable)
  - resolve target: external URL (open in new tab/window) or internal reference (navigate via `goto`) or defined name (resolve range)
  - trigger `afterHyperlinkClick`
               ↓
Removal/Import:
  - remove operations call `removeHyperlink` to delete `hyperlink` property and update DOM
  - import flow (`importModelUpdate`) maps serialized hyperlink info into cells via `updateHyperLinksFromSheet`
```

## Operations Handled

1. Initialization & Event Wiring
   - Create and wire Insert/Edit dialogs, tree views for cell references, and input validation handlers (`keyUp`).
   - Hook core notifications for model updates during import.

2. Insertion & Edit
   - Support `Web Page` and `This Document` modes; allow display text customization.
   - Normalize URLs and automatically prefix missing protocol for web addresses.
   - Allow inserting the hyperlink across a selected range; apply value and style only where appropriate.
   - Fire `beginAction`/`completeAction` around remove actions; `insert` flows use `updateCell` with `preventEvt` or `triggerEvt` flags.

3. Rendering
   - `createHyperlinkEle` builds DOM anchor elements during cell rendering, choosing text from `cell.value` or hyperlink address and preserving formatting rules.
   - Ensure hyperlink style (color/underline) and visited-state handling via `updateCell` when opened.

4. Navigation (Open)
   - On click, verify not editing and not a formula click; issue `beforeHyperlinkClick` to allow cancellation or modification.
   - Distinguish external URLs vs internal references vs defined names; open external URLs in a new window when valid, otherwise show invalid dialog.

5. Removal & Import
   - `removeHyperlink` clears `cell.hyperlink`, adjusts `cell.style` if necessary, and updates UI cells in selection or range.
   - `updateHyperLinksFromSheet` restores hyperlinks from a serialized sheet (e.g., during workbook import) by setting `cell.hyperlink` entries.

## Validation & Safety

- Respect sheet protection and `protectSettings.insertLink`; block hyperlink insert/edit when not permitted and show `editAlert` or `readonlyAlert`.
- Skip locked cells when applying hyperlink range updates (use `isLocked`/`isReadOnly` checks).
- Validate URL formats (`isValidUrl`) and show `InvalidHyperlinkAlert` dialogs when malformed.
- During click, permit handlers to cancel via `beforeHyperlinkClick` event.
- When cell is in edit mode, clicks on hyperlinks are suppressed if the cell is being edited or formula detection indicates editing.

## Desired Outputs

User-Facing:
- Insert/Edit dialogs for web and document links with validation and friendly UX.
- Clickable links in cells that open external pages or navigate within the workbook.
- Clear error dialogs for invalid links and protections preventing edits.

System-Level:
- `setLinkModel` notification and `updateHyperLinksFromSheet` import mapping.
- Cell updates via `updateCell`/`setCell` that set `cell.hyperlink`, optional `cell.value`, and link styles.
- Events: `beforeHyperlinkClick`, `afterHyperlinkClick`, `beginAction`, `completeAction`, and model import hooks.

## Implementation Notes / Integration Points

- UI components: `Dialog`, `Tab`, `TreeView`, `TextBox`, and footer buttons; Dialog hooks (`beforeOpen`, `open`, `beforeClose`).
- Core helpers: `getCell`, `getSheet`, `getSheetIndex`, `getRangeIndexes`, `getSwapRange`, `setCell`, `updateCell`, `setUsedRange`.
- Utilities: `isCellReference`, `isValidUrl`, `isLocked`, `isReadOnly`, `getCellIndexes` and localization via `L10n`.
- Rendering integration: `createHyperlinkElement` is wired into cell render pipeline to replace cell text with anchor nodes.
- Import support: serialized `sheet.hyperLinks` arrays are consumed and converted to real `cell.hyperlink` entries by `updateHyperLinksFromSheet`.

