# Chart

## Overview

`@astryx-vue/charts` uses d3 to calculate scales and geometry, then renders SVG with Vue. Each chart contains a `` canvas and one or more series, such as lines, bars, or areas.

## Install

::: code-group
```sh [pnpm]
pnpm add @astryx-vue/charts
```

```sh [npm]
npm install @astryx-vue/charts
```

```sh [yarn]
yarn add @astryx-vue/charts
```

```sh [bun]
bun add @astryx-vue/charts
```
:::

`@astryx-vue/charts` depends on `@astryx-vue/core` and `vue`. Make sure both are installed in your project.

The library includes base styles. Import the full stylesheet in your entry file:

```ts
import '@astryx-vue/charts/charts.css'
```

To load styles on demand, import individual files from `@astryx-vue/charts/styles/`, such as `chart.css`, `chart-axis.css`, `chart-grid.css`, `chart-legend.css`, `chart-tooltip.css`, or `chart-swatch.css`.

## Your first chart

A minimal chart requires three props on ``:
- `data`: An array of objects where each item represents one row of data.
- `xKey`: The field name in each row to use for the horizontal x-axis.
- `series`: An array of series definitions created with functions such as `line()` or `bar()`.

Here is the shortest working line chart:

```vue
<script setup lang="ts">
import { Chart, ChartAxis, ChartGrid, line } from '@astryx-vue/charts'

// 1. Prepare data
const data = [
  { month: 'Jan', revenue: 100, cost: 60 },
  { month: 'Feb', revenue: 150, cost: 80 },
  { month: 'Mar', revenue: 120, cost: 70 },
]

// 2. Define series: two lines reading revenue and cost
const series = [
  line('revenue', { label: 'Revenue' }),
  line('cost', { label: 'Cost' }),
]
</script>

<template>
  <Chart :data="data" x-key="month" :series="series" :height="260" legend tooltip>
    <template #grid>
      <ChartGrid />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" />
    </template>
  </Chart>
</template>
```

Here is the live result:

### Line chart

Line chart with revenue and cost series, grid lines, axes, a bottom legend, and hover tooltips.

```vue
<script setup lang="ts">
import { Chart, ChartAxis, ChartGrid, line } from '@astryx-vue/charts'
import { monthly } from './data'

const series = [
  line('revenue', { label: '收入' }),
  line('cost', { label: '成本' }),
]
</script>

<template>
  <Chart :data="monthly" x-key="month" :series="series" :height="260" title="每月收入与成本" legend tooltip>
    <template #grid>
      <ChartGrid />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" />
    </template>
  </Chart>
</template>
```

## Series

A series defines a visual representation of data on the chart. A series object holds internal state during layout and rendering. Because of this, provide each series object to one `` only. Create fresh series definitions for each chart instance.

When data has missing values (`null`, `undefined`) or non-finite numbers (`NaN`, `Infinity`), line marks break cleanly and leave an empty gap. They never drop to zero or draw false connections across gaps.

When `yDomain` is omitted, `yBaseline` controls how the y-axis range is calculated:
- `'auto'` (default): Marks with a zero baseline (bars, areas) include 0 in the scale. Continuous point marks (lines, dots) keep small padding on both ends so points do not clip at the edges.
- `'zero'`': Expands the scale symmetrically around 0. Useful for values that swing positive and negative, such as profit and loss.
- `'data'`: Clamps tightly to the minimum and maximum data values without forcing 0 or adding edge padding.

### Line (`line`)

A line series shows continuous trends over time or across categories.

```ts
declare function line(dataKey: string, options?: LineOptions): SeriesDef
```

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `color` | `string` | Auto from theme palette | Line color. |
| `curve` | `'linear' \| 'monotone' \| 'natural' \| 'step'` | `'monotone'` | Curve interpolation method. Options are linear, monotone cubic spline, natural spline, and step. |
| `strokeWidth` | `number` | `2` | Line stroke width in pixels. |
| `dots` | `boolean` | `false` | Whether to render solid circular dots at each data point. |
| `label` | `string` | `dataKey` | Human-readable name shown in legends and tooltips. |

### Bar (`bar`)

A bar series compares magnitudes across categories or time steps. Bars with the same `group` split the category bandwidth and sit side by side. Bars with the same `stack` stack on top of each other.

```ts
declare function bar(dataKey: string, options?: BarOptions): SeriesDef
```

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `color` | `ColorAccessor` | Auto from theme palette | Bar fill color. Accepts a color string or a function `(datum, index) => string`. |
| `opacity` | `number` | `1` | Bar opacity, between 0 and 1. |
| `radius` | `number` | `4` | Corner radius on the bar top in pixels. In stacked bars, only the top segment receives rounded corners. |
| `stack` | `string` | `undefined` | Stack group name. Series sharing a `stack` accumulate upward from the baseline. |
| `group` | `string` | `undefined` | Side-by-side group name. Series sharing a `group` sit next to each other within each category. |
| `label` | `string` | `dataKey` | Human-readable name shown in legends and tooltips. |

### Bar chart

Bar chart example: revenue and cost share a group to display side by side for each month.

```vue
<script setup lang="ts">
import { bar, Chart, ChartAxis, ChartGrid } from '@astryx-vue/charts'
import { monthly } from './data'

// 没写 group 或 stack 的柱子会各占一列；这里两个系列同属一个 group，并排显示。
const series = [
  bar('revenue', { group: 'money', label: '收入', radius: 4 }),
  bar('cost', { group: 'money', label: '成本', radius: 4 }),
]
</script>

<template>
  <Chart :data="monthly" x-key="month" :series="series" :height="260" title="每月收入与成本" legend tooltip>
    <template #grid>
      <ChartGrid />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" />
    </template>
  </Chart>
</template>
```

### Area (`area`)

An area series fills the region below a line. It is useful for showing total volume and changing proportions over time. Giving multiple area series the same `stack` name stacks them in order.

```ts
declare function area(dataKey: string, options?: AreaOptions): SeriesDef
```

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `color` | `string` | Auto from theme palette | Area fill color. |
| `opacity` | `number` | `0.3` | Area fill opacity. |
| `curve` | `'linear' \| 'monotone' \| 'natural' \| 'step'` | `'monotone'` | Curve interpolation algorithm. |
| `stack` | `string` | `undefined` | Stack group name. Areas sharing a `stack` stack sequentially. |
| `gradient` | `boolean` | `false` | Whether to apply a vertical gradient fill. |
| `stroke` | `boolean` | `true` | Whether to draw a stroke line along the top edge of the area. |
| `label` | `string` | `dataKey` | Human-readable name shown in legends and tooltips. |

### Stacked area chart

Stacked area chart: cost and profit share a stack identifier to show overall totals.

```vue
<script setup lang="ts">
import { area, Chart, ChartAxis, ChartGrid } from '@astryx-vue/charts'
import { monthly } from './data'

// stack 名字相同的面积会一层叠一层往上长。
const series = [
  area('cost', { stack: 'total', label: '成本' }),
  area('profit', { stack: 'total', label: '利润' }),
]
</script>

<template>
  <Chart :data="monthly" x-key="month" :series="series" :height="260" title="成本加利润等于收入" legend tooltip>
    <template #grid>
      <ChartGrid />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" />
    </template>
  </Chart>
</template>
```

