# Chart interaction

> Tooltips, trackball, rectangle and wheel zoom, pan, point selection and the instance API, all driven by a per-chart store instead of React state.

Canonical: https://salmonui.dev/docs/data-visualization/chart-interaction

Pointer, wheel and drag transients live in a per-chart store; React
re-renders only the tooltip layer when the hovered point changes, never per
pointer move. Committed changes go through controlled triads.

## Tooltip

`tooltip` (or `tooltip={{ format, header }}`) shows the hovered point;
`series.tooltip: false` opts a series out. `tooltip.render(ctx)`
returns any `ReactNode` and runs only for the hovered point.
`ref.current.showTooltip({ seriesId, index })` and `hideTooltip()` open and
close it from code.

`tooltip.mode` is `'point'` (default), `'shared'` (one box for every
series at the x) or `'split'` (one box per series, each at its own point). `tooltip.position` is `'nearest'` (default: above the nearest
point, found by binary search on the sorted x, no DOM hit-testing),
`'pointer'` (follows the pointer) or `{ x, y }` (fixed, drawing px), and
`tooltip.offset` is the gap in px. The tooltip, crosshair and
hover marks are a lazy overlay chunk mounted after hydration; a pointer
move costs one store write (the hover handler stays under 1 ms on 100,000
points, `chart-perf.spec.ts`).

## Crosshair

`crosshair` draws lines at the pointer: `lines: 'both' | 'x' | 'y'`,
`snap` (to the nearest point), `highlightCategory` (shades the hovered
category band), `axisLabels` (value boxes on the axes) and
`formatLabel(value, axisId)` for their text. `api.showCrosshair(point)`
takes a point (`{ seriesId, index }`) or data values (`{ x, y }`) and
`api.hideCrosshair()` hides it; the position lives in the chart store.

## Synchronized charts

```tsx
<ChartSyncGroup tooltip crosshair zoom selection>
  <Chart data={a} selection ... />
  <Chart data={b} selection ... />
</ChartSyncGroup>
```

Charts in one `ChartSyncGroup` share the hovered x (tooltip and
crosshair), the x zoom range and, between charts with `selection`, the
selected point indices: a click in one chart proposes the same indices in
the others through `onSelectedPointsChange` with `reason: 'sync'`. Each
group instance has its own store.

### Live demo: Synchronized charts

Live demo: https://salmonui.dev/demos/data-visualization/chart-sync

Two charts in a ChartSyncGroup share the hovered day (tooltip and crosshair), the x zoom range and the selected points; each kind of sync can be switched off.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Chart, ChartSyncGroup } from '@salmonui/charts/chart';
import type { ChartPointRef } from '@salmonui/charts/chart';

const days = Array.from({ length: 60 }, (_, d) => ({
  day: d + 1,
  visitors: 800 + Math.round(250 * Math.sin(d / 5)) + d * 4,
  orders: 40 + Math.round(15 * Math.sin(d / 5 + 0.6)) + Math.round(d / 4),
}));

