# Events

> Every event a NiiVue viewer fires, when it fires, and what its detail holds.

NiiVue uses the standard [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) API. Every controller instance is an `EventTarget`, so you use `addEventListener` and `removeEventListener` just like a DOM element.

All events are fully typed via `NVEventMap`. TypeScript will infer the correct `CustomEvent<T>` detail type for each event name when using `addEventListener`/`removeEventListener`.

## Quick Start

```js
import NiiVue from '@niivue/niivue'

const nv = new NiiVue({ backgroundColor: [0, 0, 0, 1] })
await nv.attachToCanvas(document.getElementById('gl'))

// Listen for crosshair navigation
nv.addEventListener('locationChange', (e) => {
  console.log(e.detail.string) // human-readable location
  console.log(e.detail.mm)     // [x, y, z] in mm
  console.log(e.detail.values) // per-volume intensity values
})

// Listen for any property change
nv.addEventListener('change', (e) => {
  console.log(`${e.detail.property} = ${e.detail.value}`)
})

// Clean up
const handler = (e) => { /* ... */ }
nv.addEventListener('volumeLoaded', handler)
nv.removeEventListener('volumeLoaded', handler)
```

## TypeScript Usage

Event listeners are fully typed. The detail type is inferred from the event name:

```ts
import NiiVue from '@niivue/niivue'

const nv = new NiiVue()

nv.addEventListener('locationChange', (evt) => {
  // evt is CustomEvent<NiiVueLocation> — fully typed
  const { mm, vox, values } = evt.detail
})

nv.addEventListener('documentLoaded', (evt) => {
  // evt is Event (no detail) — events with undefined payload use plain Event
})
```

## Emission timing

Events are emitted so that **the item an event references is present in the
collection (`nv.volumes` / `nv.meshes`) at the moment the event fires**:

- **Add / update / reorder** fire *after* the model changes — the item is now
  present or updated (`volumeLoaded`, `meshLoaded`, `volumeUpdated`,
  `meshUpdated`, `volumeOrderChanged`).
- **Removal** also fires *after* the model changes — the item is gone from the
  collection, and the event `detail` carries it together with its former index
  (`volumeRemoved`, `meshRemoved`, `signalRemoved`, `measurementRemoved`, and the
  bulk forms, which emit once per item in reverse index order).

**Consumer corollary:** a listener may re-read the collection synchronously
inside any of these events and see the post-mutation state. To inspect a
departing item, use `detail`. New emitting methods should preserve this
ordering: emit after the mutation.

## Event Reference

### User Interaction

#### `locationChange`
Fired when the crosshair position changes (user click, keyboard navigation, or programmatic), and on a slide plane when a landing tile changes the slide samples under the crosshair.

| Field | Type | Description |
|-------|------|-------------|
| `mm` | `[number, number, number]` | Position in mm |
| `vox` | `[number, number, number]` | Rounded voxel indices |
| `frac` | `[number, number, number]` | Scene fraction [0..1] |
| `xy` | `[number, number]` | Mouse position on canvas |
| `axCorSag` | `number` | Slice orientation (0=sagittal, 1=coronal, 2=axial); `SLICE_TYPE.RENDER` for a 3D render depth pick |
| `values` | `NiiVueLocationValue[]` | Per-volume data (name, value, label) |
| `slide` | `NiiVueLocationSlide?` | On a slide plane, when the crosshair projected onto it is on the slide: `{id, name, x, y, samples}`, base-level pixel and one `NVSlideSample` per channel from the tile cache (`value` null when missing). Re-emitted when a landing tile changes the samples |
| `string` | `string` | Human-readable location with values |

```js
nv.addEventListener('locationChange', (e) => {
  document.getElementById('info').textContent = e.detail.string
})
```

#### `frameChange`
Fired when the current 4D frame changes on a volume. For a volume with a
`frameSource` (frames fetched on demand) it fires once the new frame is in
`img`, for each volume of the source's group.

| Field | Type | Description |
|-------|------|-------------|
| `volume` | `NVImage` | The volume whose frame changed |
| `frame` | `number` | New frame index (0-based) |