### Dot (`dot`)

A dot series shows the distribution of discrete data points.

```ts
declare function dot(dataKey: string, options?: DotOptions): SeriesDef
```

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `color` | `ColorAccessor` | Auto from theme palette | Dot color. Accepts a color string or a per-point accessor function. |
| `radius` | `number` | `4` | Dot radius in pixels. |
| `opacity` | `number` | `0.8` | Dot opacity. |
| `dodge` | `boolean` | `false` | When multiple points share the same x value, offsets them horizontally to reduce overlap. |
| `label` | `string` | `dataKey` | Human-readable name shown in legends and tooltips. |

### Dot chart

Dot chart example: distribution of test scores across sample sizes and control groups.

```vue
<script setup lang="ts">
import { Chart, ChartAxis, ChartGrid, dot } from '@astryx-vue/charts'
import { samples } from './data'

const series = [
  dot('score', { label: '得分', radius: 5 }),
  dot('other', { label: '对照组', radius: 5 }),
]
</script>

<template>
  <!-- 数值 x 轴默认紧贴数据，最左和最右的点会被切掉一半；用 x-domain 留出边距。 -->
  <Chart :data="samples" x-key="size" :x-domain="[0, 70]" :series="series" :height="260" title="样本量与得分" legend tooltip>
    <template #grid>
      <ChartGrid vertical />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" />
    </template>
  </Chart>
</template>
```

### Band (`band`)

A band series fills a translucent area between an upper and a lower boundary field. It is often used to show forecast confidence intervals. Band marks are annotations, so they do not appear in legends or tooltips.

```ts
declare function band(options: BandOptions): SeriesDef
```

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `upper` | `string` | **Required** | Field name for the upper boundary value. |
| `lower` | `string` | **Required** | Field name for the lower boundary value. |
| `color` | `string` | `'var(--color-accent)'` | Fill color for the band area. |
| `opacity` | `number` | `0.15` | Fill opacity for the band area. |

### Reference line (`referenceLine`)

A reference line marks a specific horizontal or vertical threshold on the chart, or fills a shaded region between two horizontal values. Reference lines are annotations, so they do not appear in legends or tooltips.

```ts
declare function referenceLine(options: ReferenceLineOptions): SeriesDef
```

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `y` | `number` | `undefined` | Draws a horizontal line at this y-axis value. |
| `y2` | `number` | `undefined` | Second y-axis value. Providing both `y` and `y2` shades a reference band between them. |
| `x` | `number` | `undefined` | Draws a vertical line at this x-axis value. |
| `color` | `string` | `'var(--astryx-color-border-emphasized)'` | Line or band fill color. |
| `strokeWidth` | `number` | `1` | Stroke width in pixels. |
| `strokeDasharray` | `string` | `undefined` | Dash pattern string, such as `'4 4'`. |
| `label` | `string` | `undefined` | Text label displayed alongside the line. |
| `labelPosition` | `'start' \| 'end'` | `'end'` | Label placement along the line: start/end corresponds to left/right for horizontal lines, and bottom/top for vertical lines. |
| `bandOpacity` | `number` | `0.1` | Fill opacity for the reference band (active only when `y2` is set). |

### Band and reference line

Band and reference line: shaded forecast interval in the background, actual line in the middle, and a dashed target threshold on top.

```vue
<script setup lang="ts">
import { band, Chart, ChartAxis, ChartGrid, line, referenceLine } from '@astryx-vue/charts'
import { forecast } from './data'

// 区间带画在最前面，折线和参考线叠在它上面。
const series = [
  band({ upper: 'high', lower: 'low' }),
  line('actual', { label: '实际值', dots: true }),
  referenceLine({ y: 60, label: '目标 60', strokeDasharray: '4 4' }),
]
</script>

<template>
  <Chart :data="forecast" x-key="week" :series="series" :height="260" title="预测区间与目标线" tooltip>
    <template #grid>
      <ChartGrid />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" />
    </template>
  </Chart>
</template>
```

### Error bar (`errorBar`)

An error bar (whisker) displays value uncertainty. It is usually paired with `bar()` or `dot()`. Boundary fields use absolute values, allowing asymmetric error intervals. If a row lacks an upper or lower bound, the chart skips that point instead of drawing misleading lines to zero. Error bars are annotations, so they do not appear in legends or tooltips.

```ts
declare function errorBar(options: ErrorBarOptions): SeriesDef
```

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `high` | `string` | **Required** | Field name for the upper bound (absolute value). |
| `low` | `string` | **Required** | Field name for the lower bound (absolute value). |
| `color` | `string` | `'var(--astryx-color-text-primary)'` | Stroke color. |
| `strokeWidth` | `number` | `1.5` | Stroke width in pixels. |
| `capWidth` | `number` | `8` | Width in pixels of the horizontal end caps. |

### Error bars

Error bars: paired with a bar chart to display group averages alongside 95% confidence intervals.

```vue
<script setup lang="ts">
import { bar, Chart, ChartAxis, ChartGrid, errorBar } from '@astryx-vue/charts'
import { experiments } from './data'

// errorBar 读的是上下界的绝对值，所以不对称的区间也能画。
const series = [
  bar('mean', { label: '均值', radius: 4 }),
  errorBar({ high: 'upper95', low: 'lower95' }),
]
</script>

<template>
  <Chart :data="experiments" x-key="group" :series="series" :height="260" title="各组均值与 95% 区间" tooltip>
    <template #grid>
      <ChartGrid />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" />
    </template>
  </Chart>
</template>
```

### Candlestick (`candlestick`)

A candlestick series displays open, high, low, and close prices over time, commonly used in financial charts.

```ts
declare function candlestick(options: CandlestickOptions): SeriesDef
```

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `open` | `string` | **Required** | Field name for the open price. |
| `high` | `string` | **Required** | Field name for the high price. |
| `low` | `string` | **Required** | Field name for the low price. |
| `close` | `string` | **Required** | Field name for the close price. |
| `upColor` | `string` | `'var(--astryx-color-success)'` | Color for up candles, where close is greater than or equal to open. |
| `downColor` | `string` | `'var(--astryx-color-error)'` | Color for down candles, where close is lower than open. |

### Candlestick

Candlestick chart: displays daily price movements for a stock or commodity over a week.

```vue
<script setup lang="ts">
import { candlestick, Chart, ChartAxis, ChartGrid } from '@astryx-vue/charts'
import { prices } from './data'

const series = [candlestick({ open: 'open', high: 'high', low: 'low', close: 'close' })]
</script>

<template>
  <Chart :data="prices" x-key="day" :series="series" :height="260" y-baseline="data" title="一周价格走势">
    <template #grid>
      <ChartGrid />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" />
    </template>
  </Chart>
</template>
```

## Axes, grid, legend, tooltip

Supporting chart elements are provided as individual components. You can combine and configure them independently. Setting `legend` or `tooltip` to `true` on `` enables their defaults. Pass an object to customize position and layout.

### Axes (`ChartAxis`)

