# Charts API & events

> Every option, method and event of Birch UI Charts, with the exported helpers and types.

Everything here is exported from `@birchui/charts`. The tables below are generated from the package's TypeScript source; the [package reference](https://docs.birchui.com/api/charts.md) lists every exported type.

## createChart

```ts
import { createChart, type ChartApi, type ChartOptions } from '@birchui/charts';

const chart: ChartApi<Order> = createChart<Order>(container, options);
```

`createChart<TDatum>(container, options)` creates a chart inside `container` and returns its `ChartApi`. The generic parameter types `xKey`, `yKey`, `sizeKey` and `colorKey`, the `datum` in events and tooltips, and `setData()`. It throws a `TypeError` when `container` is not an element or `options` is not an object.

## Options

**`ChartOptions`** (interface from `@birchui/charts`, full reference: https://docs.birchui.com/api/charts.md)

```ts
interface ChartOptions<TDatum extends object = ChartDatum>
```

| Property | Type | Description |
| --- | --- | --- |
| `series` | `SeriesOptions<TDatum>[]` |  |
| `data?` | `readonly TDatum[]` |  |
| `title?` | `string` |  |
| `subtitle?` | `string` |  |
| `axes?` | `AxesOptions` |  |
| `legend?` | `boolean \| LegendOptions` |  |
| `tooltip?` | `boolean \| TooltipOptions<TDatum>` |  |
| `zoom?` | `boolean \| ZoomOptions` |  |
| `padding?` | `Padding` |  |
| `animation?` | `boolean \| AnimationOptions` |  |
| `theme?` | `ThemeName` |  |
| `palette?` | `readonly string[]` |  |
| `locale?` | `string` |  |
| `localeText?` | `LocaleTextInput` |  |
| `rtl?` | `boolean` |  |
| `injectStyles?` | `boolean` |  |
| `licenseKey?` | `string` |  |
| `height?` | `number \| string` |  |
| `sparkline?` | `boolean` |  |
| `accessibility?` | `AccessibilityOptions` |  |
| `renderer?` | `RendererOption` |  |
| `pixelRatio?` | `number` |  |

| Option | Default | Notes |
| --- | --- | --- |
| `series` | required | See [Series](https://docs.birchui.com/charts/series.md) |
| `data` | none | Shared rows; a series can override it with its own `data` |
| `title`, `subtitle` | none | Drawn above the plot and used in the accessible summary |
| `axes` | inferred | See [Axes](https://docs.birchui.com/charts/axes.md) |
| `legend` | automatic | Shown for two or more series, and always for pie and donut charts |
| `tooltip` | on, shared | See [Interaction](https://docs.birchui.com/charts/interaction.md#tooltip) |
| `zoom` | on | See [Interaction](https://docs.birchui.com/charts/interaction.md#zoom-and-pan) |
| `animation` | on, 450 ms | `false`, or `{ enabled, duration }`; skipped for reduced motion |
| `padding` | `16` | Pixels around the chart, as a number or `{ top, right, bottom, left }` |
| `theme` | `'auto'` | `'light'`, `'dark'` or `'auto'` |
| `palette` | `DEFAULT_PALETTE` | Series colors, used in order |
| `height` | `320` | Pixels or any CSS length; `32` for sparklines |
| `sparkline` | `false` | Hides axes, legend and title, and turns off zoom |
| `locale` | browser locale | Used for numbers, dates and the summary |
| `accessibility` | see [Accessibility](https://docs.birchui.com/charts/accessibility.md) | `label`, `dataTable`, `keyboardNavigation` |
| `renderer` | `'auto'` | `'canvas'`, `'svg'` or a custom backend factory, see [Rendering backends](#rendering-backends) |
| `pixelRatio` | `devicePixelRatio` | Canvas resolution |
| `injectStyles` | `true` | `false` to load `@birchui/charts/styles.css` yourself |
| `licenseKey` | the key from `setLicenseKey()` | See [Licensing](https://docs.birchui.com/charts/overview.md#licensing) |

## ChartApi

**`ChartApi`** (interface from `@birchui/charts`, full reference: https://docs.birchui.com/api/charts.md)

```ts
interface ChartApi<TDatum extends object = ChartDatum> extends Widget< ChartOptions<TDatum>, ChartEvents<TDatum> >
```

| Property | Type | Description |
| --- | --- | --- |
| `getOptions` | `() => ChartOptions<TDatum>` |  |
| `setData` | `(data: readonly TDatum[]) => void` |  |
| `setSeries` | `(series: SeriesOptions<TDatum>[]) => void` |  |
| `setSeriesVisible` | `(seriesId: string, visible: boolean) => void` |  |
| `isSeriesVisible` | `(seriesId: string) => boolean` |  |
| `setZoom` | `(range: [number, number] \| null) => void` |  |
| `getZoom` | `() => [number, number] \| null` |  |
| `resetZoom` | `() => void` |  |
| `setDataTableVisible` | `(visible: boolean) => void` |  |
| `toSVG` | `(options?: ExportOptions) => string` |  |
| `toPNG` | `(options?: ExportOptions) => Promise<Blob>` |  |
| `download` | `(format: ExportFormat, fileName?: string) => Promise<void>` |  |
| `readonly element` | `HTMLElement` | Inherited from Widget. |
| `update` | `(options: Partial<ChartOptions<TDatum>>) => void` | Inherited from Widget. |
| `on` | `<K extends keyof TEvents & string>(event: K, listener: Listener<TEvents[K]>) => () => void` | Inherited from Widget. |
| `destroy` | `() => void` | Inherited from Widget. |

| Method | Description |
| --- | --- |
| `update(partial)` | Apply only the options passed. Changes to `data` and `series` animate. |
| `getOptions()` | A copy of the current options |
| `setData(data)` | Shorthand for `update({ data })` |
| `setSeries(series)` | Shorthand for `update({ series })` |
| `setSeriesVisible(id, visible)` | Show or hide a series by ID, or a pie or donut slice by its label |
| `isSeriesVisible(id)` | Whether a series or slice is visible |
| `setZoom(range)` | Zoom the x axis to `[min, max]`, or reset with `null` |
| `getZoom()` | The current zoom range, or `null` |
| `resetZoom()` | Show the full range |
| `setDataTableVisible(visible)` | Show or visually hide the data table |
| `toSVG(options?)` | The chart as an SVG string |
| `toPNG(options?)` | A `Promise<Blob>` with a PNG image |
| `download(format, fileName?)` | Save as `'png'` or `'svg'` |
| `on(event, listener)` | Subscribe; returns an unsubscribe function |
| `destroy()` | Remove the chart and release every listener, observer and animation frame |
| `element` | The root element |

## Events

**`ChartEvents`** (interface from `@birchui/charts`, full reference: https://docs.birchui.com/api/charts.md)

```ts
interface ChartEvents<TDatum extends object = ChartDatum>
```

| Property | Type | Description |
| --- | --- | --- |
| `ready` | `{ chart: ChartApi<TDatum> }` |  |
| `pointClick` | `{ point: ChartPoint<TDatum>; event: MouseEvent \| KeyboardEvent }` |  |
| `legendToggle` | `{ seriesId: string; name: string; visible: boolean; sliceIndex?: number }` |  |
| `zoomChange` | `{ range: [number, number] \| null; source: ZoomSource }` |  |
| `seriesHover` | `{ seriesId: string \| null; point: ChartPoint<TDatum> \| null }` |  |

### ready

`{ chart }`. Fires once, in a microtask after `createChart()` returns, so a listener attached right after creation receives it.

### pointClick

`{ point, event }`. Fires when the user clicks a point, bar, slice or cell, or presses <kbd>Enter</kbd> or <kbd>Space</kbd> on a point focused with the keyboard. `point` is a `ChartPoint` with the series ID, name and index, the point index, the original `datum` and the raw `x` and `y`.

```ts
chart.on('pointClick', ({ point }) => {
  const order = point.datum;
  drawer.open(`/orders/${order.id}`);
});
```

### legendToggle

`{ seriesId, name, visible, sliceIndex? }`. Fires when a legend entry is toggled. For pie and donut slices, `sliceIndex` is the slice position and `seriesId` the pie series.

### zoomChange

`{ range, source }`. Fires on every zoom or pan. `range` is `[min, max]` in x axis units or `null` for the full range; `source` is `'drag'`, `'wheel'`, `'pinch'`, `'pan'`, `'keyboard'`, `'api'` or `'reset'`.

### seriesHover

`{ seriesId, point }`. Fires when the hovered or keyboard-focused point changes, with `null` values when nothing is hovered.

**`ChartPoint`** (interface from `@birchui/charts`, full reference: https://docs.birchui.com/api/charts.md)

```ts
interface ChartPoint<TDatum extends object = ChartDatum>
```

| Property | Type | Description |
| --- | --- | --- |
| `seriesId` | `string` |  |
| `seriesName` | `string` |  |
| `seriesIndex` | `number` |  |
| `index` | `number` |  |
| `datum` | `TDatum` |  |
| `x` | `unknown` |  |
| `y` | `unknown` |  |

## Exported helpers

| Export | Description |
| --- | --- |
| `chartDefinition` | The widget definition (`name: 'BirchChart'`, `tagName: 'birchui-chart'`, the five events) for framework factories and custom elements |
| `chartFromRange(values, headers, options?)` | Chart options from a 2-D range of cells. See [Grid integration](https://docs.birchui.com/charts/grid-integration.md) |
| `parseCellNumber(value)` | Parses numbers and formatted numeric text such as `$1,265,000`, `12.5%` and `(2,500)`; `NaN` otherwise |
| `sparklineSVG(values, options?)` | A sparkline as an SVG string |
| `escapeHtml(text)` | Escapes `&`, `<`, `>`, `"` and `'` for use in tooltip HTML |
| `checkPaletteContrast(palette, backgrounds, minimum?)` | Contrast report per color and background |
| `contrastRatio(a, b)` | WCAG contrast ratio of two colors |
| `DEFAULT_PALETTE` | The eight default series colors |
| `chartStyles` | The chart CSS as a string |
| `createRecordingRenderer()` | A render backend that records display lists, for tests |
| `walkPath(path, visitor)` | Iterates the commands of a recorded path |

## Rendering backends

Charts draw through a small `RenderBackend` interface that receives a display list of rectangles, paths, markers and text. Two backends are built in:

- **Canvas**, used by default (`renderer: 'auto'` or `'canvas'`).
- **SVG** (`renderer: 'svg'`), drawn as DOM elements. `'auto'` falls back to SVG where Canvas 2D is not available, and `'canvas'` falls back with a console warning.

Pass a factory to plug in your own backend. For tests, `createRecordingRenderer()` returns a backend that records each frame's display list instead of drawing, so you can assert on what a chart configuration would draw without a canvas:

```ts title="revenue-chart.test.ts"
import { createChart, createRecordingRenderer } from '@birchui/charts';

const host = document.body.appendChild(document.createElement('div'));
const recorder = createRecordingRenderer();
const chart = createChart(host, {
  data: revenue,
  series: [{ type: 'column', xKey: 'month', yKey: 'europe', name: 'Europe' }],
  renderer: recorder.factory,
  animation: false,
});

await new Promise(requestAnimationFrame);
const frame = recorder.lastFrame('main');
console.info(frame?.items.length, 'display items drawn');
chart.destroy();
```

`recorder.frames` holds every recorded frame with its layer, size, pixel ratio and display `items` (rectangles, paths, markers, text and groups of them); `lastFrame(layer?)` returns the latest one, and `destroyed()` counts destroyed backends, which helps assert that `destroy()` cleans up.

## Types

The package exports types for every option and payload, including `ChartOptions`, `SeriesOptions`, `AxisOptions`, `AxesOptions`, `LegendOptions`, `TooltipOptions`, `TooltipContext`, `TooltipPoint`, `ZoomOptions`, `AnimationOptions`, `AccessibilityOptions`, `ExportOptions`, `ChartPoint`, `ChartEvents`, `ChartApi`, `SeriesType`, `AxisType`, `CurveType`, `StackMode` and `ZoomSource`. See the [@birchui/charts reference](https://docs.birchui.com/api/charts.md).