```js
nv.addEventListener('frameChange', (e) => {
  slider.value = e.detail.frame
})
```

#### `dragRelease`
Fired when any drag interaction completes on a 2D slice.

| Field | Type | Description |
|-------|------|-------------|
| `tileIdx` | `number` | Index of the tile where drag occurred |
| `axCorSag` | `number` | Slice orientation |
| `mmLength` | `number` | Drag distance in mm |
| `voxStart` | `[number, number, number]` | Start position (voxel, rounded) |
| `voxEnd` | `[number, number, number]` | End position (voxel, rounded) |
| `mmStart` | `[number, number, number]` | Start position in mm |
| `mmEnd` | `[number, number, number]` | End position in mm |

#### `measurementCompleted`
Fired when a distance measurement line is completed — by an interactive drag in
`DRAG_MODE.measurement` or by a programmatic `addMeasurement` call. Fired after
the measurement is appended, so it is already in `getMeasurements()`. A click (zero length) adds nothing.

| Field | Type | Description |
|-------|------|-------------|
| `startMM` | `[number, number, number]` | Start point in mm |
| `endMM` | `[number, number, number]` | End point in mm |
| `distance` | `number` | Distance in mm |
| `sliceIndex` | `number` | Slice tile index |
| `sliceType` | `number` | Slice orientation |
| `slicePosition` | `number` | Slice position as a scene fraction (recorded from `scene.crosshairPos`), not mm |

#### `measurementRemoved`
Fired by `removeMeasurement` after the measurement is removed; `detail`
carries the removed measurement and its former index.

| Field | Type | Description |
|-------|------|-------------|
| `measurement` | `CompletedMeasurement` | The measurement being removed |
| `index` | `number` | Its index in the measurement list |

#### `angleCompleted`
Fired when an angle measurement (two lines) is completed.

| Field | Type | Description |
|-------|------|-------------|
| `firstLine` | `{ startMM, endMM }` | First line endpoints in mm |
| `secondLine` | `{ startMM, endMM }` | Second line endpoints in mm |
| `angle` | `number` | Angle in degrees |
| `sliceIndex` | `number` | Slice tile index |
| `sliceType` | `number` | Slice orientation |
| `slicePosition` | `number` | Slice position as a scene fraction (recorded from `scene.crosshairPos`), not mm |

#### `pointerUp`
Fired on every pointer release over the canvas.

| Field | Type | Description |
|-------|------|-------------|
| `x` | `number` | Pointer X offset on canvas |
| `y` | `number` | Pointer Y offset on canvas |
| `button` | `number` | Mouse button (0=left, 1=middle, 2=right) |

---

### Loading & Removal

#### `volumeLoaded`
Fired after a volume is successfully added (via `addVolume()` or `loadVolumes()`). Fires once per volume.

| Field | Type | Description |
|-------|------|-------------|
| `volume` | `NVImage` | The newly loaded volume |

#### `meshLoaded`
Fired after a mesh is successfully added (via `addMesh()` or `loadMeshes()`). Fires once per mesh added; a mesh the model cannot read is logged and fires nothing. `detail.mesh` is the added mesh, not the last entry of `nv.meshes`.

| Field | Type | Description |
|-------|------|-------------|
| `mesh` | `NVMesh` | The newly loaded mesh |

#### `volumeRemoved`
Fired after a volume is removed — by `removeVolume(index)`, or once per volume in reverse order by `removeAllVolumes()`. The volume is no longer in `nv.volumes`; `detail` carries it and its former index.

| Field | Type | Description |
|-------|------|-------------|
| `volume` | `NVImage` | The volume being removed |
| `index` | `number` | Index in the volumes array |

#### `meshRemoved`
Fired after a mesh is removed — by `removeMesh(index)`, or once per mesh in reverse order by `removeAllMeshes()`. The mesh is no longer in `nv.meshes`; `detail` carries it and its former index.

| Field | Type | Description |
|-------|------|-------------|
| `mesh` | `NVMesh` | The mesh being removed |
| `index` | `number` | Index in the meshes array |