Axes render along chart edges to display ticks and label text.

| Prop | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `position` | `'top' \| 'right' \| 'bottom' \| 'left'` | **Required** | Edge to place the axis on. |
| `tickCount` | `number` | `5` | Desired number of ticks. d3 uses this as a hint to find clean intervals. |
| `maxTicks` | `number` | `undefined` | Maximum number of tick labels to render. Excess ticks are skipped at uniform intervals. |
| `tickFormat` | `(value: unknown) => string` | `undefined` | Custom tick label formatting function. |
| `truncate` | `number` | `undefined` | Maximum characters for tick labels before truncating with an ellipsis. |
| `animated` | `boolean` | `true` | Whether to smoothly animate tick transitions when positions change. |
| `showAxisLine` | `boolean` | `true` on bottom axis only | Whether to render the axis baseline. If `showTicks` is true, the baseline is always drawn regardless of position. |
| `showTicks` | `boolean` | `false` | Whether to draw short perpendicular tick lines at each step. |

### Grid (`ChartGrid`)

Grid lines render behind series elements to help align values visually.

| Prop | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `horizontal` | `boolean` | `true` | Whether to draw horizontal grid lines. |
| `vertical` | `boolean` | `false` | Whether to draw vertical grid lines. |
| `tickCount` | `number` | `5` | Approximate number of grid lines. Matching this with `` aligns grid lines with axis ticks. |

### Legend (`ChartLegend`)

A legend lists series names alongside their representative colors. Setting `legend` on `` shows the legend (off by default), or use the `` component directly.

| Prop | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `items` | `LegendItem[]` | `[]` | Explicit array of legend items. Inferred automatically from series when omitted. |
| `position` | `'top' \| 'bottom' \| 'start' \| 'end'` | `'bottom'` | Docking side relative to the chart canvas. `start` and `end` follow reading direction. |
| `alignment` | `'start' \| 'center' \| 'end'` | `'start'` | Alignment of items along the docked edge. |

### Tooltip (`ChartTooltip`)

A tooltip displays details for the data row under the pointer.

| Prop | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `series` | `readonly SeriesDef[]` | Injected by Chart | Series definitions. When using `` directly, pass the same `series` array. |
| `hoverIndicator` | `boolean` | `true` | Whether to draw hover indicators. Bars highlight the active column, while lines, areas, and dots draw a vertical rule. |
| `showHoverDots` | `boolean` | `true` | Whether to highlight active data points with dots (skipped automatically on bars). |
| `placement` | `'auto' \| 'right' \| 'left' \| 'top'` | `'auto'` | Card placement relative to the active point. `auto` defaults to the right and flips left when room runs out. |

### Swatch (`ChartSwatch`)

A swatch renders a small color marker representing a series, useful inside legends or custom tooltips.

| Prop | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `color` | `string` | **Required** | Fill color value. |
| `variant` | `'square' \| 'line'` | `'square'` | Swatch shape. `square` renders a small square (for bars); `line` renders a short horizontal line (for lines and areas). |

### Custom tooltip content

When the default tooltip layout is not enough, customize the card content through the `#tooltip` slot on ``. The slot exposes the active `xValue` and row details in `rows`:

```vue
<template>
  <Chart :data="monthly" x-key="month" :series="series" tooltip>
    <template #tooltip="{ xValue, rows }">
      <div class="my-custom-tooltip">
        <strong>{{ xValue }}</strong>
        <div v-for="row in asRows(rows)" :key="row.key">
          <ChartSwatch :color="row.color" variant="line" />
          {{ row.label }}: {{ money(row.value) }}
        </div>
      </div>
    </template>
  </Chart>
</template>
```

### Custom tooltip

Custom tooltip: uses the #tooltip slot to read active data and render a custom layout.

```vue
<script setup lang="ts">
import type { TooltipSeriesValue } from '@astryx-vue/charts'
import { Chart, ChartAxis, ChartGrid, ChartSwatch, currency, line } from '@astryx-vue/charts'
import { monthly } from './data'

const money = currency('¥')

const series = [
  line('revenue', { label: '收入' }),
  line('profit', { label: '利润' }),
]

// 插槽给出的 rows 是 unknown[]，实际每一项就是 TooltipSeriesValue。
function asRows(rows: unknown[]): TooltipSeriesValue[] {
  return rows as TooltipSeriesValue[]
}
</script>

<template>
  <Chart :data="monthly" x-key="month" :series="series" :height="260" title="收入与利润" tooltip>
    <template #grid>
      <ChartGrid />
    </template>
    <template #axes>
      <ChartAxis position="bottom" />
      <ChartAxis position="left" :tick-format="money" />
    </template>
    <template #tooltip="{ xValue, rows }">
      <div style="display: grid; gap: 4px; padding: 8px 12px; font-size: 13px">
        <strong>{{ xValue }}</strong>
        <div v-for="row in asRows(rows)" :key="row.key">
          <ChartSwatch :color="row.color" variant="line" />
          {{ row.label }}：{{ money(row.value) }}
        </div>
      </div>
    </template>
  </Chart>
</template>
```

## Colors

When a series does not set an explicit color, the chart assigns one automatically in order from the active theme palette.

All chart colors use CSS variables underneath. When switching themes or toggling dark mode, chart colors update automatically without re-rendering the SVG tree.

To inspect or use the current chart palette programmatically, call `useChartColors()`. It returns a shared object across the package:

- `categorical(n: number)`: Returns an array of `n` categorical colors. If `n` exceeds palette size, colors cycle.
- `sequential`: Sequential color scale helper supporting nine hues (`blue`, `shamrock`, `orange`, `pink`, `purple`, `red`, `teal`, `yellow`, `gray`). Passing a count `n` returns a gradient color array.
- `diverging`: Two-pole diverging palette helper. Provides `positiveNegative`, `coldHot`, and `custom` (custom hues on each pole).
- `semantic`: Semantic status colors, containing `positive`, `negative`, `warning`, and `neutral`.
- `structural`: Structural colors for chart framing, containing `axis`, `grid`, `tick`, and `label`.
- `alpha(color: string, opacity: number)`: Generates a color with an alpha channel for a given opacity. CSS variables use `color-mix()` automatically.

## Formatting functions

The library includes formatting helpers for common chart values. Formatting functions follow a safe fallback rule: if an input is `NaN`, `Infinity`, or cannot be parsed, the function returns the original string as-is instead of printing errors or throwing exceptions.

- `compactNumber(value, locale)`: Abbreviates large numbers. For example, `1200` becomes "1.2K", `1500000` becomes "1.5M", and `1e12` becomes "1T".
- `currency(symbol?, locale?)`: Creates a currency formatter. For example, `currency('$')` can be passed to `ChartAxis`'s `tickFormat`. Values over 1,000 are automatically abbreviated (such as "$1.5K").
- `percent(value, locale)`: Formats a decimal ratio as a percentage. For example, `0.45` becomes "45%" and `0.005` becomes "0.5%".
- `shortDate(value, locale)`: Formats dates as a short month and day. For example, "Jan 5".
- `monthYear(value, locale)`: Formats dates as month and year. For example, "Jan 2024".
- `formatList(values, locale)`: Formats a list of words into a natural language string according to locale rules, such as "A, B, and C".

