# Slider
A number or range on a track, set by drag, keyboard or agent.
Source page: https://dinachi.dev/docs/components/slider

## Installation
```bash
npx @dinachi/cli@latest add slider
```
Adds to your project:
- `components/ui/slider/slider.tsx`
- `components/ui/slider/index.ts`
Installs:
- `@base-ui/react` ^1.9.0

## Usage
```tsx
import {
  Slider,
  SliderControl,
  SliderLabel,
  SliderRange,
  SliderThumb,
  SliderTrack,
} from "@/components/ui/slider"

export function VolumeSlider() {
  return (
    <Slider defaultValue={50}>
      <SliderLabel>Volume</SliderLabel>
      <SliderControl>
        <SliderTrack>
          <SliderRange />
          <SliderThumb />
        </SliderTrack>
      </SliderControl>
    </Slider>
  )
}
```

## Anatomy
```tsx
<Slider>
  <SliderLabel />
  <SliderValue />
  <SliderControl>
    <SliderTrack>
      <SliderRange />
      <SliderThumb />
    </SliderTrack>
  </SliderControl>
</Slider>
```
- `Slider`: Holds the value, the bounds and the step.
- `SliderLabel`: The visible label, tied to the thumbs.
- `SliderValue`: Shows the current value as text.
- `SliderControl`: The area that takes pointer input.
- `SliderTrack`: The rail the thumbs move along.
- `SliderRange`: The filled part of the track.
- `SliderThumb`: A draggable handle, one per value.
- `SliderDirectionProvider`: Sets text direction for arrow keys.

## Examples

### Default
One thumb with a label.
```tsx
import { Slider, SliderLabel, SliderControl, SliderTrack, SliderRange, SliderThumb } from '@/components/ui/slider';

export function Example() {
  return (
    <Slider defaultValue={50} className="w-full max-w-sm">
      <SliderLabel>Volume</SliderLabel>
      <SliderControl>
        <SliderTrack>
          <SliderRange />
          <SliderThumb />
        </SliderTrack>
      </SliderControl>
    </Slider>
  );
}
```

### Controlled
Controlled value shown beside the label.
```tsx
import { Slider, SliderLabel, SliderControl, SliderTrack, SliderRange, SliderThumb, SliderValue } from '@/components/ui/slider';
import { useState } from 'react';

export function Example() {
  const [value, setValue] = useState(50);

  return (
    <div className="w-full max-w-sm space-y-4">
      <Slider value={value} onValueChange={(val) => setValue(val as number)}>
        <div className="flex items-center justify-between gap-2">
          <SliderLabel>Brightness</SliderLabel>
          <SliderValue className="text-sm text-muted-foreground" />
        </div>
        <SliderControl>
          <SliderTrack>
            <SliderRange />
            <SliderThumb aria-label="Brightness" />
          </SliderTrack>
        </SliderControl>
      </Slider>
    </div>
  );
}
```

### Range
Two thumbs select a low and a high value.
```tsx
import { Slider, SliderControl, SliderTrack, SliderRange, SliderThumb } from '@/components/ui/slider';
import { useState } from 'react';

export function Example() {
  const [range, setRange] = useState([25, 75]);

  return (
    <div className="w-full max-w-sm space-y-4">
      <div className="flex items-center justify-between">
        <label className="text-sm font-medium text-foreground">Price Range</label>
        <span className="text-sm text-muted-foreground">
          ${range[0]} - ${range[1]}
        </span>
      </div>
      <Slider value={range} onValueChange={(val) => setRange(val as number[])}>
        <SliderControl>
          <SliderTrack>
            <SliderRange />
            <SliderThumb index={0} aria-label="Minimum price" />
            <SliderThumb index={1} aria-label="Maximum price" />
          </SliderTrack>
        </SliderControl>
      </Slider>
    </div>
  );
}
```

### Steps
Snaps to steps of 25.
```tsx
import { Slider, SliderControl, SliderTrack, SliderRange, SliderThumb } from '@/components/ui/slider';
import { useState } from 'react';

export function Example() {
  const [value, setValue] = useState(50);
  const steps = [0, 25, 50, 75, 100];

  return (
    <div className="w-full max-w-sm space-y-4">
      <div className="flex items-center justify-between">
        <label className="text-sm font-medium text-foreground">Quality</label>
        <span className="text-sm text-muted-foreground">{value}%</span>
      </div>
      <Slider value={value} onValueChange={(val) => setValue(val as number)} step={25}>
        <SliderControl>
          <SliderTrack>
            <SliderRange />
            <SliderThumb aria-label="Quality" />
          </SliderTrack>
        </SliderControl>
      </Slider>
      <div className="flex justify-between text-xs text-muted-foreground">
        {steps.map((step) => (
          <span key={step}>{step}%</span>
        ))}
      </div>
    </div>
  );
}
```