export default function ChartSyncDemo() {
  const [tooltip, setTooltip] = useState(true);
  const [crosshair, setCrosshair] = useState(true);
  const [zoom, setZoom] = useState(true);
  const [selection, setSelection] = useState(true);
  const [visitorSel, setVisitorSel] = useState<readonly ChartPointRef[]>([]);
  const [orderSel, setOrderSel] = useState<readonly ChartPointRef[]>([]);
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <Checkbox checked={tooltip} onCheckedChange={(checked) => setTooltip(checked)}>Sync tooltip</Checkbox>
        <Checkbox checked={crosshair} onCheckedChange={(checked) => setCrosshair(checked)}>Sync crosshair</Checkbox>
        <Checkbox checked={zoom} onCheckedChange={(checked) => setZoom(checked)}>Sync zoom</Checkbox>
        <Checkbox checked={selection} onCheckedChange={(checked) => setSelection(checked)}>Sync selection</Checkbox>
      </div>
      <ChartSyncGroup tooltip={tooltip} crosshair={crosshair} zoom={zoom} selection={selection}>
        <Chart
          title="Visitors"
          data={days}
          height={200}
          legend={false}
          tooltip
          crosshair={{ lines: 'x' }}
          zoom={{ mode: 'x' }}
          selection
          selectedPoints={visitorSel}
          onSelectedPointsChange={setVisitorSel}
          series={[{ type: 'area', name: 'Visitors', xField: 'day', yField: 'visitors' }]}
        />
        <Chart
          title="Orders"
          data={days}
          height={200}
          legend={false}
          tooltip
          crosshair={{ lines: 'x' }}
          zoom={{ mode: 'x' }}
          selection
          selectedPoints={orderSel}
          onSelectedPointsChange={setOrderSel}
          series={[{ type: 'column', name: 'Orders', xField: 'day', yField: 'orders' }]}
        />
      </ChartSyncGroup>
      <p className="demo-status" aria-live="polite">
        Selected days: visitors <code>{visitorSel.map((p) => p.index + 1).join(', ') || 'none'}</code>, orders{' '}
        <code>{orderSel.map((p) => p.index + 1).join(', ') || 'none'}</code>
      </p>
    </div>
  );
}
```

## Plot events and touch

`onPlotClick(point, event)` and `onPlotPointerMove(point, event)` fire
anywhere on the plot (not only on points) with drawing coordinates and the
data values under the pointer: `{ x, y, xValue, yValue }`, `xValue` a
category, `Date` or number of the x axis and `yValue` of the first y axis.
`onClick`, `onDoubleClick`, `onContextMenu` and `onPointerDown`,
`onPointerUp`, `onPointerMove` and `onPointerLeave` are DOM handlers on the
chart root. `StockChart` and `Gauge` take the same set, `TreeMap` the click,
double click, context menu and pointer move handlers. `Sparkline` and
`GeoMap` keep their bundles small and take none: put the handlers on a
wrapping element, where these events bubble.

Touch uses Pointer Events: a long press (500 ms) shows the tooltip of the
nearest point and moving the finger cancels it; the plot sets
`touch-action: pan-y` so the page still scrolls vertically, and `none` when
zoom, pan, range or lasso selection or point drag need the gestures.
Layout follows the container size, never device detection.

## Trackball

`crosshair={{ snap: true }}` with `tooltip={{ mode: 'shared' }}` makes a
trackball: the crosshair snaps to the nearest x, every series
at that x is highlighted and listed in one tooltip.

### Live demo: Tooltip, crosshair and trackball

Live demo: https://salmonui.dev/demos/data-visualization/chart-tooltip-crosshair

Point, shared and split tooltips at the nearest point, the pointer or a fixed position, a custom tooltip render, crosshair lines with axis labels and category highlight, a snapping trackball, the tooltip and crosshair API, keyboard focus and touch long press.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Chart } from '@salmonui/charts/chart';
import type { ChartApi, ChartTooltipOptions } from '@salmonui/charts/chart';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const visits = months.map((month, i) => ({
  month,
  organic: 3200 + Math.round(900 * Math.sin(i / 2)),
  paid: 1800 + ((i * 410) % 1300),
  referral: 700 + ((i * 170) % 500),
}));

type Mode = 'point' | 'shared' | 'split';
type Position = 'nearest' | 'pointer' | 'fixed';
type Lines = 'off' | 'both' | 'x' | 'y';

export default function ChartTooltipCrosshairDemo() {
  const chart = useRef<ChartApi>(null);
  const [mode, setMode] = useState<Mode>('shared');
  const [position, setPosition] = useState<Position>('nearest');
  const [custom, setCustom] = useState(false);
  const [lines, setLines] = useState<Lines>('x');
  const [snap, setSnap] = useState(true);
  const [highlightCategory, setHighlightCategory] = useState(false);
  const [referralTooltip, setReferralTooltip] = useState(true);

  const tooltip: ChartTooltipOptions = {
    mode,
    position: position === 'fixed' ? { x: 80, y: 40 } : position,
    offset: 12,
    format: (p) => `${p.seriesName}: ${p.y.toLocaleString('en-US')} visits`,
    render: custom
      ? (ctx) => (
          <div>
            <strong>{ctx.header}</strong>
            <ul style={{ margin: 0, paddingInlineStart: 16 }}>
              {ctx.points.map((p) => (
                <li key={p.seriesId} style={{ color: p.color }}>
                  {p.seriesName}: {p.yText}
                </li>
              ))}
            </ul>
          </div>
        )
      : undefined,
  };

  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Tooltip mode
          <Select aria-label="Tooltip mode" data={['point', 'shared', 'split']} value={mode} onValueChange={(value) => value != null && setMode(value as Mode)} />
        </label>
        <label>
          Position
          <Select aria-label="Position" data={[{ value: 'nearest', label: 'nearest' }, { value: 'pointer', label: 'pointer' }, { value: 'fixed', label: 'fixed (80, 40)' }]} value={position} onValueChange={(value) => value != null && setPosition(value as Position)} />
        </label>
        <Checkbox checked={custom} onCheckedChange={(checked) => setCustom(checked)}>
          Custom render
        </Checkbox>
        <Checkbox checked={referralTooltip} onCheckedChange={(checked) => setReferralTooltip(checked)}>
          Referral in tooltip
        </Checkbox>
      </div>
      <div className="demo-toolbar">
        <label>
          Crosshair
          <Select aria-label="Crosshair" data={['off', 'both', 'x', 'y']} value={lines} onValueChange={(value) => value != null && setLines(value as Lines)} />
        </label>
        <Checkbox checked={snap} onCheckedChange={(checked) => setSnap(checked)}>
          Snap (trackball)
        </Checkbox>
        <Checkbox checked={highlightCategory} onCheckedChange={(checked) => setHighlightCategory(checked)}>
          Highlight category
        </Checkbox>
        <Button variant="outline" type="button" onClick={() => chart.current?.showTooltip({ seriesId: 'Paid', index: 5 })}>
          Show June paid tooltip
        </Button>
        <Button variant="outline" type="button" onClick={() => chart.current?.hideTooltip()}>
          Hide tooltip
        </Button>
        <Button variant="outline" type="button" onClick={() => chart.current?.showCrosshair({ x: 'Sep' })}>
          Crosshair at Sep
        </Button>
        <Button variant="outline" type="button" onClick={() => chart.current?.hideCrosshair()}>
          Hide crosshair
        </Button>
      </div>
      <Chart
        ref={chart}
        title="Website visits"
        data={visits}
        height={320}
        tooltip={tooltip}
        crosshair={lines === 'off' ? false : { lines, snap, highlightCategory, axisLabels: true }}
        series={[
          { type: 'line', name: 'Organic', xField: 'month', yField: 'organic', markers: true },
          { type: 'line', name: 'Paid', xField: 'month', yField: 'paid', markers: true },
          { type: 'line', name: 'Referral', xField: 'month', yField: 'referral', markers: true, tooltip: referralTooltip },
        ]}
      />
    </div>
  );
}
```

