# Elastic slider

> A native slider with a yielding track, live value and keyboard reachable preset stops.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/elastic-slider`
- File: `src/components/haze/ui/elastic-slider.astro`
- npm dependencies: none
- Registry dependencies: @haze/slider, @haze/utils
- Docs page: https://hazeui.com/ui/elastic-slider

## Use when
- Volume, intensity or a similar continuous setting benefits from subtle resistance at the limits.
- A few common values should be reachable directly as named presets.

## Avoid when
- Use slider for a plain compact range without preset buttons.
- Use range-slider when users choose both bounds of an interval.

## Alternatives
- [slider](https://hazeui.com/ui/slider.md)
- [range-slider](https://hazeui.com/ui/range-slider.md)
- [ruler-slider](https://hazeui.com/ui/ruler-slider.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller supplied prefix for the control and its associated content. |
| name | `string` | id | no | Name submitted by the native form control. |
| label | `string` | Playback volume | no | Visible label for the range input. |
| min | `number` | 0 | no | Lower bound of the domain. |
| max | `number` | 100 | no | Upper bound of the domain. |
| step | `number` | 1 | no | Native range increment. |
| value | `number` | 60 | no | Initial setting, clamped to the supplied domain. |
| unit | `string` | % | no | Suffix used in the readout and accessible value. |
| marks | `{ value: number; label: string }[]` | Mute / Half / Full | no | Named native datalist stops with enhanced shortcut buttons. |
| disabled | `boolean` | false | no | Prevents user changes through the native disabled state. |
| class | `string` |  | no | Additional classes on this component's outer wrapper. |
| [key: string] | `unknown` |  | no | Other native range attributes are passed through to Slider. |

## Accessibility
- The real range input remains the only slider and provides native keyboard behavior and forced color support.
- The datalist works without enhancement; preset buttons are enabled only after their handlers are ready.
- The visible readout is hidden from assistive technology because aria-valuetext supplies the same value with its unit.
- Track displacement is capped at eight pixels and is skipped for reduced motion; cancellation releases the transient displacement.
- Key Arrows / Home / End: Adjust the native range or reach either end.
- Key Tab, Enter / Space: Focus and apply one of the named stops.

## Agent prompts

### Install and use

Install the Haze UI component "Elastic slider" with `npx shadcn@latest add @haze/elastic-slider`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ElasticSlider from "@/components/haze/ui/elastic-slider.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/elastic-slider.md

### Customize with real content

Adapt the Haze elastic-slider ui for our product. Replace the demo values of these props with our real content: id, name, label, min, max, step, value, unit, marks, disabled, class, [key: string]. Keep the layout, the heading level rules and these accessibility details: The real range input remains the only slider and provides native keyboard behavior and forced color support. The datalist works without enhancement; preset buttons are enabled only after their handlers are ready. The visible readout is hidden from assistive technology because aria-valuetext supplies the same value with its unit. Track displacement is capped at eight pixels and is skipped for reduced motion; cancellation releases the transient displacement. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using elastic-slider, check it fits: use it when volume, intensity or a similar continuous setting benefits from subtle resistance at the limits.; a few common values should be reachable directly as named presets.. Avoid it when use slider for a plain compact range without preset buttons.; use range-slider when users choose both bounds of an interval.. Alternatives: @haze/slider, @haze/range-slider, @haze/ruler-slider.

## Example requests that should lead here
- Add a listening volume control with Mute, Half and Full presets
- Use an elastic native slider for playback intensity

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";
import Slider from "./slider.astro";

interface Props {
  id: string;
  name?: string;
  label?: string;
  min?: number;
  max?: number;
  step?: number;
  value?: number;
  unit?: string;
  marks?: { value: number; label: string }[];
  disabled?: boolean;
  class?: string;
  [key: string]: unknown;
}
const { id, name = id, label = "Playback volume", min = 0, max = 100, step = 1, value = 60, unit = "%", marks = [{ value: 0, label: "Mute" }, { value: 50, label: "Half" }, { value: 100, label: "Full" }], disabled, class: className, ...rest } = Astro.props;
const floor = Number.isFinite(min) ? min : 0;
const ceiling = Number.isFinite(max) && max > floor ? max : floor + 100;
const increment = Number.isFinite(step) && step > 0 ? step : 1;
const initial = Number.isFinite(value) ? Math.max(floor, Math.min(ceiling, value)) : floor;
const stops = marks.filter((mark) => Number.isFinite(mark.value) && mark.value >= floor && mark.value <= ceiling);
---
<div data-haze-elastic-slider data-unit={unit} class={cn("grid w-full min-w-0 gap-3 text-foreground", className)}>
  <div class="flex flex-wrap items-baseline justify-between gap-2">
    <label for={id} class="text-[0.8125rem]/5 font-medium">{label}</label>
    <output data-readout for={id} aria-hidden="true" class="text-[0.8125rem]/5 text-muted-foreground tabular-nums">{initial}{unit}</output>
  </div>
  <div data-elastic-track class="translate-x-(--elastic-offset,0px) transition-[translate] duration-200 ease-snappy data-[dragging]:duration-75">
    <Slider id={id} name={name} min={floor} max={ceiling} step={increment} value={initial} disabled={disabled} list={`${id}-stops`} {...rest} />
  </div>
  <datalist id={`${id}-stops`}>{stops.map((mark) => <option value={mark.value} label={mark.label} />)}</datalist>
  <div class="flex flex-wrap justify-between gap-1">
    {stops.map((mark) => <button type="button" data-stop={mark.value} disabled class="min-h-8 cursor-pointer rounded-md px-1.5 text-[0.8125rem]/5 text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75 disabled:cursor-default">{mark.label}</button>)}
  </div>
</div>
<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const input = root.querySelector<HTMLInputElement>("input[type=range]");
    const track = root.querySelector<HTMLElement>("[data-elastic-track]");
    const readout = root.querySelector<HTMLOutputElement>("[data-readout]");
    if (!input || !track || !readout) return;
    const reduced = matchMedia("(prefers-reduced-motion: reduce)");
    const stops = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-stop]"));
    let pointer: number | null = null;
    const sync = () => {
      readout.textContent = `${input.value}${root.dataset.unit || ""}`;
      input.setAttribute("aria-valuetext", readout.textContent);
      stops.forEach((button) => { button.disabled = input.disabled; button.setAttribute("aria-pressed", String(Number(button.dataset.stop) === input.valueAsNumber)); });
    };
    const release = () => { pointer = null; track.removeAttribute("data-dragging"); track.style.setProperty("--elastic-offset", "0px"); };
    input.addEventListener("pointerdown", (event) => { if (!input.disabled) { pointer = event.pointerId; track.setAttribute("data-dragging", ""); } });
    input.addEventListener("pointermove", (event) => {
      if (pointer !== event.pointerId || reduced.matches) return;
      const rect = input.getBoundingClientRect();
      const overflow = event.clientX < rect.left ? event.clientX - rect.left : event.clientX > rect.right ? event.clientX - rect.right : 0;
      track.style.setProperty("--elastic-offset", `${Math.sign(overflow) * Math.min(8, Math.sqrt(Math.abs(overflow)))}px`);
    });
    ["pointerup", "pointercancel", "lostpointercapture", "blur"].forEach((type) => input.addEventListener(type, release));
    input.addEventListener("input", sync);
    input.addEventListener("change", () => { release(); sync(); });
    stops.forEach((button) => button.addEventListener("click", () => { input.value = button.dataset.stop!; input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("change", { bubbles: true })); input.focus(); }));
    input.form?.addEventListener("reset", () => queueMicrotask(() => { release(); sync(); }));
    root.setAttribute("data-enhanced", "");
    sync();
  }
  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-elastic-slider]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-elastic-slider-listener")) {
    document.documentElement.setAttribute("data-haze-elastic-slider-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