## Reduce large line datasets

`m4Reduce` groups points by horizontal pixel width and keeps the first, last, minimum, and maximum point in each bucket. It reduces line-rendering work while preserving peaks and valleys that remain visible at the target resolution.

```ts
import { m4Reduce } from '@astryx-vue/charts'

const reduced = m4Reduce(rawData, chartWidth, xDomain)
```

Input data must be sorted by `x` in ascending order. `width` is the positive chart width in pixels, and the output contains at most `4 × ceil(width)` points. When provided, `xDomain` should match the chart's x-axis range. Points outside that range join the nearest edge bucket. The function does not mutate input points and returns the original array when the dataset is already small enough.

| Parameter | Type | Description |
| --- | --- | --- |
| `data` | `M4Point[]` | `{ x, y }` points sorted by x in ascending order. |
| `width` | `number` | Positive pixel width used to create buckets. |
| `xDomain` | `[number, number]` | Optional x-axis range. Defaults to the first and last x values in the data. |

### M4 line reduction

A line chart comparing 12,000 original points with the M4 reduction while preserving the same major peaks and valleys.

```vue
<script setup lang="ts">
import { Chart, ChartAxis, ChartGrid, line, m4Reduce } from '@astryx-vue/charts'

const rawData = Array.from({ length: 12_000 }, (_, x) => ({
  x,
  y: 48 + Math.sin(x / 1_800) * 18 + Math.cos(x / 950) * 7,
}))
const reducedData = m4Reduce(rawData, 480)
const panels = [
  {
    id: 'raw',
    label: 'Original',
    data: rawData,
    series: [line('y', { curve: 'linear', label: 'Original' })],
  },
  {
    id: 'm4',
    label: 'M4 reduced · 480 px',
    data: reducedData,
    series: [line('y', { curve: 'linear', label: 'M4 reduced' })],
  },
]
</script>

<template>
  <div class="chart-m4-demo">
    <figure v-for="panel in panels" :key="panel.id">
      <figcaption>
        <strong>{{ panel.label }}</strong>
        <span>{{ panel.data.length.toLocaleString('en-US') }} points</span>
      </figcaption>
      <Chart
        :data="panel.data"
        x-key="x"
        :series="panel.series"
        :x-domain="[0, 11_999]"
        :y-domain="[-50, 110]"
        :height="180"
      >
        <template #grid>
          <ChartGrid />
        </template>
        <template #axes>
          <ChartAxis position="bottom" :tick-count="4" />
          <ChartAxis position="left" :tick-count="4" />
        </template>
      </Chart>
    </figure>
    <p>Both charts keep the same peaks and valleys. M4 only reduces the number of points.</p>
  </div>
</template>

<style scoped>
.chart-m4-demo { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; width: 100%; }
.chart-m4-demo figure { min-width: 0; margin: 0; }
.chart-m4-demo figcaption { display: flex; justify-content: space-between; gap: 12px; margin-bottom: 8px; font-size: 12px; }
.chart-m4-demo figcaption span, .chart-m4-demo p { color: var(--astryx-color-text-secondary); }
.chart-m4-demo p { grid-column: 1 / -1; margin: 0; font-size: 12px; }
@media (max-width: 680px) {
  .chart-m4-demo { grid-template-columns: minmax(0, 1fr); }
}
</style>
```

## Radial charts

`RadialChart` uses a dedicated radial coordinate space. Provide `axes` for a radar chart, or provide `valueKey` without `axes` for a pie or donut chart. Grids, areas, slices, and tooltips share the same center, radii, and angle calculations.

| RadialChart prop | Type | Default | Description |
| --- | --- | --- | --- |
| `data` | `Record<string, unknown>[]` | **Required** | Series rows for radar mode or slice rows for pie mode. |
| `width` / `height` | `number` | `0` / `400` | Container width is measured in the browser. Pass `width` explicitly for SSR. |
| `axes` | `string[]` | `undefined` | Radar axis fields. Providing this selects radar mode. |
| `valueKey` | `string` | `undefined` | Numeric slice field. Non-finite and negative values count as zero. |
| `labelKey` | `string` | `undefined` | Slice label field. |
| `innerRadius` | `number` | `0` | Inner radius as a fraction of the outer radius. For example, `0.6` creates a donut. |
| `padAngle` | `number` | `0.02` | Angular gap between adjacent slices. |
| `interactive` | `boolean` | `false` | Prevents page scrolling during touch dragging. When off, `pan-y` remains available. |
| `label` | `string` | Derived from the mode | Accessible SVG name. |

### Radar charts

`RadialGrid` draws concentric polygons and axis lines, `RadialArea` draws one data row, and `RadialAxis` draws axis labels. `RadialArea.dataKey` matches any string field value in a row and falls back to the first row when no match exists.

```vue
<RadialChart :data="data" :axes="['speed', 'handling']" :height="360">
  <RadialGrid :rings="5" />
  <RadialArea data-key="Model A" :color="colors[0]" dots />
  <RadialAxis />
  <RadialTooltip />
</RadialChart>
```

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `RadialGrid.rings` | `number` | `5` | Number of concentric grid rings. |
| `RadialAxis.labelOffset` | `number` | `16` | Distance between labels and the outer ring. |
| `RadialArea.dataKey` | `string` | **Required** | Identifier of the data row to draw. |
| `RadialArea.color` | `string` | **Required** | Fill and stroke color. |
| `RadialArea.opacity` | `number` | `0.2` | Fill opacity. |
| `RadialArea.strokeWidth` | `number` | `2` | Polygon stroke width. |
| `RadialArea.dots` / `dotRadius` | `boolean` / `number` | `false` / `4` | Vertex visibility and dot radius. |

### Radar chart

A five-axis radar chart with two series, grid rings, vertex dots, labels, and hover tooltips.

```vue
<script setup lang="ts">
import { RadialArea, RadialAxis, RadialChart, RadialGrid, RadialTooltip, useChartColors } from '@astryx-vue/charts'

const axes = ['speed', 'handling', 'comfort', 'reliability', 'efficiency']
const data = [
  { model: 'Model A', speed: 8, handling: 6, comfort: 9, reliability: 7, efficiency: 8 },
  { model: 'Model B', speed: 6, handling: 9, comfort: 6, reliability: 8, efficiency: 7 },
]
const colors = useChartColors().categorical(2)
const series = [
  { key: 'Model A', color: colors[0] },
  { key: 'Model B', color: colors[1] },
]
</script>

<template>
  <div class="radial-spider-demo">
    <RadialChart :data="data" :axes="axes" :height="360" label="Model comparison radar chart" interactive>
      <RadialGrid :rings="5" />
      <RadialArea data-key="Model A" :color="colors[0]" dots />
      <RadialArea data-key="Model B" :color="colors[1]" dots />
      <RadialAxis />
      <RadialTooltip />
    </RadialChart>
    <div class="radial-spider-demo__legend" aria-label="Series">
      <span v-for="item in series" :key="item.key">
        <i :style="{ backgroundColor: item.color }" aria-hidden="true" />
        {{ item.key }}
      </span>
    </div>
  </div>
</template>

<style scoped>
.radial-spider-demo { width: 100%; }
.radial-spider-demo__legend { display: flex; flex-wrap: wrap; justify-content: center; gap: 16px; font-size: 12px; }
.radial-spider-demo__legend span { display: inline-flex; align-items: center; gap: 6px; }
.radial-spider-demo__legend i { width: 10px; height: 10px; border-radius: 2px; }
</style>
```

