# Slider

> Single and range sliders from @salmonui/inputs/slider on visually hidden native range inputs, with ticks, value labels, limits, discrete values, vertical orientation, RTL mirroring and zero React renders while dragging.

Canonical: https://salmonui.dev/docs/inputs/slider

`Slider` picks a single value or a range. Every thumb is a visually hidden native `<input type="range">`
positioned on its visual thumb: keyboard focus, `aria-valuetext`, form
submission and screen reader output come from the native input; the track,
fill and thumbs are CSS placed by two percentages.

```tsx
import { Slider } from '@salmonui/inputs/slider';
import '@salmonui/inputs/slider/styles.css';

<Slider name="volume" label="Volume" defaultValue={40} fill />
<Slider name="price" label="Price" defaultValue={[20, 80]} step={5} minStepsBetweenThumbs={2} />
```

### Live demo: Slider basics

Live demo: https://salmonui.dev/demos/inputs/slider-basics

A filled single slider with a value label, a currency range with ticks and a thumb gap, discrete sizes and a vertical slider.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Slider } from '@salmonui/inputs/slider';

// A filled single slider with a live and a committed value, a currency range with ticks, discrete sizes and a vertical slider.
export default function SliderBasicsDemo() {
  const [live, setLive] = useState(40);
  const [committed, setCommitted] = useState(40);
  return (
    <div style={{ display: 'grid', gap: 24, maxInlineSize: 360 }}>
      <Slider label="Volume" defaultValue={40} fill valueLabel={{ show: 'focus' }} onValueChange={setLive} onValueCommit={setCommitted} />
      <output>
        Live {live}, committed {committed}
      </output>
      <Slider
        label="Price"
        defaultValue={[200, 600]}
        max={1000}
        step={50}
        minStepsBetweenThumbs={2}
        formatOptions={{ style: 'currency', currency: 'USD', maximumFractionDigits: 0 }}
        ticks={{ placement: 'after', majorStep: 250, minorStep: 50, showMinor: true }}
      />
      <Slider label="Size" values={['XS', 'S', 'M', 'L', 'XL']} defaultValue="M" ticks={{ placement: 'after' }} />
      <Slider label="Level" orientation="vertical" defaultValue={60} fill ticks={{ placement: 'after', majorStep: 25 }} />
    </div>
  );
}
```

## Value

- `value` / `defaultValue` / `onValueChange(value, details)`:
  controlled with `value`, uncontrolled with `defaultValue`.
  A number gives one thumb; a `[start, end]` tuple gives a range with two
  thumbs. The default is `min` (or `[min, max]` when a tuple is
  passed).
- `min` (default 0), `max` (default 100) and `step` (default 1) bound and
  snap every value; PageUp / PageDown move by `pageStep` (default
  a tenth of the range rounded to `step`).
- `fill` fills the track from `min` to the thumb; a range always fills between its thumbs.
- `values` is a list of entries; the
  value is an entry (`'M'`), the native input holds its index and a hidden
  input submits the entry.
- `details` is `{ source, reason, thumb }`: `source` `'pointer'`,
  `'touch'`, `'keyboard'` or `'api'`; `reason` `'drag'`, `'keyboard'`,
  `'input'` (a native input event, e.g. an assistive technology increment)
  or `'reset'`; `thumb` 0 or 1.

## Change and commit

`onValueChange` fires while the value changes, at most once per animation
frame during a drag; `onValueCommit` fires once when the drag ends
(pointerup) or the key is released.

An uncontrolled slider does not re-render while dragging: pointer moves are
coalesced to one frame, which writes `--salmon-slider-start` /
`--salmon-slider-end` on the root and the native input's `value` and
`aria-valuetext`; the component renders once, on pointerup (`tests/browser/inputs-pointer.spec.ts`: zero React commits counted by a
`Profiler` during a drag, and a median move frame well under 1 ms). A
controlled slider renders what its owner passes back, so the owner can clamp
or veto a value.

### Live demo: Inputs render cost

Live demo: https://salmonui.dev/demos/inputs/inputs-performance

Render counters around text, number and masked fields show that typing re-renders only the edited field, a Slider drag and a signature stroke run without React renders, and the QueryBuilder subpath loads as its own chunk only when used.

`Demo.tsx`:

```tsx
'use client';