### Disabled
Blocks people and agents.
```tsx
import { Slider, SliderControl, SliderTrack, SliderRange, SliderThumb } from '@/components/ui/slider';

export function Example() {
  return (
    <div className="w-full max-w-sm space-y-4">
      <label className="text-sm font-medium text-muted-foreground">
        Volume (Locked)
      </label>
      <Slider defaultValue={30} disabled>
        <SliderControl>
          <SliderTrack>
            <SliderRange />
            <SliderThumb aria-label="Volume" />
          </SliderTrack>
        </SliderControl>
      </Slider>
    </div>
  );
}
```

## Notes

### Single value or range
A number gives one thumb and an array gives a range. In a range, `onValueChange` receives an array, and each `SliderThumb` needs its `index`.

### Naming a range
Without a `SliderLabel`, the agent lists a range under its first thumb's `aria-label`. Add a `SliderLabel` or an `aria-label` on `Slider` to name the whole control.

## API reference
Props marked **agent** change what an agent reads or may do.

### Slider
Holds the value, the bounds and the step.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `number \| number[]` | - | Controlled value. An array gives one thumb per entry. |
| `defaultValue` | `number \| number[]` | `min` | Starting value when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs on every move, for people and agents. `details.cancel()` refuses the change. |
| `onValueCommitted` **agent** | `(value, details) => void` | - | Runs when a drag ends, and once after an agent's change. |
| `min` **agent** | `number` | `0` | The lowest value. Agents are refused below it. |
| `max` **agent** | `number` | `100` | The highest value. Agents are refused above it. |
| `step` **agent** | `number` | `1` | The increment. Agent values snap to it. |
| `largeStep` | `number` | `10` | The increment for Page Up, Page Down and Shift with an arrow. |
| `minStepsBetweenValues` | `number` | `0` | Keeps range thumbs this many steps apart. |
| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | The direction of the track. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `format` | `Intl.NumberFormatOptions` | - | How `SliderValue` and the announced text format the number. |
| `name` | `string` | - | Submits the value with a form. |

### SliderLabel
The visible label, tied to the thumbs.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | - | Also the name the agent reads. |

### SliderValue
Shows the current value as text.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `(formattedValues, values) => ReactNode` | - | Formats the values yourself, for example a range as `20 to 80`. |

### SliderControl
The area that takes pointer input.

Takes the props of the element it renders.

### SliderTrack
The rail the thumbs move along.

Takes the props of the element it renders.

### SliderRange
The filled part of the track.

Takes the props of the element it renders.

### SliderThumb
A draggable handle, one per value.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `index` | `number` | - | Which value this thumb holds. Required with more than one thumb. |
| `aria-label` **agent** | `string` | - | Names the thumb. The agent uses it when the slider has no label. |
| `getAriaValueText` | `(formattedValue, value, index) => string` | - | The text screen readers announce for this thumb. |
| `disabled` | `boolean` | `false` | Blocks this thumb only. |

### SliderDirectionProvider
Sets text direction for arrow keys.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `direction` | `"ltr" \| "rtl"` | `"ltr"` | The reading direction. |

## Agent
Inside an `AgentProvider`, Slider appears in `agent.snapshot()` as `slider`.
Reads:
- `label`: The `SliderLabel` or the slider's aria-label, else the first thumb's aria-label.
- `value`: The number, or [low, high] for a range.
- `min / max / step`: The bounds and the increment.
- `disabled`: True when the slider is blocked.
Actions:
- `setValue(60)`: Snaps to the step. Rejects values out of range, values that are not numbers, and a range sent out of order or with the wrong count.
- `setValue([20, 80])`: Sets both ends of a range at once.
An agent's change runs through `onValueChange` like anyone's. `isAgentChange(details)` is true for it; `details.cancel()` refuses it and the agent is told the app refused. A disabled slider refuses on its own.
```ts
await agent.act({
  steps: [{ ref: "Volume", action: "setValue", args: [60] }],
})
```