### Pie and donut charts

`RadialSlice` draws slices from `valueKey` proportions. A positive `innerRadius` creates the donut hole. `cornerRadius` draws real rounded arc geometry. Use `labels` and `labelThreshold` to control percentage labels.

```vue
<RadialChart :data="data" value-key="revenue" label-key="region" :inner-radius="0.6">
  <RadialSlice :colors="colors" :corner-radius="4" />
  <RadialTooltip />
</RadialChart>
```

| RadialSlice prop | Type | Default | Description |
| --- | --- | --- | --- |
| `colors` | `string[]` | **Required** | Slice colors, cycled in data order. |
| `cornerRadius` | `number` | `0` | Corner radius for the inner and outer arc edges. |
| `labels` | `boolean` | `true` | Whether to show percentage labels. |
| `labelThreshold` | `number` | `5` | Minimum percentage required for a visible label. |

### Donut chart

Regional revenue donut with an inner hole, rounded corners, percentage labels, and hover highlighting.

```vue
<script setup lang="ts">
import { RadialChart, RadialSlice, RadialTooltip, useChartColors } from '@astryx-vue/charts'

const data = [
  { region: 'North America', revenue: 500 },
  { region: 'Europe', revenue: 300 },
  { region: 'Asia Pacific', revenue: 200 },
]
const colors = useChartColors().categorical(data.length)
</script>

<template>
  <RadialChart
    :data="data"
    value-key="revenue"
    label-key="region"
    :inner-radius="0.6"
    :height="360"
    interactive
    label="Revenue share by region"
  >
    <RadialSlice :colors="colors" :corner-radius="4" />
    <RadialTooltip />
  </RadialChart>
</template>
```

### Radial tooltips

`RadialTooltip` hit-tests slices by radius and angle in pie mode. In radar mode, it shows the nearest axis and the highest series value on that axis. It supports mouse hover, touch tapping, and dragging. `highlight` draws and offsets the active slice outline; `highlightOffset` controls the offset distance.

Use the default slot for custom content. It receives `label`, `value`, `percentage`, and `index`:

```vue
<RadialTooltip>
  <template #default="{ label, value, percentage }">
    <strong>{{ label }}</strong>
    {{ value }} · {{ Math.round((percentage ?? 0) * 100) }}%
  </template>
</RadialTooltip>
```

## Sankey charts

`SankeyChart` represents flow between nodes with ribbons whose width follows the value. Omit `columns` to infer columns from link direction, or provide string arrays and rich `{ ids, label }` definitions.

A node's `value` is the total flow through that node. Derive node totals and link values from the same business data so incoming flow, outgoing flow and node totals stay consistent.

```vue
<SankeyChart :nodes="nodes" :links="links" :columns="columns" :min-column-width="180" label="Visitor activation flow">
  <SankeyGrid />
  <SankeyLink color="gradient" :opacity="0.72" />
  <SankeyNode />
  <SankeyLabel />
</SankeyChart>
```

| SankeyChart prop | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes` | `SankeyNodeDatum[]` | **Required** | Node `id`, `label`, total `value`, and optional OKLCH `color`. |
| `links` | `SankeyLinkDatum[]` | **Required** | Flow values between source and target node IDs. |
| `columns` | `SankeyColumn[]` | Inferred | A mixed array of ID arrays or `{ ids, label }` definitions. |
| `width` / `height` | `number` | `0` / `320` | Container width is measured in the browser; pass `width` explicitly for SSR. |
| `nodeWidth` / `nodeGap` | `number` | `20` / `14` | Node bar width and vertical gap within a column. |
| `nodeColor` | `string` | `undefined` | One CSS color for every node; labels adapt their contrast color. |
| `minColumnWidth` | `number` | `160` | Minimum column width. Narrow containers scroll horizontally in a keyboard-focusable region. |
| `label` | `string` | Localized | Accessible name for the SVG and scroll region. |

### Links, nodes, and labels

`SankeyLink` defaults to a source-to-target gradient. `color` also accepts `'source'`, `'target'`, any CSS color, or `{ gradient: number }` with a bias from 0 to 1. `tension` controls the bezier curve; `0` produces straight ribbons. Gradient IDs are scoped per chart, so multiple charts do not reference each other's definitions.

`SankeyNode` provides a `glow` toggle. `SankeyLabel` chooses rotated on-bar or beside-bar labels from node height; last-column labels anchor left to avoid clipping. Use `formatValue` for custom values and `showPercent` for downstream percentages. Percentages use the largest column total as 100%.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `SankeyGrid.dashArray` | `string` | `'4 4'` | Column grid dash pattern. |
| `SankeyGrid.color` / `opacity` | `string` / `number` | Theme border / `0.3` | Grid color and opacity. |
| `SankeyGrid.showHeaders` | `boolean` | `true` | Show labels from rich column definitions. |
| `SankeyLink.color` | `SankeyLinkColor` | `'gradient'` | Gradient, source, target, or flat color mode. |
| `SankeyLink.opacity` / `tension` | `number` | `0.7` / `0.5` | Ribbon opacity and curve tension. |
| `SankeyNode.glow` | `boolean` | `true` | Draw the node glow. |
| `SankeyLabel.showPercent` | `boolean` | `true` | Show percentages for downstream nodes. |
| `SankeyLabel.formatValue` | `(value: number) => string` | Compact number | Custom label value formatter. |

For up to 100 links, the chart also renders a visually hidden From/To/Value table for screen readers.

### Sankey chart

Three columns of visitor flow with gradient ribbons, node labels and headers; narrow screens scroll horizontally.

```vue
<script setup lang="ts">
import { SankeyChart, SankeyGrid, SankeyLabel, SankeyLink, SankeyNode } from '@astryx-vue/charts'

const nodes = [
  { id: 'search', label: 'Search', value: 45 },
  { id: 'direct', label: 'Direct', value: 35 },
  { id: 'social', label: 'Social', value: 20 },
  { id: 'product', label: 'Product', value: 60 },
  { id: 'docs', label: 'Docs', value: 40 },
  { id: 'activated', label: 'Activated', value: 55 },
  { id: 'dropped', label: 'Dropped', value: 45 },
]

const links = [
  { source: 'search', target: 'product', value: 28 },
  { source: 'search', target: 'docs', value: 17 },
  { source: 'direct', target: 'product', value: 22 },
  { source: 'direct', target: 'docs', value: 13 },
  { source: 'social', target: 'product', value: 10 },
  { source: 'social', target: 'docs', value: 10 },
  { source: 'product', target: 'activated', value: 38 },
  { source: 'product', target: 'dropped', value: 22 },
  { source: 'docs', target: 'activated', value: 17 },
  { source: 'docs', target: 'dropped', value: 23 },
]