## Zoom and pan

`zoom` turns on wheel zoom, rectangle selection zoom and pan;
`zoom={{ wheel, selection, pan, mode: 'x' | 'y' | 'xy' }}` picks them.
Shift + drag (or drag with `selection: false`) pans a zoomed
chart; the pan frame stays in the store until release. Every
committed step calls `onZoomRangeChange(range, event)` with
`event.reason` `'wheel' | 'selection' | 'pan' | 'pinch' | 'keyboard' |
'toolbar' | 'reset'`; a controlled chart vetoes by keeping its
`zoomRange`; `+`, `-` and `0` zoom from the keyboard and
`api.resetZoom()` resets. `zoom.wheel` and `zoom.pinch` (two
touches, `touch-action: none` on the plot) zoom around the pointer or
the midpoint of the fingers; the pinch frame stays in the store until the
fingers lift; `zoom.pinch: false` turns pinch off. A wheel step on
100,000 points stays within a 16.7 ms frame at p95 (`chart-perf.spec.ts`).
`zoom.deferred` moves only the drawn series during
a pan and lays out once on release.

### Lazy loading

`onVisibleRangeChange({ axisId, range })` fires when a zoom or pan
commits (never per drag frame), so an application fetches the rows of the
visible range. `createRangeSource` from `@salmonui/data` does the fetching:
it widens each request by half its span, caches loaded ranges, aborts
superseded loads and exposes a snapshot for `useSyncExternalStore`:

```tsx
import { createRangeSource } from '@salmonui/data';

const source = createRangeSource({ load: ([from, to], { signal }) => fetch(`/ticks?from=${from}&to=${to}`, { signal }).then((r) => r.json()) });

function LiveChart() {
  const { rows } = useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot);
  return <Chart data={rows} zoom xAxis={{ scale: 'time', min: start, max: end }} onVisibleRangeChange={({ range }) => source.request(range)} series={[{ xField: 't', yField: 'v' }]} />;
}
```

There is no axis scrollbar; a linked `RangeSelector` navigator shows and
moves the zoomed window (see
[Chart axes](https://salmonui.dev/docs/data-visualization/chart-axes), "Axis scrollbar").

The drag, wheel and pinch code is a lazy chunk loaded after hydration
when `zoom`, a range or lasso `selection`, or `onPointChange` is on; the
plot gets `data-interactive` once it is ready.

```tsx
import '@salmonui/navigation/toolbar/styles.css';
import '@salmonui/buttons/button/styles.css';

<Chart zoom={{ toolbar: ['zoom', 'pan', 'zoomIn', 'zoomOut', 'reset'], toolbarPosition: 'topEnd' }} {...props} />
```

`zoom.toolbar` (`true` for every tool, or a list) renders the zoom toolbar
after hydration: Navigation's `Toolbar` with a `ToggleButtonGroup` for the
drag tool (rubber-band zoom or pan) and buttons for zoom in, zoom out and
reset (disabled while not zoomed). It loads from the public
`@salmonui/navigation/toolbar` and `@salmonui/buttons/button` entries in a lazy
chunk, so import their stylesheets; `zoom.toolbarPosition` is `'topEnd'`
(default), `'topStart'`, `'bottomEnd'` or `'bottomStart'`, and
`text.zoomToolbar`, `zoomTool`, `zoomIn`, `zoomOut`, `pan` and
`resetZoom` localize the names.

### Live demo: Zoom, pan and the zoom toolbar

Live demo: https://salmonui.dev/demos/data-visualization/chart-zoom

A 2,000-point chart with wheel, pinch and rectangle zoom along x, y or both, pan, deferred pan, the zoom toolbar and a controlled zoom range whose changes and committed visible ranges are logged.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Chart } from '@salmonui/charts/chart';
import type { ChartZoomRange } from '@salmonui/charts/chart';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';

// 2,000 hourly sensor readings; x is the hour number.
const readings = Array.from({ length: 2000 }, (_, h) => ({ hour: h, value: Math.round((20 + 6 * Math.sin(h / 24) + 2 * Math.sin(h / 3.7) + (h % 7) / 3) * 10) / 10 }));

type Mode = 'x' | 'y' | 'xy';

export default function ChartZoomDemo() {
  const [mode, setMode] = useState<Mode>('x');
  const [wheel, setWheel] = useState(true);
  const [selection, setSelection] = useState(true);
  const [pan, setPan] = useState(true);
  const [deferred, setDeferred] = useState(false);
  const [range, setRange] = useState<ChartZoomRange>({ x: [400, 900] });
  const [log, setLog] = useState<string[]>([]);
  const add = (line: string) => setLog((l) => [line, ...l].slice(0, 6));
  const fmt = (r: readonly [number, number] | undefined) => (r ? `${Math.round(r[0])}–${Math.round(r[1])}` : 'full');

  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Mode
          <Select aria-label="Mode" data={['x', 'y', 'xy']} value={mode} onValueChange={(value) => value != null && setMode(value as Mode)} />
        </label>
        <Checkbox checked={wheel} onCheckedChange={(checked) => setWheel(checked)}>
          Wheel and pinch
        </Checkbox>
        <Checkbox checked={selection} onCheckedChange={(checked) => setSelection(checked)}>
          Rectangle zoom
        </Checkbox>
        <Checkbox checked={pan} onCheckedChange={(checked) => setPan(checked)}>
          Pan
        </Checkbox>
        <Checkbox checked={deferred} onCheckedChange={(checked) => setDeferred(checked)}>
          Deferred pan
        </Checkbox>
        <Button variant="outline" type="button" onClick={() => setRange({ x: [0, 168] })}>
          First week
        </Button>
        <Button variant="outline" type="button" onClick={() => setRange({})}>
          Reset
        </Button>
      </div>
      <Chart
        title="Sensor temperature"
        data={readings}
        height={320}
        legend={false}
        xAxis={{ title: 'Hour' }}
        yAxis={{ format: '{value} °C' }}
        zoom={{ wheel, pinch: wheel, selection, pan, mode, deferred, toolbar: ['zoom', 'pan', 'zoomIn', 'zoomOut', 'reset'], toolbarPosition: 'topEnd' }}
        zoomRange={range}
        onZoomRangeChange={(next, event) => {
          setRange(next);
          add(`onZoomRangeChange: ${event.reason} (${event.source}), x ${fmt(next.x)}`);
        }}
        onVisibleRangeChange={({ axisId, range: r }) => add(`onVisibleRangeChange: ${axisId} ${fmt(r)}`)}
        series={[{ type: 'line', name: 'Temperature', xField: 'hour', yField: 'value' }]}
      />
      <p className="demo-status" aria-live="polite">
        zoomRange.x: <code>{fmt(range.x)}</code>
      </p>
      <div className="demo-log" aria-label="Zoom events">
        <ol>
          {log.map((line, i) => (
            <li key={`${i}-${line}`}>{line}</li>
          ))}
        </ol>
      </div>
    </div>
  );
}
```

## Selection

`selection` (or `selection={{ mode: 'point' | 'series', multiple }}`)
selects points by click or Enter; the triad is `selectedPoints` /
`defaultSelectedPoints` / `onSelectedPointsChange(points, event)` with
`{ seriesId, index }` entries, and Ctrl / Cmd adds to the selection.
Selected marks carry `data-selected` for styling; series under a
legend hover carry `data-highlighted` and the others `data-dimmed`.
`mode: 'series'` selects the whole series and `mode: 'cluster'`
every series' point at the clicked index.

`selection={{ mode: 'range', axis: 'x' | 'y' | 'xy' }}` selects the points
inside a dragged rectangle (a band along x or y for one axis) and
`mode: 'lasso'` the points inside a drawn polygon (point-in-polygon on the
model's anchors, no DOM hit-testing). Both propose the points through
`onSelectedPointsChange` with `reason: 'range' | 'lasso'` and call
`onRangeSelect({ ranges, points }, event)` with the data range per axis.

`highlight: 'series' | 'point' | 'cluster'` fades everything but the
hovered series, point or index (`data-faded`, set on the marks without a
React render), and `legend.highlight` dims the other series while a legend
item is hovered or focused. `onPointClick`,
`onPointDoubleClick` and `onPointHover` receive the point context
`{ seriesId, index, datum, x, y, ... }`.

## Editing points

```tsx
<Chart
  data={rows}
  series={[{ xField: 'month', yField: 'units', markers: true, editable: { min: 0, max: 100, step: 1 } }]}
  onPointChange={({ index, value }) => setRows((r) => r.map((d, i) => (i === index ? { ...d, units: value } : d)))}