## Accessibility
- Each thumb holds a range input that announces its value and bounds.
- Name it with a `SliderLabel` or an aria-label per thumb. The agent reads the same name.
- In a range, label each thumb, for example "Minimum price" and "Maximum price".
- Reduced motion turns off the thumb's grow on drag.
### Keyboard
| Keys | Does |
| --- | --- |
| `←` / `→` | Moves the focused thumb by one step |
| `↑` / `↓` | Moves the focused thumb by one step |
| `Shift` | Held with an arrow, moves by the large step |
| `Page Up` / `Page Down` | Moves by the large step |
| `Home` / `End` | Jumps to the minimum or maximum, or up to the neighbouring thumb in a range |

## Source
`components/ui/slider/slider.tsx`
```tsx
import * as React from "react";
import { Slider as BaseSlider } from "@base-ui/react/slider";
import { DirectionProvider } from "@base-ui/react/direction-provider";
import { cn } from "@/lib/utils";
import { agentRound, changeAsAgent, createAgentChangeDetails, useAgentControl, useAgentState, useHasAgent, useMergedRef } from "@/components/ui/agent";

type SliderNumber = number | readonly number[];

/** One number, snapped to the step from min, or what is wrong with it. */
function snapped(item: unknown, min: number, max: number, step: number): number | string {
  const n = Number(item);
  if (item === "" || item === null || !Number.isFinite(n)) return `"${String(item)}" is not a number.`;
  if (n < min || n > max) return `${n} is out of range: ${min} to ${max}.`;
  return Math.min(max, agentRound(min + Math.round((n - min) / step) * step, min, step));
}

/** Snaps to the step and checks the bounds and shape, or says what is wrong. */
function sliderValue(wanted: unknown, current: SliderNumber, min: number, max: number, step: number): SliderNumber | string {
  const count = Array.isArray(current) ? current.length : 0;
  const list: unknown[] = Array.isArray(wanted) ? wanted : [wanted];
  if (list.length !== Math.max(count, 1)) return count ? `Send ${count} numbers, low to high.` : "Send one number.";
  const next = list.map((item) => snapped(item, min, max, step));
  const wrong = next.find((n) => typeof n === "string");
  if (wrong !== undefined) return wrong;
  if (next.some((n, i) => i > 0 && n < next[i - 1])) return "Values must go from low to high.";
  return count ? (next as number[]) : (next[0] as number);
}

/**
 * Base UI's root, holding its own value so an agent can set it the way a parent would.
 * Controlled use is unchanged, and `onValueChange` sees the agent's change first and can
 * cancel it.
 */
const Slider = React.forwardRef<
  React.ComponentRef<typeof BaseSlider.Root>,
  React.ComponentProps<typeof BaseSlider.Root>
>(({ className, value: valueProp, defaultValue, onValueChange, ...props }, ref) => {
  type Details = BaseSlider.Root.ChangeEventDetails;
  const { min = 0, max = 100, step = 1 } = props;
  const [value, changeValue] = useAgentState<SliderNumber, Details>(
    valueProp,
    defaultValue ?? min,
    onValueChange as ((value: SliderNumber, details: Details) => void) | undefined
  );
  const element = React.useRef<HTMLDivElement>(null);

  useAgentControl(() => {
    const root = element.current;
    // Unnamed, the slider takes the name a thumb was given.
    const named = root?.matches("[aria-label], [aria-labelledby], [data-agent-label]");
    return {
      kind: "slider",
      element: root,
      label: named ? undefined : root?.querySelector("input")?.getAttribute("aria-label") ?? undefined,
      value: Array.isArray(value) ? [...value] : (value as number),
      min,
      max,
      step,
      disabled: props.disabled,
      actions: {
        setValue: (wanted: unknown) => {
          const next = sliderValue(wanted, value, min, max, step);
          if (typeof next === "string") return next;
          // An agent's change is whole at once, so it is committed too, as a drag is on release.
          return changeAsAgent(changeValue, next) ?? void props.onValueCommitted?.(next, createAgentChangeDetails("none"));
        },
      },
    };
  });

  return (
    <BaseSlider.Root
      ref={useMergedRef(ref, element)}
      className={cn("relative flex w-full flex-col gap-2", className)}
      value={value}
      onValueChange={changeValue}
      data-slot="slider"
      {...props}
    />
  );
});
Slider.displayName = "Slider";

/** The root reports every thumb as one control, so the thumbs' own inputs stay out. */
const hideFromAgent = (node: HTMLInputElement | null) => node?.setAttribute("data-agent-part", "");

const SliderValue = React.forwardRef<
  React.ComponentRef<typeof BaseSlider.Value>,
  React.ComponentProps<typeof BaseSlider.Value>
>(({ className, ...props }, ref) => (
  <BaseSlider.Value
    ref={ref}
    data-slot="slider-value"
    className={cn("text-sm font-medium", className)}
    {...props}
  />
));
SliderValue.displayName = "SliderValue";

const SliderControl = React.forwardRef<
  React.ComponentRef<typeof BaseSlider.Control>,
  React.ComponentProps<typeof BaseSlider.Control>
>(({ className, ...props }, ref) => (
  <BaseSlider.Control
    ref={ref}
    data-slot="slider-control"
    className={cn("relative flex w-full touch-none select-none items-center", className)}
    {...props}
  />
));
SliderControl.displayName = "SliderControl";

const SliderTrack = React.forwardRef<
  React.ComponentRef<typeof BaseSlider.Track>,
  React.ComponentProps<typeof BaseSlider.Track>
>(({ className, ...props }, ref) => (
  <BaseSlider.Track
    ref={ref}
    data-slot="slider-track"
    className={cn(
      "relative h-2 w-full grow rounded-full bg-secondary shadow-[inset_0_0_0_1px] shadow-secondary-foreground/5",
      className
    )}
    {...props}
  />
));
SliderTrack.displayName = "SliderTrack";

const SliderRange = React.forwardRef<
  React.ComponentRef<typeof BaseSlider.Indicator>,
  React.ComponentProps<typeof BaseSlider.Indicator>
>(({ className, ...props }, ref) => (
  <BaseSlider.Indicator
    ref={ref}
    data-slot="slider-range"
    className={cn("absolute h-full bg-primary rounded-full", className)}
    {...props}
  />
));
SliderRange.displayName = "SliderRange";

const SliderThumb = React.forwardRef<
  React.ComponentRef<typeof BaseSlider.Thumb>,
  React.ComponentProps<typeof BaseSlider.Thumb>
>(({ className, inputRef, ...props }, ref) => (
  <BaseSlider.Thumb
    ref={ref}
    data-slot="slider-thumb"
    inputRef={useMergedRef(inputRef, useHasAgent() ? hideFromAgent : undefined)}
    className={cn(
      "block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background",
      "transition-[color,background-color,border-color,transform,scale] duration-150",
      "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
      "data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      "data-[dragging]:scale-110 motion-reduce:data-[dragging]:scale-100",
      className
    )}
    {...props}
  />
));
SliderThumb.displayName = "SliderThumb";

const SliderLabel = React.forwardRef<
  React.ComponentRef<typeof BaseSlider.Label>,
  React.ComponentProps<typeof BaseSlider.Label>
>(({ className, ...props }, ref) => (
  <BaseSlider.Label
    ref={ref}
    data-slot="slider-label"
    className={cn("block text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70", className)}
    {...props}
  />
));
SliderLabel.displayName = "SliderLabel";

const SliderDirectionProvider: React.FC<React.ComponentProps<typeof DirectionProvider>> = ({
  children,
  ...props
}) => (
  <DirectionProvider {...props}>
    {children}
  </DirectionProvider>
);
SliderDirectionProvider.displayName = "SliderDirectionProvider";

export type SliderProps = React.ComponentProps<typeof BaseSlider.Root>;
export type SliderValueProps = React.ComponentProps<typeof BaseSlider.Value>;
export type SliderControlProps = React.ComponentProps<typeof BaseSlider.Control>;
export type SliderTrackProps = React.ComponentProps<typeof BaseSlider.Track>;
export type SliderRangeProps = React.ComponentProps<typeof BaseSlider.Indicator>;
export type SliderThumbProps = React.ComponentProps<typeof BaseSlider.Thumb>;
export type SliderLabelProps = React.ComponentProps<typeof BaseSlider.Label>;
export type SliderDirectionProviderProps = React.ComponentProps<typeof DirectionProvider>;

export {
  Slider,
  SliderValue,
  SliderLabel,
  SliderControl,
  SliderTrack,
  SliderRange,
  SliderThumb,
  SliderDirectionProvider,
};
```