const columns = [
  { ids: ['search', 'direct', 'social'], label: 'Acquisition' },
  { ids: ['product', 'docs'], label: 'Engagement' },
  { ids: ['activated', 'dropped'], label: 'Outcome' },
]
</script>

<template>
  <SankeyChart
    :nodes="nodes"
    :links="links"
    :columns="columns"
    :width="720"
    :height="340"
    :min-column-width="220"
    label="Visitor activation flow"
  >
    <SankeyGrid />
    <SankeyLink :opacity="0.72" />
    <SankeyNode />
    <SankeyLabel />
  </SankeyChart>
</template>
```

## Three-dimensional SVG charts

`ThreeDChart` normalizes x/y/z data, projects it into two-dimensional SVG, and paints marks in depth order. WebGL is not required. With `interactive`, drag to rotate the camera; when focused, arrow keys rotate by 10° and elevation is clamped from -89° to 89°.

```vue
<ThreeDChart :data="data" x-key="x" y-key="y" z-key="z" interactive>
  <ThreeDGrid />
  <ThreeDAxis />
  <ThreeDScatter color="var(--astryx-color-data-1)" />
</ThreeDChart>
```

| ThreeDChart prop | Type | Default | Description |
| --- | --- | --- | --- |
| `data` | `Record<string, unknown>[]` | **Required** | 3D rows; marks skip rows containing non-finite values. |
| `xKey` / `yKey` / `zKey` | `string` | **Required** | Field names for the three dimensions; y is height. |
| `xDomain` / `yDomain` / `zDomain` | `[number, number]` | Data extent | Optional explicit numeric domains. |
| `width` / `height` | `number` | `0` / `400` | Container width is measured in the browser; pass `width` explicitly for SSR. |
| `azimuth` / `elevation` | `number` | `35` / `25` | Initial camera angles in degrees. |
| `interactive` | `boolean` | `false` | Enable pointer drag and arrow-key rotation, including touch pointer capture. |
| `autoRotate` | `number` | `0` | Azimuth increment per frame; pauses on hover/focus and stops under reduced motion. |
| `label` | `string` | From fields | Accessible SVG name. |

Auto-rotation updates about every 50ms and scales by elapsed time. The SVG is focusable when interaction or auto-rotation is enabled. Arrow keys do not move the camera when only auto-rotation is enabled.

### Three-dimensional marks

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `ThreeDScatter.color` | `string` | **Required** | Point color; radius and opacity vary with depth. |
| `ThreeDScatter.radius` / `opacity` | `number` | `4` / `0.85` | Base point radius and opacity. |
| `ThreeDBar.color` | `string` | **Required** | Fill and stroke for all three bar faces. |
| `ThreeDBar.barWidth` / `barDepth` | `number` | `0.06` / `0.06` | Width and depth in normalized coordinates, not pixels. |
| `ThreeDGrid.divisions` | `number` | `5` | Floor divisions along both x and z. |
| `ThreeDAxis.labels` | `boolean` | `true` | Show field and domain labels. |
| `ThreeDSurface.colorRange` | `string[]` | **Required** | Low-to-high height color ramp. |
| `ThreeDSurface.opacity` | `number` | `0.8` | Surface fill opacity. |
| `ThreeDSurface.wireframe` | `boolean` | `false` | Draw outlines without face fills. |

`ThreeDSurface` expects a complete x/z grid. Faces with missing cells or invalid points are skipped. All three examples support drag and arrow-key rotation.

### 3D scatter

Three 3D clusters with a floor grid and axes, supporting drag and arrow-key rotation.

```vue
<script setup lang="ts">
import { ThreeDAxis, ThreeDChart, ThreeDGrid, ThreeDScatter, useChartColors } from '@astryx-vue/charts'

const centers = [
  { x: 2, y: 3, z: 2 },
  { x: 6, y: 7, z: 5 },
  { x: 3, y: 5, z: 8 },
]
const data = centers.flatMap((center, group) => Array.from({ length: 12 }, (_, index) => ({
  x: center.x + Math.sin(index * 1.7 + group) * 1.1,
  y: center.y + Math.cos(index * 1.3 + group) * 0.9,
  z: center.z + Math.sin(index * 1.1 + group) * 1.2,
})))
const color = useChartColors().categorical(1)[0]
</script>

<template>
  <ThreeDChart
    :data="data"
    x-key="x"
    y-key="y"
    z-key="z"
    :width="720"
    :height="420"
    interactive
    label="Three-dimensional clusters"
  >
    <ThreeDGrid />
    <ThreeDAxis />
    <ThreeDScatter :color="color" :radius="4.5" />
  </ThreeDChart>
</template>
```

### 3D bars

3D bars with distinct top, front and side shading.

```vue
<script setup lang="ts">
import { ThreeDAxis, ThreeDBar, ThreeDChart, ThreeDGrid, useChartColors } from '@astryx-vue/charts'

const data = Array.from({ length: 12 }, (_, index) => ({
  x: index % 4 * 2,
  y: 4 + Math.sin(index * 0.8) * 2 + index % 3,
  z: Math.floor(index / 4) * 2,
}))
const color = useChartColors().categorical(2)[1]
</script>

<template>
  <ThreeDChart
    :data="data"
    x-key="x"
    y-key="y"
    z-key="z"
    :x-domain="[0, 6]"
    :y-domain="[0, 10]"
    :z-domain="[0, 4]"
    :width="720"
    :height="420"
    interactive
    label="Three-dimensional bar chart"
  >
    <ThreeDGrid />
    <ThreeDAxis />
    <ThreeDBar :color="color" :bar-width="0.12" :bar-depth="0.16" />
  </ThreeDChart>
</template>
```

### 3D surface

A continuous wave surface colored by height, with guards against missing or invalid cells.

```vue
<script setup lang="ts">
import { ThreeDAxis, ThreeDChart, ThreeDGrid, ThreeDSurface, useChartColors } from '@astryx-vue/charts'

const data = Array.from({ length: 11 }, (_, x) => Array.from({ length: 11 }, (_, z) => ({
  x,
  y: 5 + Math.sin(x * 0.7) * Math.cos(z * 0.6) * 2.5,
  z,
}))).flat()
const colorRange = useChartColors().sequential.blue(5)
</script>

<template>
  <ThreeDChart
    :data="data"
    x-key="x"
    y-key="y"
    z-key="z"
    :x-domain="[0, 10]"
    :y-domain="[0, 10]"
    :z-domain="[0, 10]"
    :width="720"
    :height="420"
    interactive
    label="Three-dimensional wave surface"
  >
    <ThreeDGrid :divisions="4" />
    <ThreeDSurface :color-range="colorRange" :opacity="0.86" />
    <ThreeDAxis />
  </ThreeDChart>
</template>
```

`ThreeDScatterGL` and other GL/WebGL marks are not included in this package.

## Brush selection

Place `` in the `` `interactions` slot to let users drag a selection over the plot. `mode="x"` selects a horizontal range, useful for time windows; `mode="xy"` selects a rectangle, useful for scatter plots.

```vue
<Chart :data="data" x-key="x" :series="series">
  <template #interactions>
    <ChartBrush @brush="onBrush" @clear="clearSelection" />
  </template>