/>
```

`series.editable` lets the pointer drag a point's value; the preview is a
store overlay and `onPointChange({ seriesId, index, value }, event)` fires
once on release with the value clamped to `min` / `max`. With the plot
focused, Up / Down (Left / Right in a horizontal chart) step the focused
point by `step` (default a tenth of the tick interval, Shift for ten
steps). Edits are proposals: the application updates `data`.

### Live demo: Selection, highlight, point events and editing

Live demo: https://salmonui.dev/demos/data-visualization/chart-selection

Point, series and cluster selection with a controlled selectedPoints list, hover highlight, styling hooks, point and plot events, range and lasso selection on a scatter chart, and a line whose points are edited by drag or keyboard.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { Chart } from '@salmonui/charts/chart';
import type { ChartPointRef } from '@salmonui/charts/chart';

const quarters = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6'];
const regions = quarters.map((quarter, i) => ({ quarter, north: 40 + ((i * 13) % 25), south: 30 + ((i * 17) % 30), west: 22 + ((i * 7) % 20) }));
const samples = Array.from({ length: 60 }, (_, i) => ({ x: (i * 37) % 100, y: (i * 61) % 100 }));

type Mode = 'point' | 'series' | 'cluster' | 'range' | 'lasso';
type Highlight = 'off' | 'series' | 'point' | 'cluster';

// Selected, dimmed and highlighted marks carry data attributes for className overrides.
const css = `.demo-chart-selection [data-selected] { stroke: var(--salmon-text-primary); stroke-width: 2px; }
.demo-chart-selection [data-dimmed] { opacity: 0.25; }`;

export default function ChartSelectionDemo() {
  const [mode, setMode] = useState<Mode>('point');
  const [multiple, setMultiple] = useState(true);
  const [highlight, setHighlight] = useState<Highlight>('series');
  const [selected, setSelected] = useState<readonly ChartPointRef[]>([]);
  const [scatterSelected, setScatterSelected] = useState<readonly ChartPointRef[]>([]);
  const [units, setUnits] = useState([12, 18, 15, 22, 19, 25]);
  const [log, setLog] = useState<string[]>([]);
  const add = (line: string) => setLog((l) => [line, ...l].slice(0, 6));
  const boxMode = mode === 'range' || mode === 'lasso';

  return (
    <div className="demo-stack demo-chart-selection">
      <style>{css}</style>
      <div className="demo-toolbar">
        <label>
          Column selection mode
          <Select aria-label="Column selection mode" data={[{ value: 'point', label: 'point' }, { value: 'series', label: 'series' }, { value: 'cluster', label: 'cluster' }]} value={boxMode ? 'point' : mode} onValueChange={(value) => value != null && setMode(value as Mode)} />
        </label>
        <Checkbox checked={multiple} onCheckedChange={(checked) => setMultiple(checked)}>Multiple</Checkbox>
        <label>
          Hover highlight
          <Select aria-label="Hover highlight" data={[{ value: 'off', label: 'false' }, { value: 'series', label: 'series' }, { value: 'point', label: 'point' }, { value: 'cluster', label: 'cluster' }]} value={highlight} onValueChange={(value) => value != null && setHighlight(value as Highlight)} />
        </label>
        <Button variant="outline" type="button" onClick={() => setSelected([])}>
          Clear selection
        </Button>
      </div>
      <Chart
        title="Sales by region"
        data={regions}
        height={280}
        selection={{ mode: boxMode ? 'point' : mode, multiple }}
        selectedPoints={selected}
        onSelectedPointsChange={(points, event) => {
          setSelected(points);
          add(`onSelectedPointsChange: ${points.length} points (${event.reason})`);
        }}
        highlight={highlight === 'off' ? false : highlight}
        legend={{ highlight: true }}
        onPointClick={(p) => add(`onPointClick: ${p.seriesName} ${p.xText} = ${p.yText}`)}
        onPointDoubleClick={(p) => add(`onPointDoubleClick: ${p.seriesName} ${p.xText}`)}
        onPointHover={(p) => {
          if (p) add(`onPointHover: ${p.seriesName} ${p.xText}`);
        }}
        onPlotClick={(p) => add(`onPlotClick: x ${String(p.xValue)}, y ${typeof p.yValue === 'number' ? p.yValue.toFixed(1) : String(p.yValue)}`)}
        onContextMenu={(e) => {
          e.preventDefault();
          add('onContextMenu on the chart root');
        }}
        series={[
          { type: 'column', name: 'North', xField: 'quarter', yField: 'north' },
          { type: 'column', name: 'South', xField: 'quarter', yField: 'south' },
          { type: 'column', name: 'West', xField: 'quarter', yField: 'west' },
        ]}
      />
      <p className="demo-status" aria-live="polite">
        selectedPoints: <code>{selected.map((p) => `${p.seriesId}[${p.index}]`).join(', ') || 'none'}</code>
      </p>
      <div className="demo-toolbar">
        <label>
          Scatter selection
          <Select aria-label="Scatter selection" data={[{ value: 'range', label: 'range (drag a rectangle)' }, { value: 'lasso', label: 'lasso (draw a shape)' }]} value={boxMode ? mode : 'range'} onValueChange={(value) => value != null && setMode(value as Mode)} />
        </label>
      </div>
      <Chart
        title="Samples"
        data={samples}
        height={260}
        legend={false}
        selection={{ mode: mode === 'lasso' ? 'lasso' : 'range', axis: 'xy', multiple: true }}
        selectedPoints={scatterSelected}
        onSelectedPointsChange={setScatterSelected}
        onRangeSelect={({ ranges, points }, event) => add(`onRangeSelect (${event.reason}): ${points.length} points${ranges.x ? `, x ${ranges.x.map((v) => v.toFixed(0)).join('–')}` : ''}`)}
        series={[{ type: 'scatter', name: 'Samples', xField: 'x', yField: 'y' }]}
      />
      <Chart
        title="Planned units (drag a point, or focus the plot and press Up / Down)"
        data={units.map((value, i) => ({ quarter: quarters[i], value }))}
        height={240}
        legend={false}
        yAxis={{ min: 0, max: 40 }}
        series={[{ type: 'line', name: 'Units', xField: 'quarter', yField: 'value', markers: true, editable: { min: 0, max: 40, step: 1 } }]}
        onPointChange={({ index, value }, event) => {
          setUnits((u) => u.map((v, i) => (i === index ? Math.round(value) : v)));
          add(`onPointChange: ${quarters[index]} = ${Math.round(value)} (${event.reason})`);
        }}
      />
      <div className="demo-log" aria-label="Chart events">
        <ol>
          {log.map((line, i) => (
            <li key={`${i}-${line}`}>{line}</li>
          ))}
        </ol>
      </div>
    </div>
  );
}
```

## Keyboard

The plot is one tab stop. Arrow keys move a virtual focus between points,
Home / End jump to the ends, PageUp / PageDown switch series, Enter
selects, Escape closes the tooltip; the focused point is announced through
a polite live region. Every figure family (`PieChart`, `FunnelChart`, `HeatMap`, `TreeMap`,
`SankeyChart`, `GeoMap`, `Gauge`, `BulletChart`) follows the same model:
one tab stop, a virtual focus announced politely, legends as APG
Toolbars; their accessibility trees are pinned as ARIA snapshots.

There are no global shortcuts: a key like Alt+J collides with
screen reader and browser keys, and intercepting Ctrl+P would hijack
browser printing. Each visualization is one tab stop with the full keyboard
model inside. For a shortcut, call `api.focus()` from your own key handler,
and call `api.print()` from a button.

## Reference

`ChartApi` (the `ref`), `ChartTooltipOptions`, `ChartCrosshairOptions`,
`ChartZoomOptions` and `ChartSyncGroupProps` are in the
[API reference](https://salmonui.dev/docs/reference/charts/chart); the `interactions` feature
is in [`@salmonui/charts/chart/features`](https://salmonui.dev/docs/reference/charts/chart-features).