import { lazy, Suspense, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { Button } from '@salmonui/buttons/button';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { SignaturePad } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';
import { TextField } from '@salmonui/inputs/text-field';

const QueryBuilderPanel = lazy(() => import('./QueryBuilderPanel'));

/**
 * Counts the commits of the component that renders it. The count is written
 * to the DOM from a layout effect, so counting never causes a render.
 */
function RenderCount({ label }: { label: string }) {
  const count = useRef(0);
  const out = useRef<HTMLSpanElement>(null);
  useLayoutEffect(() => {
    count.current += 1;
    if (out.current) out.current.textContent = String(count.current);
  });
  return (
    <span className="demo-badge" aria-label={`${label} renders`}>
      {label} renders: <span ref={out}>0</span>
    </span>
  );
}

/** One field and the render count of the component around it. */
function Cell({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div style={{ display: 'grid', gap: 4 }}>
      {children}
      <RenderCount label={label} />
    </div>
  );
}

/** A controlled field: its owner re-renders per keystroke, nothing else does. */
function ControlledCell() {
  const [value, setValue] = useState('');
  const typedAt = useRef(0);
  const out = useRef<HTMLOutputElement>(null);
  useLayoutEffect(() => {
    if (typedAt.current && out.current) out.current.textContent = `last keystroke: ${(performance.now() - typedAt.current).toFixed(2)} ms from the input event to the commit`;
  });
  return (
    <Cell label="Controlled owner">
      <TextField
        label="Controlled text"
        value={value}
        onValueChange={setValue}
        onKeyDown={() => {
          typedAt.current = performance.now();
        }}
      />
      <output ref={out}>last keystroke: (type to measure)</output>
    </Cell>
  );
}

// typing re-renders only the edited field, dragging writes CSS
// or canvas without React renders, and a subpath loads only when used.
export default function InputsPerformanceDemo() {
  const sliderRenders = useRef(0);
  const moves = useRef(0);
  const strokes = useRef(0);
  const dragOut = useRef<HTMLOutputElement>(null);
  const [showBuilder, setShowBuilder] = useState(false);
  const report = () => {
    if (dragOut.current) dragOut.current.textContent = `pointer moves: ${moves.current}, Slider renders: ${sliderRenders.current}, SignaturePad value changes: ${strokes.current}`;
  };
  return (
    <div style={{ display: 'grid', gap: 20, maxInlineSize: 460 }}>
      <RenderCount label="Demo (parent)" />
      <Cell label="Text owner">
        <TextField label="Uncontrolled text" />
      </Cell>
      <Cell label="Number owner">
        <NumberField label="Uncontrolled number" defaultValue={10} />
      </Cell>
      <Cell label="Masked owner">
        <MaskedField label="Uncontrolled card" mask="0000 0000 0000 0000" />
      </Cell>
      <ControlledCell />
      <div
        style={{ display: 'grid', gap: 16 }}
        onPointerMove={(event) => {
          if (event.buttons === 0) return;
          moves.current += 1;
          report();
        }}
        onPointerUp={report}
      >
        <Slider
          label="Uncontrolled slider"
          defaultValue={50}
          fill
          valueLabel={{ show: 'always' }}
          ticks={{ placement: 'after', majorStep: 25 }}
          renderTick={(tick) => {
            // Instrumentation only: renderTick runs during the Slider's render, once per tick.
            if (tick.value === 0) sliderRenders.current += 1;
            return tick.label;
          }}
        />
        <SignaturePad
          label="Uncontrolled signature"
          style={{ maxInlineSize: 'none' }}
          height={120}
          backgroundColor="#ffffff"
          onValueChange={() => {
            strokes.current += 1;
            report();
          }}
        />
        <output ref={dragOut}>pointer moves: 0, Slider renders: 0, SignaturePad value changes: 0</output>
      </div>
      <div style={{ display: 'grid', gap: 8 }}>
        {showBuilder ? (
          <Suspense fallback={<p className="demo-status">Loading @salmonui/query-builder…</p>}>
            <QueryBuilderPanel />
          </Suspense>
        ) : (
          <Button type="button" variant="outline" onClick={() => setShowBuilder(true)} style={{ justifySelf: 'start' }}>
            Load the QueryBuilder subpath
          </Button>
        )}
      </div>
    </div>
  );
}
```

`QueryBuilderPanel.tsx`:

```tsx
'use client';

import { QueryBuilder, type QueryField } from '@salmonui/query-builder';

const fields: QueryField[] = [
  { field: 'country', label: 'Country' },
  { field: 'total', label: 'Order total', type: 'number' },
];

/** Loaded with a dynamic import: the QueryBuilder subpath arrives as its own chunk. */
export default function QueryBuilderPanel() {
  return <QueryBuilder aria-label="Orders filter" fields={fields} defaultValue={{ logic: 'and', filters: [{ field: 'country', operator: 'equal', value: 'Japan' }] }} />;
}
```

## Ranges

Two thumbs never cross; `minStepsBetweenThumbs` keeps them that many steps
apart. A press on the track moves the nearer thumb; when both
thumbs sit on one spot the first move's direction picks the thumb. The
inputs are named by the label plus `localeText.start` / `localeText.end`
("Price Minimum", "Price Maximum").

## Ticks

`ticks: { placement, majorStep, minorStep, showMinor, formatOptions }`
 renders tick marks as markup at percentage positions, so the
server output is final and nothing is measured. `placement` is `'before'`,
`'after'` (default), `'both'` or `'none'`; `majorStep` defaults to 10 (1 with
`values`), `minorStep` to 1. Major ticks are labelled with the formatted
value; `renderTick({ value, label, major, percent })` replaces the content
of every tick. Ticks are decorative (`aria-hidden`); the value text
comes from `aria-valuetext`.

## Value label

`valueLabel: { show, placement, formatOptions, format }` shows a
bubble over each thumb: `show` is `'focus'` (default: keyboard focus or
hover), `'hover'`, `'always'` or `'never'`; `placement` is `'before'`
(above, or the inline start of a vertical slider) or `'after'`.
`format(value)` returns the bubble text. The bubble is CSS only and `aria-hidden`; the part class is
`classNames.valueLabel`.

## Limits

`limits: { minStart, maxStart, minEnd, maxEnd, startFixed, endFixed }`
 bounds the start thumb (the only thumb of a single slider) and the
end thumb inside `min..max`; a fixed thumb ignores keys and the pointer, and
a press on the track moves the other thumb.

### Live demo: Slider ranges, ticks and limits

Live demo: https://salmonui.dev/demos/inputs/slider-limits

Slider min, max and step set live, tick labels formatted with ticks.formatOptions or drawn by renderTick, value label text from valueLabel.format, and range limits with a fixed start thumb.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { NumberField } from '@salmonui/inputs/number-field';
import { Slider } from '@salmonui/inputs/slider';

const hours = (value: number | string) => {
  const h = Number(value);
  return `${String(Math.floor(h)).padStart(2, '0')}:${h % 1 === 0 ? '00' : '30'}`;
};

// min / max / step from the toolbar, formatted tick labels, a custom tick
// renderer, a value label formatter and range limits with a fixed thumb.
export default function SliderLimitsDemo() {
  const [min, setMin] = useState(0);
  const [max, setMax] = useState(100);
  const [step, setStep] = useState(10);
  const [fixed, setFixed] = useState(false);
  const [range, setRange] = useState<readonly [number, number]>([9, 17]);
  return (
    <>
      <div className="demo-toolbar">
        <label>
          min
          <NumberField aria-label="min" value={min} onValueChange={(value) => setMin(value ?? 0)} style={{ inlineSize: 110 }} />
        </label>
        <label>
          max
          <NumberField aria-label="max" value={max} onValueChange={(value) => setMax(value ?? 0)} style={{ inlineSize: 110 }} />
        </label>
        <label>
          step
          <NumberField aria-label="step" value={step} min={1} onValueChange={(value) => setStep(Math.max(1, value ?? 1))} style={{ inlineSize: 110 }} />
        </label>
      </div>
      <div style={{ display: 'grid', gap: 32, maxInlineSize: 420 }}>
        <Slider
          label="Discount"
          min={min}
          max={max}
          step={step}
          defaultValue={20}
          fill
          ticks={{ placement: 'after', majorStep: step * 2, formatOptions: { style: 'unit', unit: 'percent' } }}
          formatOptions={{ style: 'unit', unit: 'percent' }}
          valueLabel={{ show: 'always', format: (value) => `${value} % off` }}
          description="Ticks formatted with ticks.formatOptions; the bubble text comes from valueLabel.format"
        />
        <Slider
          label="Mood"
          min={1}
          max={5}
          defaultValue={3}
          ticks={{ placement: 'after', majorStep: 1 }}
          renderTick={(tick) => <span aria-hidden="true">{['😞', '🙁', '😐', '🙂', '😄'][Number(tick.value) - 1]}</span>}
          valueLabel={{ show: 'hover', format: (value) => ['Awful', 'Bad', 'Okay', 'Good', 'Great'][Number(value) - 1] ?? '' }}
          description="renderTick draws each tick; the value label names the mood"
        />
        <div className="demo-toolbar" style={{ marginBlockEnd: 0 }}>
          <Checkbox checked={fixed} onCheckedChange={(checked) => setFixed(checked)}>
            limits.startFixed
          </Checkbox>
        </div>
        <Slider
          label="Opening hours"
          min={0}
          max={24}
          step={0.5}
          value={range}
          onValueChange={setRange}
          limits={{ minStart: 6, maxStart: 12, minEnd: 14, maxEnd: 22, startFixed: fixed }}
          ticks={{ placement: 'after', majorStep: 6, minorStep: 1, showMinor: true }}
          valueLabel={{ show: 'focus', format: hours }}
          description="Opening between 06:00 and 12:00, closing between 14:00 and 22:00"
        />
        <output>
          Open {hours(range[0])} to {hours(range[1])}
        </output>
      </div>
    </>
  );
}
```

## Orientation and RTL

`orientation: 'vertical'` grows upward; set its length with the
`--salmon-slider-length` custom property (default 10rem). Horizontal sliders
mirror in right-to-left content: the fill and thumbs use logical insets, a
press on the left edge selects the high end, and ArrowRight decreases;
vertical sliders never mirror.

## Form submission

`name` is submitted by each native input: a range submits `name`
twice (`price=20&price=60`), as a multiple-value field. With `values` the
entry is submitted. An uncontrolled slider restores `defaultValue` on the
owning form's `reset`; a controlled one calls `onValueChange(default, {
reason: 'reset' })`. `form` and `disabled` are forwarded.

### Live demo: Fields in a form

Live demo: https://salmonui.dev/demos/inputs/field-forms

Uncontrolled text, masked, number, radio, checkbox, switch, range slider, rating and signature fields in a native form - names and values submitted through FormData, a required incomplete mask blocking the submit, and a form reset restoring every default.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Form } from '@salmonui/inputs/form';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Rating } from '@salmonui/inputs/rating';
import { Select } from '@salmonui/dropdowns/select';
import { SignaturePad } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';
import { Switch } from '@salmonui/inputs/switch';
import { TextField } from '@salmonui/inputs/text-field';

/** One line per FormData entry; long data URLs are shortened. */
function entriesOf(form: HTMLFormElement): string[] {
  return Array.from(new FormData(form), ([key, value]) => {
    const text = typeof value === 'string' ? value : `File ${value.name}`;
    return `${key} = ${text.length > 48 ? `${text.slice(0, 40)}… (${text.length} chars)` : JSON.stringify(text)}`;
  });
}

// Every field is uncontrolled inside a native form: names submit through
// FormData (custom-drawn controls through native or hidden inputs) and the
// Reset button restores each defaultValue and clears the shown errors.
export default function FieldFormsDemo() {
  const [submitValue, setSubmitValue] = useState<'raw' | 'masked'>('raw');
  const [entries, setEntries] = useState<readonly string[]>([]);
  const [status, setStatus] = useState('Change some fields, then submit or reset.');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          MaskedField submitValue
          <Select aria-label="MaskedField submitValue" data={['raw', 'masked']} value={submitValue} onValueChange={(value) => value != null && setSubmitValue(value as 'raw' | 'masked')} />
        </label>
      </div>
      <Form
        aria-label="Delivery preferences"
        style={{ display: 'grid', gap: 16, maxInlineSize: 420 }}
        onSubmit={(event) => {
          event.preventDefault();
          setEntries(entriesOf(event.currentTarget));
          setStatus('Submitted: the FormData entries are listed below.');
        }}
        onValidate={({ valid }) => !valid && setStatus('Not submitted: fix the highlighted field.')}
        onReset={() => {
          setEntries([]);
          setStatus('Reset: every field is back to its defaultValue.');
        }}
      >
        <TextField name="name" label="Name" defaultValue="Ada Lovelace" required />
        <MaskedField name="phone" label="Phone" mask="(000) 000-0000" defaultValue="5551234567" required submitValue={submitValue} description="Required: an incomplete number blocks the submit" />
        <NumberField name="parcels" label="Parcels" defaultValue={2} min={1} max={9} />
        <RadioGroup name="slot" label="Delivery slot" defaultValue="am" orientation="horizontal">
          <Radio value="am">Morning</Radio>
          <Radio value="pm">Afternoon</Radio>
        </RadioGroup>
        <Checkbox name="extras" value="gift-wrap" defaultChecked>
          Gift wrap
        </Checkbox>
        <Switch name="notify" value="sms">
          Text me when it ships
        </Switch>
        <Slider name="window" label="Delivery window (hours)" defaultValue={[9, 17]} min={6} max={22} ticks={{ placement: 'after', majorStep: 4 }} />
        <Rating name="priority" label="Priority" defaultValue={2} count={3} />
        <SignaturePad name="signature" label="Signature" description="Optional: submitted as a PNG data URL" height={120} backgroundColor="#ffffff" />
        <div style={{ display: 'flex', gap: 8 }}>
          <Button type="submit" tone="primary">
            Submit
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </div>
      </Form>
      <p className="demo-status" role="status">
        {status}
      </p>
      <pre className="demo-log" aria-label="Submitted FormData">
        {entries.length === 0 ? '(nothing submitted yet)' : entries.join('\n')}
      </pre>
    </>
  );
}
```