</Chart>
```

The `brush` event receives `(range, data)`. `range.x` is the `[min, max]` interval in data coordinates, with `range.y` also present in xy mode; `data` contains the original rows inside the selection. `clear` is a click that did not become a drag.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `mode` | `'x' \| 'xy'` | `'x'` | Horizontal or rectangular selection. |
| `color` | `string` | `var(--astryx-color-accent)` | Selection color. |
| `opacity` | `number` | `0.15` | Selection fill opacity. |

### Brush data

Drag a range and inspect the returned interval and matching rows.

```vue
<script setup lang="ts">
import { Chart, ChartBrush, line } from '@astryx-vue/charts'
import { ref } from 'vue'

const data = Array.from({ length: 12 }, (_, x) => ({ x, y: 10 + (x % 5) * 4 }))
const series = [line('y', { dots: true })]
const result = ref('Drag across the chart to select a range.')

function onBrush(range: { x: [number, number] }, selected: unknown[]): void {
  result.value = `${selected.length} points · x ${range.x[0].toFixed(1)}–${range.x[1].toFixed(1)}`
}
</script>

<template>
  <div class="chart-brush-demo">
    <Chart :data="data" x-key="x" :series="series" :height="240" title="Selectable values">
      <template #interactions>
        <ChartBrush @brush="onBrush" @clear="result = 'Drag across the chart to select a range.'" />
      </template>
    </Chart>
    <p>{{ result }}</p>
  </div>
</template>

<style scoped>
.chart-brush-demo { width: 100%; }
.chart-brush-demo p { margin: 8px 0 0; color: var(--astryx-color-text-secondary); font-size: 12px; }
</style>
```

## Select data points

Place `` in the `interactions` slot to let users click or tap the nearest data point. Pointer positions more than 30 pixels from every point do not trigger a selection.

`selected` is controlled by the caller and contains data row indices. A regular click selects only the current point. Shift-click or Meta-click toggles that point while preserving the other selected rows.

```vue
<Chart :data="data" x-key="month" :series="series">
  <template #interactions>
    <ChartSelect :selected="selected" @selection-change="selected = $event" />
  </template>
</Chart>
```

The `select` event receives `(datum, index)`; `selection-change` receives the new index array. Selection rings use the chart's resolved point positions and support numeric and categorical x axes.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `selected` | `number[]` | `[]` | Selected data row indices. |
| `color` | `string` | `var(--astryx-color-accent)` | Selection ring color. |
| `radius` | `number` | `6` | Selection ring radius. |

### Select data points

Click a data point, or use Shift or Meta to toggle multiple points.

```vue
<script setup lang="ts">
import { Chart, ChartSelect, line } from '@astryx-vue/charts'
import { computed, ref } from 'vue'

const data = [
  { month: 'Jan', revenue: 12 },
  { month: 'Feb', revenue: 18 },
  { month: 'Mar', revenue: 15 },
  { month: 'Apr', revenue: 24 },
  { month: 'May', revenue: 21 },
]
const series = [line('revenue', { dots: true })]
const selected = ref<number[]>([1])
const result = computed(() => selected.value.length > 0
  ? `Selected: ${selected.value.map(index => data[index]?.month).filter(Boolean).join(', ')}`
  : 'Click a point to select it.')
</script>

<template>
  <div class="chart-select-demo">
    <Chart :data="data" x-key="month" :series="series" :height="240" title="Monthly revenue">
      <template #interactions>
        <ChartSelect :selected="selected" @selection-change="selected = $event" />
      </template>
    </Chart>
    <p>{{ result }} Use Shift or Meta to toggle multiple points.</p>
  </div>
</template>

<style scoped>
.chart-select-demo { width: 100%; }
.chart-select-demo p { margin: 8px 0 0; color: var(--astryx-color-text-secondary); font-size: 12px; }
</style>
```

## Zoom and pan

Place `` in the `interactions` slot to let users zoom with the wheel or a pinch gesture and drag to pan. The top-right toolbar provides zoom in, zoom out, and reset buttons; set `toolbar="false"` to hide it.

Zoom updates controlled domains through events rather than changing the `` internal state:

```vue
<Chart :data="data" x-key="x" :series="series" :x-domain="xDomain" :y-domain="yDomain">
  <template #interactions>
    <ChartZoom @x-domain-change="xDomain = $event" @y-domain-change="yDomain = $event" />
  </template>
</Chart>
```

Reset restores the initial domains captured when ChartZoom mounts. A categorical x axis does not participate in numeric zoom or pan. Use `xOnly` or `yOnly` to operate on one axis.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `zoomSpeed` | `number` | `0.1` | Zoom speed per wheel tick. |
| `xOnly` | `boolean` | `false` | Operate only on the x axis. |
| `yOnly` | `boolean` | `false` | Operate only on the y axis. |
| `toolbar` | `false \| 'top-right' \| 'top-left' \| 'bottom-right' \| 'bottom-left'` | `'top-right'` | Toolbar position or hidden. |

### Zoom and pan

Use the wheel, pinch, drag, and toolbar to adjust the chart range.

```vue
<script setup lang="ts">
import { Chart, ChartZoom, line } from '@astryx-vue/charts'
import { ref } from 'vue'

const data = Array.from({ length: 16 }, (_, x) => ({ x, y: 12 + Math.sin(x / 2) * 6 + x * 0.4 }))
const series = [line('y')]
const xDomain = ref<[number, number]>([0, 15])
const yDomain = ref<[number, number]>([0, 24])
</script>

<template>
  <div class="chart-zoom-demo">
    <Chart
      :data="data"
      x-key="x"
      :series="series"
      :x-domain="xDomain"
      :y-domain="yDomain"
      :height="260"
      title="Zoomable values"
    >
      <template #interactions>
        <ChartZoom
          @x-domain-change="xDomain = $event"
          @y-domain-change="yDomain = $event"
        />
      </template>
    </Chart>
    <p>x {{ xDomain.map(value => value.toFixed(1)).join('–') }} · y {{ yDomain.map(value => value.toFixed(1)).join('–') }}</p>
    <p>Use the wheel or pinch to zoom. Drag to pan. Use the toolbar to reset.</p>
  </div>
</template>

<style scoped>
.chart-zoom-demo { width: 100%; }
.chart-zoom-demo p { margin: 8px 0 0; color: var(--astryx-color-text-secondary); font-size: 12px; }
.chart-zoom-demo p + p { margin-top: 4px; }
</style>
```

## Streaming data ranges

`useChartRange` manages controlled x/y domains for continuously appended data. Each `push(x, y)` synchronously updates the ranges. Read them with `.value` inside `<script setup>`; template usage unwraps them automatically.

```ts
const { xDomain, yDomain, push, reset } = useChartRange({
  xWindow: 300,
  yPadding: 0.1,
})