#### `documentLoaded`
Fired after `loadDocument()` completes. No detail payload — the loaded state is reflected in the model. By then any half-drawn annotation, the annotation selection, and the `annotationUndo()` history from the previous scene have been cleared.

```js
nv.addEventListener('documentLoaded', () => {
  console.log(`Loaded ${nv.volumes.length} volumes`)
})
```

---

### View Lifecycle

#### `viewAttached`
Fired after `attachToCanvas()` or `attachTo()` completes successfully (GPU initialized, interaction handlers set up).

| Field | Type | Description |
|-------|------|-------------|
| `canvas` | `HTMLCanvasElement` | The attached canvas |
| `backend` | `'webgpu' \| 'webgl2'` | Active rendering backend |

```js
nv.addEventListener('viewAttached', (e) => {
  console.log(`Rendering with ${e.detail.backend}`)
})
```

#### `viewDestroyed`
Fired when `destroy()` is called, before teardown begins. No detail payload.

#### `canvasResize`
Fired when the canvas is resized (via ResizeObserver).

| Field | Type | Description |
|-------|------|-------------|
| `width` | `number` | New canvas clientWidth |
| `height` | `number` | New canvas clientHeight |

```js
nv.addEventListener('canvasResize', (e) => {
  overlay.style.width = `${e.detail.width}px`
})
```

---

### View Control

#### `azimuthElevationChange`
Fired when `azimuth` or `elevation` is set programmatically, or when the user
rotates the 3D render view (mouse drag or the H/J/K/L keys).

| Field | Type | Description |
|-------|------|-------------|
| `azimuth` | `number` | Current azimuth (degrees) |
| `elevation` | `number` | Current elevation (degrees) |

#### `clipPlaneChange`
Fired when a clip plane is modified via `setClipPlane()` or `setClipPlaneDepthAziElev()`.

| Field | Type | Description |
|-------|------|-------------|
| `clipPlane` | `number[]` | `[depth, azimuth, elevation]` |

#### `sliceTypeChange`
Fired when `sliceType` is set.

| Field | Type | Description |
|-------|------|-------------|
| `sliceType` | `number` | New slice type value |

---

### Data Updates

#### `volumeUpdated`
Fired after `setVolume()` applies property changes to a volume, including a
`colormap` change between a continuous and a label colormap.
Not fired by `updateVolumeData()`, which edits voxel values (typically every
frame) without changing any display option.