## Keyboard

| Key | Action |
| --- | --- |
| Tab / Shift+Tab | Moves between thumbs (one tab stop each) |
| Arrow Right / Arrow Up | Increases by `step` (in RTL, Arrow Left increases a horizontal slider) |
| Arrow Left / Arrow Down | Decreases by `step` (in RTL, Arrow Right decreases a horizontal slider) |
| Page Up / Page Down | Increases / decreases by `pageStep` |
| Home / End | Sets the thumb to its lowest / highest allowed value |

These are the APG Slider and Multi-Thumb Slider keys. Screen
readers hear the native slider role with `aria-valuetext` formatted by
`formatOptions` and `locale` (default `'en-US'`; "$20"), the orientation, and
`aria-readonly` with `readOnly`. Try it in the
[keyboard demo](https://salmonui.dev/demos/inputs/inputs-keyboard).

## SSR

Positions, ticks and value labels are markup and CSS percentages, so the
server output is final and nothing is measured; the native range inputs
work and submit before hydration.

## Design notes

- no ticks-rendered event: a "rendered" lifecycle event has no
  React meaning. Move post-render tick code into `renderTick` or an effect.
- no built-in increase / decrease buttons: they are a composition
  the application can place anywhere. Place two `Button`s that step a
  controlled `value`; keyboard steps stay built in.
- no per-range color option: per-range colors are a theme input outside the
  five color seeds. Style the track with `classNames.track` /
  `classNames.range` and the `--salmon-slider-start` /
  `--salmon-slider-end` custom properties (for example a gradient).
- no reposition method: positions are CSS percentages, so nothing
  needs re-measuring on resize.

## API

| Prop | Type | Default |
| --- | --- | --- |
| `value`, `defaultValue` | `number \| string \| readonly [a, b]` | `min` |
| `onValueChange`, `onValueCommit` | `(value, { source, reason, thumb }) => void` | |
| `min`, `max`, `step` | `number` | `0`, `100`, `1` |
| `pageStep` | `number` | a tenth of the range |
| `values` | `readonly (string \| number)[]` | |
| `minStepsBetweenThumbs` | `number` | `0` |
| `fill` | `boolean` | `false` |
| `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` |
| `ticks` | `{ placement, majorStep, minorStep, showMinor, formatOptions }` | no ticks |
| `renderTick` | `({ value, label, major, percent }) => ReactNode` | major labels |
| `valueLabel` | `{ show, placement, formatOptions, format }` | no label |
| `formatOptions` | `Intl.NumberFormatOptions` | |
| `locale` | `string` | `'en-US'` |
| `limits` | `{ minStart, maxStart, minEnd, maxEnd, startFixed, endFixed }` | |
| `name`, `form` | `string` | not submitted |
| `disabled`, `readOnly` | `boolean` | `false` |
| `label`, `description`, `errorMessage`, `invalid`, `validation` | see [Field](https://salmonui.dev/docs/inputs/field) | |
| `localeText` | `{ start, end, validation* }` | `'Minimum'`, `'Maximum'` |
| `size` | `'sm' \| 'md' \| 'lg'` (thumb 14, 18, 22 px) | `'md'` |
| `dir`, `id`, `className`, `style` | root passthrough | |
| `classNames` | `{ label, control, track, range, thumb, valueLabel, ticks, tick, description, error }` | |
| `ref` | `HTMLDivElement` (the root) | |

Full signatures: [`@salmonui/inputs/slider` API reference](https://salmonui.dev/docs/reference/inputs/slider).