push(nextX, value)
```

```vue
<Chart :data="data" x-key="x" :series="series" :x-domain="xDomain" :y-domain="yDomain" />
```

During warmup, the x domain expands as `[0, max(x, 1)]`. Once `xWindow` is reached, it slides as `[x - xWindow, x]`. By default, y tracks the historical minimum and maximum values observed by the composable. It does not shrink when old points leave the x window. `reset()` clears that history and restores the initial ranges.

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `xWindow` | `number` | **Required** | Width of the sliding x window. |
| `yDomain` | `[number, number]` | `undefined` | Fixed y domain. Providing it disables automatic tracking. |
| `yPadding` | `number` | `0.1` | Padding ratio added above and below the automatic y range. |
| `yCenter` | `boolean` | `false` | Expands the automatic y domain symmetrically around zero. |

### Streaming data ranges

Start and pause streaming or reset the chart to inspect controlled x/y domain changes.

```vue
<script setup lang="ts">
import { Chart, ChartAxis, ChartGrid, line, useChartRange } from '@astryx-vue/charts'
import { Button } from '@astryx-vue/core'
import { onBeforeUnmount, ref } from 'vue'

const data = ref<Record<string, number>[]>([])
const series = [line('y', { curve: 'linear', label: 'Value' })]
const { xDomain, yDomain, push, reset } = useChartRange({ xWindow: 100, yPadding: 0.15 })
const running = ref(false)
let nextX = 0
let timer: ReturnType<typeof setInterval> | undefined

function append(): void {
  const x = nextX
  const y = 12 + Math.sin(x / 3) * 6 + Math.cos(x / 8) * 3
  push(x, y)
  data.value = [...data.value, { x, y }].filter(point => point.x >= xDomain.value[0])
  nextX += 1
}

function stop(): void {
  if (timer !== undefined)
    clearInterval(timer)
  timer = undefined
  running.value = false
}

function toggle(): void {
  if (timer !== undefined) {
    stop()
    return
  }
  running.value = true
  timer = setInterval(append, 450)
}

function seed(): void {
  for (let index = 0; index < 110; index++)
    append()
}

function resetStream(): void {
  reset()
  data.value = []
  nextX = 0
  seed()
}

seed()

onBeforeUnmount(stop)
</script>

<template>
  <div class="chart-range-demo">
    <Chart
      :data="data"
      x-key="x"
      :series="series"
      :x-domain="xDomain"
      :y-domain="yDomain"
      :height="240"
      title="Streaming values"
    >
      <template #grid>
        <ChartGrid />
      </template>
      <template #axes>
        <ChartAxis position="bottom" />
        <ChartAxis position="left" :tick-count="4" />
      </template>
    </Chart>
    <div class="chart-range-demo__controls">
      <Button :label="running ? 'Pause' : 'Start stream'" variant="primary" @click="toggle" />
      <Button label="Reset" @click="resetStream" />
      <span>x {{ xDomain.map(value => value.toFixed(0)).join('–') }} · y {{ yDomain.map(value => value.toFixed(1)).join('–') }} · {{ data.length }} points</span>
    </div>
    <p>Start adds one point every 450 ms. The x window slides and y tracks the observed range.</p>
  </div>
</template>

<style scoped>
.chart-range-demo { width: 100%; }
.chart-range-demo__controls { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 12px; }
.chart-range-demo__controls span { margin-inline-start: auto; color: var(--astryx-color-text-secondary); font-size: 12px; }
.chart-range-demo p { margin: 8px 0 0; color: var(--astryx-color-text-secondary); font-size: 12px; }
@media (max-width: 560px) {
  .chart-range-demo__controls span { flex-basis: 100%; margin-inline-start: 0; }
}
</style>
```

## Accessibility

Charts include built-in accessibility features so screen reader users can understand chart content:

- The root element has a `role="img"` attribute.
- The chart's accessible name prioritizes the `title` prop. When `title` is omitted, the component builds a semantic description from primary series and the x-axis field (such as "Monthly Revenue and Cost trend"). If only annotations are present, it falls back to "Chart".
- The `subtitle` prop maps to the chart's accessible description.
- When total data points (data rows × data columns) do not exceed 100 (`MAX_TABLE_POINTS`), the chart generates a visually hidden data table using `VisuallyHidden`. Screen readers can read exact values row by row. Above 100 points, the table is omitted to prevent excessive speech noise.

## Server-side rendering

During server-side rendering (SSR), no browser DOM exists, so the component cannot measure parent container width in pixels.

When rendering on the server, pass an explicit `width` prop on ``. This allows the server to compute scales and render complete SVG paths and rectangles into HTML. After client-side hydration, once the browser measures the real container width, the chart takes over and responds to container resize events.

## Not supported yet

To stay lightweight and focused, the package currently leaves out:
- Four WebGL-based series marks for very large datasets (such as `dotGL`) are not yet included.
- The Nuxt module does not yet include auto-import switches for `@astryx-vue/charts`. Import components manually when using Nuxt.

## `` props and slots

`` is the root container. It measures container dimensions, builds coordinate scales, calculates geometry positions, and renders the SVG tree.

### Props

| Name | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `data` | `Record<string, unknown>[]` | **Required** | Rows of data to render. Each row contains an x-axis field and one or more series fields. |
| `xKey` | `string` | **Required** | Field name used as the x value across all series. |
| `series` | `SeriesDef[]` | **Required** | Array of series definitions, rendered in order on a shared coordinate system. |
| `height` | `number` | `300` | Chart height in CSS pixels. Non-finite values and negative numbers are treated as 0. |
| `width` | `number` | `0` | Chart width in CSS pixels. Ignored after the browser first measures the container. Used during server-side rendering when no DOM container exists. |
| `margin` | `Partial` | `{ top: 24, right: 24, bottom: 32, left: 48 }` | Partial margin overrides for the plotting area. Omitted sides use defaults. |
| `yBaseline` | `'auto' \| 'zero' \| 'data'` | `'auto'` | How to determine the y-axis domain when `yDomain` is not set. |
| `yDomain` | `[number, number]` | `undefined` | Explicit y-axis range `[min, max]`. When set, this range is used directly without baseline adjustments or edge padding. |
| `xDomain` | `[number, number]` | `undefined` | Explicit range `[min, max]` for numeric x-axes. Stays active even when `data` is empty, keeping streaming windows stable. Ignored on categorical band axes. |
| `legend` | `boolean \| ChartLegendConfig` | `false` | Whether to show the legend derived from series, or a configuration object to adjust position and alignment. |
| `tooltip` | `boolean \| ChartTooltipConfig` | `false` | Whether to show grouped hover tooltips. |
| `title` | `string` | `undefined` | Chart title, used as the SVG accessible name. |
| `subtitle` | `string` | `undefined` | Supporting text below the title, used as the SVG accessible description. |

### Slots

| Name | Bindings | Description |
| :--- | :--- | :--- |
| `grid` | None | Background grid rendered behind series, usually containing ``. |
| `axes` | None | Axes rendered behind series, usually containing one or more `` components. |
| `interactions` | None | Custom interaction layer rendered above the pointer capture surface. |
| `tooltip` | `{ xValue: unknown, rows: unknown[] }` | Custom tooltip slot. `xValue` is the active x value under the pointer. `rows` is the list of series data items for that row. |
| `default` | None | Extra content rendered after the built-in tooltip layer. |