| Field | Type | Description |
|-------|------|-------------|
| `volumeIndex` | `number` | Index of the updated volume |
| `volume` | `NVImage` | The volume (after update) |
| `changes` | `VolumeUpdate` | The options that were applied; `calMin`/`calMax`, when present, are the resolved window (a NaN request reports the image default, a CT map's fill its window) |

```js
nv.addEventListener('volumeUpdated', (e) => {
  const { volumeIndex, changes } = e.detail
  if (changes.colormap) updateColormapUI(volumeIndex, changes.colormap)
})
```

#### `meshUpdated`
Fired after `setMesh()` applies property changes to a mesh, or after a
scalar-overlay layer change (`addMeshLayer`, `removeMeshLayer`,
`setMeshLayerProperty`). Not fired by `updateMeshPositions()`, which moves
vertices (typically every frame) without changing any display option.

| Field | Type | Description |
|-------|------|-------------|
| `meshIndex` | `number` | Index of the updated mesh |
| `mesh` | `NVMesh` | The mesh (after update) |
| `changes` | `MeshUpdate` | The options that were applied — **empty (`{}`) for layer changes**, since layer state isn't a `MeshUpdate` diff; re-read `mesh.layers` |

#### `colormapAdded`
Fired after `addColormap()` or `addColormapFromUrl()` registers a new user-defined colormap. The new LUT is then visible to volumes, mesh layers, colorbars, connectomes, and tracts.

| Field | Type | Description |
|-------|------|-------------|
| `name` | `string` | Registered colormap name |

```js
nv.addEventListener('colormapAdded', (e) => {
  populateColormapDropdown(nv.colormaps)
  console.log(`registered ${e.detail.name}`)
})
```

---

### Chunk Streaming

Chunked (oversized) volumes stream their bricks to the GPU over multiple
frames. These events replace polling `chunkStreamStats()` on a timer. Both
carry a `ChunkStreamDetail` — the same shape as the non-null return of
`chunkStreamStats()`, and the method reads back the same counts at emit time.

| Field | Type | Description |
|-------|------|-------------|
| `resident` | `number` | Bricks currently GPU-resident |
| `pending` | `number` | Bricks queued for upload |
| `inFlight` | `number` | Bricks mid-upload |
| `total` | `number` | Bricks in the plan |
| `staleDropped` | `number` | Cumulative queued uploads retired because the view moved on |
| `predicted` | `number` | Cumulative speculative source reads |
| `retiring` | `number` | Replaced bricks a `keepUntilCovered` swap still draws |
| `retiringBytes` | `number` | GPU bytes those bricks hold |
| `decoded` | `ByteLruStats` | Decoded-chunk (CPU byte) tier counters |

#### `chunkStreamProgress`
Fired on a drawn frame while streaming is outstanding (`pending + inFlight > 0`),
whenever a count changed since the last emission — identical back-to-back
snapshots are skipped, so the render loop's cadence bounds the rate (no timer).
The final, settled counts are also emitted as progress, immediately before
`chunkStreamIdle`.

#### `chunkStreamIdle`
Fired when the stream settles: a drawn frame had `pending + inFlight > 0`, and a
later drawn frame is complete — nothing queued or mid-upload for the working set
that frame requested, and no brick still cross-fading in. It is emitted after
that frame's draw has been submitted, so the canvas shows every brick the frame
asked for and a listener may capture it.

What idle does and does not promise:

- `resident < total` on the idle frame is normal under a residency budget: idle
  means the visible working set is resident, not the whole plan.
- A brick whose upload failed is not resident and does not settle the stream;
  the next drawn frame re-requests it.
- Because `chunkStreamStats()` returns zeroed counts (not null) whenever a view
  is attached, idle is defined on this transition — it never fires for a view
  that is attached but has not streamed.
- Streaming that resumes (e.g. a camera move queues new bricks) re-arms it, so
  it fires once per settle.

```js
nv.addEventListener('chunkStreamProgress', (e) => {
  spinner.textContent = `${e.detail.resident} / ${e.detail.total} bricks`
})
nv.addEventListener('chunkStreamIdle', () => {
  spinner.hidden = true // the frame on screen shows every brick it asked for
})
```

---

### Drawing

#### `drawingChanged`
Fired on drawing lifecycle events and user strokes.

| Field | Type | Description |
|-------|------|-------------|
| `action` | `'stroke' \| 'create' \| 'close' \| 'undo' \| 'load' \| 'update'` | What happened |

- `'create'` — `createEmptyDrawing()` was called
- `'stroke'` — user completed a pen stroke (pointerup)
- `'undo'` — `drawUndo()` restored a previous state
- `'close'` — `closeDrawing()` destroyed the drawing
- `'load'` — `loadDrawing()` loaded a drawing from a volume
- `'update'` — the drawing bitmap was updated programmatically (extension `ctx.drawing.update()`)

#### `drawingEnabled`
Fired when `drawIsEnabled` is set.

| Field | Type | Description |
|-------|------|-------------|
| `isEnabled` | `boolean` | Whether drawing mode is now active |

#### `penValueChanged`
Fired when `drawPenValue` is set.

| Field | Type | Description |
|-------|------|-------------|
| `penValue` | `number` | New pen label index |

---

### Annotations

#### `annotationAdded`
Fired when a new vector annotation is added.

| Field | Type | Description |
|-------|------|-------------|
| `annotation` | `VectorAnnotation` | The newly added annotation |

#### `annotationRemoved`
Fired when a vector annotation is removed.

| Field | Type | Description |
|-------|------|-------------|
| `id` | `string` | ID of the removed annotation |

#### `annotationChanged`
Fired on annotation editing events (draw, erase, move, resize, undo, redo, clear).

A draw fires `annotationAdded` and then `annotationChanged` with the new id in `added`; annotations it merged or cut appear in `updated` or `removed`. `addAnnotation` and `removeAnnotation` fire only `annotationAdded` / `annotationRemoved`; `loadAnnotationsJSON` and `loadDocument` fire neither.

| Field | Type | Description |
|-------|------|-------------|
| `action` | `'draw' \| 'erase' \| 'move' \| 'resize' \| 'undo' \| 'redo' \| 'clear'` | What happened |
| `added` | `string[]` | Ids of annotations the change added |
| `updated` | `string[]` | Ids of annotations whose geometry, stats or text changed |
| `removed` | `string[]` | Ids of annotations the change removed |

Ids are `VectorAnnotation.id`, which must be unique (drawn annotations get a random UUID).

---

### Generic Property Change

#### `change`
Fired by every property setter on the controller. Use this for unified state tracking without subscribing to individual events.

| Field | Type | Description |
|-------|------|-------------|
| `property` | `string` | Property name (matches the setter name, e.g. `'azimuth'`, `'isColorbarVisible'`) |
| `value` | `unknown` | New value |

```js
// Log all property changes
nv.addEventListener('change', (e) => {
  console.log(`${e.detail.property} changed to`, e.detail.value)
})

// React to specific properties
nv.addEventListener('change', (e) => {
  if (e.detail.property === 'backgroundColor') {
    document.body.style.background = `rgba(${e.detail.value})`
  }
})
```

Properties that emit `change` include all controller setters: `azimuth`, `elevation`, `crosshairPos`, `sliceType`, `backgroundColor`, `isColorbarVisible`, `volumeIllumination`, `meshXRay`, `drawPenValue`, `primaryDragMode`, and all others. Some setters also emit a more specific event (e.g. `azimuthElevationChange`, `sliceTypeChange`). Setting `annotationTool` to its current value is a no-op: it emits no `change` and keeps the selection and any half-drawn shape.

---

## Migrating from Callbacks

The old callback-based API (`onLocationChange`, `onFrameChange`, `onDragRelease`) has been replaced by events. Migration is straightforward:

```js
// Before (callbacks in constructor)
const nv = new NiiVue({
  onLocationChange: (data) => { /* ... */ },
  onFrameChange: (volume, frame) => { /* ... */ },
  onDragRelease: (info) => { /* ... */ },
})

// After (addEventListener)
const nv = new NiiVue({})
nv.addEventListener('locationChange', (e) => { /* e.detail === data */ })
nv.addEventListener('frameChange', (e) => {
  const { volume, frame } = e.detail
})
nv.addEventListener('dragRelease', (e) => { /* e.detail === info */ })
```

Key differences:
- Event data is in `e.detail` (standard `CustomEvent` pattern)
- Listeners can be added/removed at any time, not just at construction
- Multiple listeners per event are supported
- Events with no payload (e.g. `documentLoaded`, `viewDestroyed`) use plain `Event` instead of `CustomEvent`

## Exported Types

All event detail types are exported from the package for use in TypeScript:

```ts
import type {
  NVEventMap,
  NVEventTarget,
  FrameChangeDetail,
  VolumeLoadedDetail,
  MeshLoadedDetail,
  VolumeRemovedDetail,
  MeshRemovedDetail,
  AzimuthElevationChangeDetail,
  ClipPlaneChangeDetail,
  SliceTypeChangeDetail,
  PenValueChangedDetail,
  DrawingChangedDetail,
  DrawingEnabledDetail,
  PropertyChangeDetail,
  PointerUpDetail,
  VolumeUpdatedDetail,
  MeshUpdatedDetail,
  ViewAttachedDetail,
  CanvasResizeDetail,
  AnnotationAddedDetail,
  AnnotationRemovedDetail,
  AnnotationChangedDetail,
  ColormapAddedDetail,
  ChunkStreamDetail,
  ByteLruStats,
} from '@niivue/niivue'
```
