# Gauge

> Circular gauges with several axes, ticks, labels, tapered ranges, needle, bar and marker pointers, annotations, a range legend, tooltips, pointer transitions, and draggable pointers and ranges that follow the slider pattern.

Canonical: https://salmonui.dev/docs/data-visualization/gauge

```tsx
import { Gauge } from '@salmonui/charts/gauge';
import '@salmonui/charts/gauge/styles.css';

<Gauge
  title="Speed"
  axes={[{ ranges: [{ from: 0, to: 60, color: '#2e7d32' }, { from: 60, to: 100, color: '#c62828' }] }]}
  pointers={[{ value: 72, label: 'Speed', valueText: (v) => `${v} km/h` }]}
/>;
```

`Gauge` draws circular and linear gauges with one
component: `shape="circular"` (default) or `shape="linear"` (see
[Linear gauge](https://salmonui.dev/docs/data-visualization/linear-gauge)). The markup is final on
the server: the drawing has a fixed size (`width` / `height`, default 240 x
240) and a `viewBox`, so it scales with its container and never relays out
after hydration (no `onResize`).

`axes` and `pointers` also have a JSX form: `GaugeAxis` and `GaugePointer`
children take the same fields as an array entry and are read in order when
the array prop is absent (`pointer.axis` then counts `GaugeAxis` children).

```tsx
import { Gauge, GaugeAxis, GaugePointer } from '@salmonui/charts/gauge';

<Gauge title="Load">
  <GaugeAxis min={0} max={200} ranges={[{ from: 150, to: 200, label: 'High' }]} />
  <GaugePointer value={120} label="Load" />
</Gauge>;
```

## Axes

`axes` is an array (default one axis from 0 to 100). Each axis takes `min`,
`max`, `startAngle` and `endAngle` in degrees clockwise from 12 o'clock
(default 225 and 135, a 270-degree dial), `direction: 'clockwise' |
'counterclockwise'` and `radius` as a fraction of the available radius.
`center` moves the dial (fractions of the drawing) and `rangeGap`
separates inside ranges from the axis line. Several axes draw concentric
dials; a pointer picks its axis with `pointer.axis`.

## Ticks and labels

- `axis.ticks`: `interval` (default a nice step), `minor` (minor tick
  interval), `position: 'inside' | 'outside' | 'cross'`, `rangeColor` (ticks
  inside a range take its color) and `hidden`.
- `axis.labels`: `position: 'inside' | 'outside'`, `rotate` (along the arc),
  `hide: 'first' | 'last'`, `showLast`, `overlap: 'hide'` (default) and
  `format` (`Intl.NumberFormatOptions`, with the `locale` prop).
- `axis.formatLabel(value)` returns any label text.

## Ranges

`axis.ranges: [{ id, from, to, width, position, color, label }]`.
`width` is a number or `[start, end]` for a tapered band; `position` is
`'inside'`, `'outside'` or `'cross'`. A range without a `color` takes the
next slot of the categorical palette, or of `palette` when given. Colors are
data colors: they are used as given.

## Pointers

`pointers` is an array; each pointer is reactive: change `value` and the
gauge redraws (no `setPointerValue()`).

- `type: 'needle'` (default on circular gauges): `length` and `tail` as
  fractions of the radius, `width` and `cap` in pixels.
- `type: 'bar'`: a range bar from the minimum to the value.
- `type: 'marker'`: `shape` is `circle`, `rectangle`, `triangle`,
  `invertedTriangle`, `diamond`, `arrow`, `invertedArrow` or `text` (with
  `text`); `render` draws any React content, an image for example, at the
  pointer.

## Dragging

`draggable` turns a pointer into an APG slider: drag it, or focus it
and press the arrow keys (one `step`, default 1 % of the axis), Page Up /
Page Down (ten steps) and Home / End. Arrow keys follow the data direction,
which never mirrors in right-to-left pages. `onPointerValueChange({ pointerId,
value }, event)` proposes values during a drag and on each key press;
`onPointerValueCommit` fires on release and once per key press. Both receive
a frozen event with `source` (`'pointer'`, `'keyboard'`, `'touch'`) and
`reason` (`'drag'`, `'release'`, `'keyboard'`). A controlled pointer (`value`)
moves only when you update the prop; an uncontrolled one starts at
`defaultValue` and keeps the committed value itself. The drag preview lives in
the component's store, never in React state.

```tsx
import { useState } from 'react';
import { Gauge } from '@salmonui/charts/gauge';

function Volume() {
  const [volume, setVolume] = useState(40);
  return (
    <Gauge
      pointers={[{ id: 'volume', type: 'marker', value: volume, draggable: true, step: 5, label: 'Volume' }]}
      onPointerValueChange={(change) => setVolume(change.value)}
    />
  );
}
```

`range.draggable` makes both ends of a range slider thumbs (the APG
multi-thumb slider): each end is a `role="slider"` named after the range
(`"Comfort band start"`, `"Comfort band end"`) whose `aria-valuemin` /
`aria-valuemax` stop at the other end, so the ends never cross. Drag an end or
use the same keys as a pointer (`range.step`, default 1 % of the axis).
Ranges are reactive props: `onRangeChange({ rangeId, from, to }, event)`
reports the moved range during a drag (`event.reason === 'drag'`), on release
(`'release'`) and per key press (`'keyboard'`); apply it to `axes`.

```tsx
// inside a component
const [band, setBand] = useState({ from: 40, to: 70 });

<Gauge
  axes={[{ ranges: [{ id: 'band', ...band, label: 'Comfort band', draggable: true, step: 5 }] }]}
  onRangeChange={(change) => setBand({ from: change.from, to: change.to })}
/>;
```

### Live demo: Thermostat with a draggable comfort range

Live demo: https://salmonui.dev/demos/data-visualization/gauge-thermostat

A circular gauge with triangle, diamond, text and custom-rendered marker pointers, a draggable comfort range, degree axis labels through formatLabel, animated pointer updates and root pointer events.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Gauge } from '@salmonui/charts/gauge';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';

/** A thermostat: marker pointers, a draggable comfort range, formatted labels, animation and root events. */
export default function GaugeThermostatDemo() {
  const [indoor, setIndoor] = useState(20.5);
  const [comfort, setComfort] = useState({ from: 19, to: 23 });
  const [animated, setAnimated] = useState(true);
  const [over, setOver] = useState(false);
  const inComfort = indoor >= comfort.from && indoor <= comfort.to;
  return (
    <div className="demo-stack">
      <div className="demo-toolbar" role="group" aria-label="Thermostat">
        <Button variant="outline" type="button" onClick={() => setIndoor((t) => Math.max(10, t - 1.5))}>
          Cooler
        </Button>
        <Button variant="outline" type="button" onClick={() => setIndoor((t) => Math.min(30, t + 1.5))}>
          Warmer
        </Button>
        <Checkbox checked={animated} onCheckedChange={(checked) => setAnimated(checked)}>
          Animate pointers
        </Checkbox>
      </div>
      <div style={{ inlineSize: 300 }}>
        <Gauge
          title="Living room"
          subtitle="Drag either end of the comfort band"
          animated={animated}
          tooltip
          axes={[
            {
              min: 10,
              max: 30,
              ticks: { interval: 5, minor: 1 },
              formatLabel: (v) => `${v}°`,
              ranges: [
                { id: 'cold', from: 10, to: comfort.from, color: '#2563eb', label: 'Too cold' },
                { id: 'comfort', from: comfort.from, to: comfort.to, color: '#15803d', label: 'Comfort', draggable: true, step: 0.5, width: 14 },
                { id: 'warm', from: comfort.to, to: 30, color: '#c2410c', label: 'Too warm' },
              ],
            },
          ]}
          pointers={[
            { id: 'indoor', type: 'marker', shape: 'invertedTriangle', position: 'outside', value: indoor, width: 16, color: 'var(--salmon-text-primary)', label: 'Indoor', valueText: (v) => `${v} °C indoors` },
            { id: 'night', type: 'marker', shape: 'diamond', position: 'inside', value: 16, width: 12, color: '#6b7280', label: 'Night setpoint' },
            {
              id: 'outdoor',
              type: 'marker',
              shape: 'circle',
              position: 'outside',
              value: 12,
              width: 8,
              color: '#a16207',
              label: 'Outdoor',
              valueText: (v) => `${v} °C outdoors`,
              // Custom content (an icon or an image) drawn at the pointer position.
              render: ({ x, y }) => (
                <g stroke="#a16207" strokeWidth={1.5} aria-hidden="true">
                  {[0, 45, 90, 135, 180, 225, 270, 315].map((a) => {
                    const r = (a * Math.PI) / 180;
                    return <line key={a} x1={x + Math.cos(r) * 6} y1={y + Math.sin(r) * 6} x2={x + Math.cos(r) * 9} y2={y + Math.sin(r) * 9} />;
                  })}
                </g>
              ),
            },
            { id: 'eco', type: 'marker', shape: 'text', text: 'ECO', position: 'inside', value: 17, color: '#15803d', label: 'Eco setpoint' },
          ]}
          onRangeChange={(change) => {
            if (change.rangeId === 'comfort') setComfort({ from: change.from, to: change.to });
          }}
          onPointerEnter={() => setOver(true)}
          onPointerLeave={() => setOver(false)}
        />
      </div>
      <p className="demo-status" aria-live="polite">
        Indoor <code>{indoor} °C</code> is {inComfort ? 'inside' : 'outside'} the comfort band <code>{comfort.from}–{comfort.to} °C</code>
        {over ? ' · pointer over the gauge' : ''}
      </p>
    </div>
  );
}
```

## Annotations, legend and tooltips

- `axis.annotations: [{ angle, radius, content, rotate, label }]` place React
  content on the dial.
- `legend` (`true` or `{ position: 'top' | 'bottom', title, toggle }`) lists
  the ranges as a toolbar of toggle buttons; the triad `hiddenRanges` /
  `defaultHiddenRanges` / `onHiddenRangesChange(ids, event)` controls which
  ranges (by range `id`) are hidden.
- `tooltip` shows the value of a hovered or focused pointer and the span of a
  hovered range. `tooltip.targets` picks among `'pointer'`,
  `'range'` and `'annotation'` (default the first two); an annotation tooltip
  shows the annotation's `label`. `tooltip.render(ctx)` replaces the content;
  `ctx.target` tells which kind was hovered.

## Animation

`animated` (default `true`) moves pointers from the axis minimum on first
display and from the previous value on every later change: one
transition of about 0.6 s. The server and the hydration render draw the final
values, so there is no hydration difference; the transition starts after
hydration from a small lazy chunk and writes the pointer geometry to the DOM
per frame, never through React state. It is off under
`prefers-reduced-motion: reduce`, and drags and key presses move the pointer
directly. Ranges, ticks and labels render with the first frame.

## Accessibility

The gauge is a `<figure>` labelled by `title`, described by an automatic
summary and backed by a visually hidden data table (`showDataTable` shows
it). Each read-only pointer is a `role="meter"` with `aria-valuemin`,
`aria-valuemax`, `aria-valuenow` and `aria-valuetext` (from `valueText`); a
draggable pointer or range end is a `role="slider"` in the tab order.
`title` and `subtitle` are also drawn at the top of the drawing (the gauge
sits below them); `subtitle` and `description` (which replaces the summary)
complete the figure, and `locale` formats labels and value text. For a plain progress ring
use `Progress` from Notifications instead.

## Export and DOM events

`ref` receives a `GaugeApi`: `element`, `export({ format, fileName, scale })`
(`'png'`, `'jpeg'` or `'svg'`), `toBlob`, `toDataURL`, `toSVGString`,
`print()` and `focus()` (the first slider thumb); the export code is a lazy
chunk. DOM props and handlers (`onPointerMove`, `onClick`, `data-*`) go to the
root `<figure>`, so any pointer or mouse handler works on the whole gauge.
The full prop and type list is in the
[API reference](https://salmonui.dev/docs/reference/charts/gauge).

## Design notes

Values, ranges and annotations are reactive props: change `value`, `ranges`
or `annotations` to update the gauge; there are no setter methods. Tooltips
and annotations take React content (`tooltip.render`, `content`), never
HTML strings. Animation is on or off (`animated`) with system-owned timing,
and surface colors come from the theme seeds; use `className` / `style`
for the rest (see [Rendering and colors](https://salmonui.dev/docs/data-visualization/rendering-and-colors)).

### Live demo: Circular gauge with ranges and a draggable pointer

Live demo: https://salmonui.dev/demos/data-visualization/gauge-basic

A speedometer with tapered ranges, minor ticks, an annotation, a range legend and tooltips, next to a controlled dial whose needle you drag or step with the keyboard.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Gauge } from '@salmonui/charts/gauge';

const ranges = [
  { id: 'normal', from: 0, to: 60, color: '#2e7d32', label: 'Normal' },
  { id: 'high', from: 60, to: 85, color: '#b26a00', label: 'High' },
  { id: 'critical', from: 85, to: 100, color: '#c62828', label: 'Critical', width: [10, 18] as const },
];

// A read-only speedometer and a controlled, draggable volume dial.
export default function GaugeBasicDemo() {
  const [volume, setVolume] = useState(40);
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'flex-start' }}>
      <div style={{ inlineSize: 260 }}>
        <Gauge
          title="Speed"
          axes={[{ ranges, ticks: { minor: 5 }, annotations: [{ angle: 180, radius: 0.45, content: <strong>72 km/h</strong> }] }]}
          pointers={[{ value: 72, label: 'Speed', valueText: (v) => `${v} km/h` }]}
          legend
          tooltip
        />
      </div>
      <div style={{ inlineSize: 260 }}>
        <Gauge
          title="Volume"
          axes={[{ startAngle: 270, endAngle: 90, labels: { position: 'outside' } }]}
          pointers={[
            { type: 'bar', value: volume, width: 14 },
            { id: 'volume', value: volume, draggable: true, label: 'Volume', step: 5, length: 0.7 },
          ]}
          onPointerValueChange={(change) => setVolume(change.value)}
        />
        <output>Volume: {volume}</output>
      </div>
    </div>
  );
}
```
