# RangeSelector

> A two-thumb range slider over a mini series with time, linear and log scales, grouped labels, snapping, tooltips, period buttons and a form bridge; PeriodSelector on its own.

Canonical: https://salmonui.dev/docs/data-visualization/range-selector

`RangeSelector` and `PeriodSelector` live in `@salmonui/charts/range-selector`
(CSS: `@salmonui/charts/range-selector/styles.css`; `PeriodSelector` also
uses `@salmonui/buttons/button/styles.css`).

```tsx
import { RangeSelector } from '@salmonui/charts/range-selector';
import '@salmonui/charts/range-selector/styles.css';
import '@salmonui/buttons/button/styles.css'; // with periods

<RangeSelector
  data={prices}
  xField="date"
  yField="close"
  value={range}
  onValueCommit={(next) => setRange(next)}
  periods={[{ id: '1m', unit: 'month', count: 1, label: '1M' }, { id: 'all', unit: 'all', label: 'All' }]}
/>;
```

## Value

The value is `[start, end]` (numbers; epoch ms on time scales) with the
triad `value` / `defaultValue` plus two callbacks:

- `onValueChange(value, event)` during a drag, at most once per animation
  frame, without touching React state;
- `onValueCommit(value, event)` on release and after every keyboard step;
  the uncontrolled value updates here.

## Series and scales

`series: [{ type: 'line' | 'area' | 'stepLine', data, xField, yField }]` or
`data` + `xField` / `yField` draw the background series; without series the
selector is a plain axis. `scale: 'time' | 'linear' |
'log'` (time is inferred from dates), `min`, `max`, `interval` (a number or
`{ unit, step }`) and `base` set the axis.

## Labels

`format`, `formatLabel`, `labelPosition: 'inside' | 'outside'`,
`labelOverlap` and `groupLabels: { unit, align }` (a second label row by
year, month, ...). `gridLines` and `ticks` can be turned off.

## Snapping and tooltips

`snap` snaps released thumbs to the nearest data point; `snap="interval"`
selects whole intervals. `tooltip` shows the thumb values while
dragging or focused, `tooltip="always"` keeps them.

## Periods

`periods: [{ id, unit, count, label }]` renders a `PeriodSelector` (an APG
radio group) above or below (`periodSelector={{ position: 'bottom' }}`);
`unit` is a calendar unit, `'ytd'` or `'all'`, and the range ends at the
data end. `PeriodSelector` is usable alone, and `periodRange()`
computes a period's range.

## Keyboard and accessibility

The two thumbs follow the APG Slider (Multi-Thumb) pattern: `role="slider"`
with `aria-valuemin` / `aria-valuemax` bounded by the other thumb and a
formatted `aria-valuetext`; arrows step by the interval (or 1 % of the
span), PageUp / PageDown and Shift by 10 %, Home / End jump. The selected
band is a third slider that moves both thumbs. The data axis does
not mirror in RTL.

## Linking to a chart

Pass the value to a chart's zoom range:
`<Chart zoomRange={{ x: range }} />`; `StockChart` wires this
internally.

### Live demo: RangeSelector as a chart navigator

Live demo: https://salmonui.dev/demos/data-visualization/range-selector-navigator

A RangeSelector with an area, line or step-line series and period buttons drives a chart's zoom range; it reports the range live while dragging and commits it on release, and works from the keyboard.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Select } from '@salmonui/dropdowns/select';
import { Chart } from '@salmonui/charts/chart';
import { RangeSelector } from '@salmonui/charts/range-selector';
import type { RangeValue } from '@salmonui/charts/range-selector';

const DAY = 86_400_000;
const START = Date.UTC(2025, 0, 1);
const traffic = Array.from({ length: 540 }, (_, i) => ({ date: new Date(START + i * DAY), visits: Math.round(5000 + 1800 * Math.sin(i / 30) + 600 * Math.sin(i / 3.5) + i * 4) }));
const fmt = (v: number) => new Date(v).toISOString().slice(0, 10);

export default function RangeSelectorNavigatorDemo() {
  const [value, setValue] = useState<RangeValue>([Date.UTC(2025, 9, 1), Date.UTC(2026, 0, 1)]);
  const [live, setLive] = useState<RangeValue>(value);
  const [type, setType] = useState<'area' | 'line' | 'stepLine'>('area');
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Navigator series
          <Select aria-label="Navigator series" data={[{ value: 'area', label: 'area' }, { value: 'line', label: 'line' }, { value: 'stepLine', label: 'stepLine' }]} value={type} onValueChange={(value) => value != null && setType(value as 'area' | 'line' | 'stepLine')} />
        </label>
      </div>
      {/* The chart shows the committed range: zoomRange keyed by the x axis id. */}
      <Chart title="Daily visits" data={traffic} height={260} legend={false} timeZone="UTC" locale="en-US" zoomRange={{ x: value }} series={[{ type: 'line', name: 'Visits', xField: 'date', yField: 'visits' }]} />
      <RangeSelector
        aria-label="Visible dates"
        series={[{ type, data: traffic, xField: 'date', yField: 'visits' }]}
        height={90}
        timeZone="UTC"
        locale="en-US"
        value={value}
        onValueChange={(next) => setLive(next)}
        onValueCommit={(next) => {
          setValue(next);
          setLive(next);
        }}
        periods={[
          { id: '1m', unit: 'month', count: 1, label: '1M' },
          { id: '3m', unit: 'month', count: 3, label: '3M' },
          { id: '6m', unit: 'month', count: 6, label: '6M' },
          { id: 'ytd', unit: 'ytd', label: 'YTD' },
          { id: 'all', unit: 'all', label: 'All' },
        ]}
      />
      <p className="demo-status" aria-live="polite">
        onValueChange: <code>{`${fmt(live[0])} to ${fmt(live[1])}`}</code>, committed value: <code>{`${fmt(value[0])} to ${fmt(value[1])}`}</code>
      </p>
    </div>
  );
}
```

## Forms

With `name`, two hidden inputs carry the start and end (ISO strings on
time scales), and a form reset restores `defaultValue`.

Colors come from the `primary` seed (selected band and thumbs) and the
surface (dimmed regions); thumb geometry is system-owned.

### Live demo: RangeSelector scales, labels, snapping and forms

Live demo: https://salmonui.dev/demos/data-visualization/range-selector-options

A time RangeSelector with month intervals, year label groups, snapping, tooltips, grid lines and ticks inside a form, a log-scale selector without a series and a linear one snapping to whole steps.

`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 { RangeSelector } from '@salmonui/charts/range-selector';

const DAY = 86_400_000;
const START = Date.UTC(2024, 0, 1);
const rainfall = Array.from({ length: 730 }, (_, i) => ({ date: new Date(START + i * DAY), mm: Math.max(0, Math.round(4 + 4 * Math.sin(i / 58) + 3 * Math.sin(i * 0.9))) }));
const sizes = [1, 3, 10, 30, 100, 300, 1000, 3000, 10000].map((kb) => ({ kb, files: Math.round(900 / Math.sqrt(kb)) }));

type Snap = 'off' | 'points' | 'interval';
type Tooltip = 'off' | 'drag' | 'always';
type Overlap = 'none' | 'hide' | 'rotate45' | 'stagger';

export default function RangeSelectorOptionsDemo() {
  const [snap, setSnap] = useState<Snap>('interval');
  const [tooltip, setTooltip] = useState<Tooltip>('always');
  const [inside, setInside] = useState(false);
  const [overlap, setOverlap] = useState<Overlap>('hide');
  const [grid, setGrid] = useState(true);
  const [ticks, setTicks] = useState(true);
  const [submitted, setSubmitted] = useState('');
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Snap
          <Select aria-label="Snap" data={[{ value: 'off', label: 'false' }, { value: 'points', label: 'true (data points)' }, { value: 'interval', label: 'interval' }]} value={snap} onValueChange={(value) => value != null && setSnap(value as Snap)} />
        </label>
        <label>
          Tooltip
          <Select aria-label="Tooltip" data={[{ value: 'off', label: 'false' }, { value: 'drag', label: 'true (drag and focus)' }, { value: 'always', label: 'always' }]} value={tooltip} onValueChange={(value) => value != null && setTooltip(value as Tooltip)} />
        </label>
        <label>
          Label overlap
          <Select aria-label="Label overlap" data={[{ value: 'none', label: 'none' }, { value: 'hide', label: 'hide' }, { value: 'rotate45', label: 'rotate45' }, { value: 'stagger', label: 'stagger' }]} value={overlap} onValueChange={(value) => value != null && setOverlap(value as Overlap)} />
        </label>
        <Checkbox checked={inside} onCheckedChange={(checked) => setInside(checked)}>Labels inside</Checkbox>
        <Checkbox checked={grid} onCheckedChange={(checked) => setGrid(checked)}>Grid lines</Checkbox>
        <Checkbox checked={ticks} onCheckedChange={(checked) => setTicks(checked)}>Ticks</Checkbox>
      </div>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          const form = new FormData(e.currentTarget);
          setSubmitted(form.getAll('season').join(' to '));
        }}
      >
        <RangeSelector
          aria-label="Season"
          name="season"
          data={rainfall}
          xField="date"
          yField="mm"
          height={110}
          timeZone="UTC"
          locale="en-US"
          interval={{ unit: 'month', step: 1 }}
          format="MMM"
          groupLabels={{ unit: 'year', align: 'start' }}
          labelPosition={inside ? 'inside' : 'outside'}
          labelOverlap={overlap}
          gridLines={grid}
          ticks={ticks}
          snap={snap === 'off' ? false : snap === 'interval' ? 'interval' : true}
          tooltip={tooltip === 'off' ? false : tooltip === 'always' ? 'always' : { format: 'yMMMd' }}
          defaultValue={[Date.UTC(2024, 3, 1), Date.UTC(2024, 8, 1)]}
          // Always-on tooltips float above the thumbs: keep room for them.
          style={tooltip === 'always' ? { marginBlockStart: 32 } : undefined}
        />
        <div className="demo-toolbar">
          <Button variant="outline" type="submit">Submit</Button>
          <Button variant="outline" type="reset">Reset</Button>
          <span className="demo-status" aria-live="polite">
            {submitted ? `Submitted: ${submitted}` : 'Submit to see the hidden inputs'}
          </span>
        </div>
      </form>
      <RangeSelector
        aria-label="File size"
        scale="log"
        base={10}
        min={1}
        max={10000}
        formatLabel={(kb) => (kb >= 1000 ? `${kb / 1000} MB` : `${kb} KB`)}
        tooltip="always"
        defaultValue={[10, 1000]}
        height={70}
        style={{ marginBlockStart: 32 }}
      />
      <RangeSelector aria-label="Rating" scale="linear" min={0} max={10} interval={1} snap="interval" tooltip defaultValue={[3, 8]} height={60} series={[{ type: 'stepLine', data: sizes.map((d, i) => ({ x: i + 1, y: d.files })), xField: 'x', yField: 'y' }]} />
    </div>
  );
}
```

## SSR and reference

The selector renders on the server at its nominal size (600 px wide, 80 px
tall unless `height` or CSS says otherwise) and relays out once after
hydration; pass `timeZone` and `locale` for stable time labels. `ref`
gives `RangeSelectorApi` (`element`, `focus()`). Every prop is in the
[API reference](https://salmonui.dev/docs/reference/charts/range-selector).
