# Slider

A controlled slider with one thumb or several, dragged or moved with the keyboard.

- Page: https://www.effectcn.com/components/slider
- Kind: Headless component with parts
- File: `src/ui/slider.ts`
- Built on: `Slider` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/slider.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/slider.ts`

```ts
import type { Component, View } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { Slider } from "@effect/ui-kit"
import { cn } from "#lib/cn"

/** What the kit's `Slider` hands its `view` closure. */
export type SliderParts = Component.Headless.Parts<typeof Slider>

interface ClassOption {
  readonly class?: string | undefined
}

/** The root: a column for a header and the control, or a row when vertical. */
export const SliderRoot = <Msg>(h: Html.H<Msg>, slider: SliderParts, options: ClassOption = {}) =>
  slider.root(
    h.div.class(cn(
      "flex w-full min-w-40 flex-col gap-2",
      "data-[orientation=vertical]:h-45 data-[orientation=vertical]:w-auto data-[orientation=vertical]:min-w-0 data-[orientation=vertical]:flex-row",
      options.class
    ))
  )

/** A row above the control for `SliderLabel` and `SliderValue`. */
export const SliderHeader = <Msg>(h: Html.H<Msg>, slider: SliderParts, options: ClassOption = {}) =>
  h.div
    .class(cn("flex items-baseline justify-between gap-3 data-[disabled]:opacity-50", options.class))
    .attr("data-disabled", slider.disabled ? "" : undefined)

/** A `<label>`. Point its `for` at the id of the thumb's input. */
export const SliderLabel = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.label.class(cn("text-[13px] font-medium", options.class))

/** The `<output>` that shows the value. */
export const SliderValue = <Msg>(h: Html.H<Msg>, slider: SliderParts, options: ClassOption = {}) =>
  slider.value(h.output.class(cn("text-xs text-muted-foreground tabular-nums", options.class)))

/** The area that takes presses, taller than the track it holds. */
export const SliderControl = <Msg>(h: Html.H<Msg>, slider: SliderParts, options: ClassOption = {}) =>
  slider.control(
    h.div.class(cn(
      "relative flex h-5 w-full cursor-pointer touch-none items-center px-2 select-none",
      "data-[orientation=vertical]:h-full data-[orientation=vertical]:w-5 data-[orientation=vertical]:flex-col data-[orientation=vertical]:px-0 data-[orientation=vertical]:py-2",
      "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
      options.class
    ))
  )

export const SliderTrack = <Msg>(h: Html.H<Msg>, slider: SliderParts, options: ClassOption = {}) =>
  slider.track(
    h.div.class(cn(
      "relative h-1 flex-1 rounded-full bg-foreground/12",
      "data-[orientation=vertical]:h-auto data-[orientation=vertical]:w-1",
      options.class
    ))
  )

/** The filled range, placed with the kit's `--slider-indicator-*` variables. */
export const SliderIndicator = <Msg>(h: Html.H<Msg>, slider: SliderParts, options: ClassOption = {}) =>
  slider.indicator(
    h.div.class(cn(
      "absolute inset-y-0 left-[var(--slider-indicator-start)] w-[var(--slider-indicator-size)] rounded-[inherit] bg-brand",
      "data-[orientation=vertical]:inset-x-0 data-[orientation=vertical]:top-auto data-[orientation=vertical]:bottom-[var(--slider-indicator-start)]",
      "data-[orientation=vertical]:h-[var(--slider-indicator-size)] data-[orientation=vertical]:w-auto",
      options.class
    ))
  )

/**
 * A thumb. `input` is the `<input>` that takes focus, the keys and the form
 * value: give it a `name` and an `aria-label`, or pass `field.control(h.input)`.
 * `index` picks the value it shows, and is required for a range.
 */
export const SliderThumb = <Msg, I extends View.PartTarget<"input">>(
  h: Html.H<Msg>,
  slider: SliderParts,
  options: ClassOption & { readonly input: I; readonly index?: number | undefined }
) =>
  slider.thumb({
    element: h.div.class(cn(
      "absolute top-1/2 left-[var(--slider-thumb-position)] size-4 -translate-1/2 rounded-full border-[1.5px] border-brand bg-background shadow-sm",
      "transition-shadow duration-150 hover:ring-4 hover:ring-brand/15 data-[dragging]:ring-4 data-[dragging]:ring-brand/15",
      "has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-ring",
      "data-[orientation=vertical]:top-auto data-[orientation=vertical]:bottom-[var(--slider-thumb-position)] data-[orientation=vertical]:left-1/2 data-[orientation=vertical]:translate-y-1/2",
      "data-[disabled]:ring-0",
      options.class
    )),
    input: options.input,
    index: options.index
  })
```

```ts
import { SliderRoot, SliderHeader, SliderLabel, SliderValue, SliderControl, SliderTrack, SliderIndicator, SliderThumb } from "#ui/slider"
```

## Usage

Moved reports every value on the way, and Committed the one the user left.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Slider } from "@effect/ui-kit"
import { Schema } from "effect"
import { SliderControl, SliderIndicator, SliderRoot, SliderThumb, SliderTrack } from "#ui/slider"

const SliderBasicMessage = UiSchema.TaggedEnum({
  MovedSlider: { value: Schema.Number },
  CommittedSlider: { value: Schema.Number }
})

export const SliderBasic = Html.component({
  name: "SliderBasic",
  model: Schema.Struct({ volume: Schema.Number, committed: Schema.Number }),
  message: SliderBasicMessage
}).make({
  init: () => ({ volume: 40, committed: 40 }),
  update: {
    MovedSlider: ($, { value }) => $.evolve({ volume: value }),
    CommittedSlider: ($, { value }) => $.evolve({ committed: value })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-4").children(
      Slider(h, {
        props: { value: model.volume },
        // The events carry a number because the value prop is one.
        onEmit: {
          Moved: ({ value }) =>
            typeof value === "number" ? SliderBasicMessage.MovedSlider({ value }) : undefined,
          Committed: ({ value }) =>
            typeof value === "number" ? SliderBasicMessage.CommittedSlider({ value }) : undefined
        },
        view: (slider) =>
          SliderRoot(h, slider).children(
            SliderControl(h, slider).children(
              SliderTrack(h, slider).children(
                SliderIndicator(h, slider),
                SliderThumb(h, slider, { input: h.input.attrs({ name: "volume", "aria-label": "Volume" }) })
              )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        `Moved to ${model.volume}, committed at ${model.committed}`
      )
    )
})
```

## Examples

### Range

An array value draws one thumb per number, kept a few steps apart.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Slider } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  SliderControl,
  SliderHeader,
  SliderIndicator,
  SliderRoot,
  SliderThumb,
  SliderTrack,
  SliderValue
} from "#ui/slider"

const SliderRangeMessage = UiSchema.TaggedEnum({
  MovedSlider: { values: Schema.Array(Schema.Number) }
})

const price = (value: number | undefined) => `$${value ?? 0}`

export const SliderRange = Html.component({
  name: "SliderRange",
  model: Schema.Struct({ price: Schema.Array(Schema.Number) }),
  message: SliderRangeMessage
}).make({
  init: () => ({ price: [120, 480] }),
  update: {
    MovedSlider: ($, { values }) => $.evolve({ price: values })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Slider(h, {
        props: { value: model.price, min: 0, max: 600, step: 10, minStepsBetweenValues: 4 },
        onEmit: {
          Moved: ({ value }) =>
            typeof value === "number" ? undefined : SliderRangeMessage.MovedSlider({ values: value }),
          Committed: () => undefined
        },
        view: (slider) =>
          SliderRoot(h, slider).attr("aria-label", "Price range").children(
            SliderHeader(h, slider).children(
              h.span.class("text-[13px] font-medium").children("Price"),
              SliderValue(h, slider).children(
                `${price(slider.values[0])} – ${price(slider.values[1])}`
              )
            ),
            SliderControl(h, slider).children(
              SliderTrack(h, slider).children(
                SliderIndicator(h, slider),
                // A thumb of a slider whose value is an array needs its index.
                SliderThumb(h, slider, {
                  input: h.input.attrs({ name: "min", "aria-label": "Minimum price" }),
                  index: 0
                }),
                SliderThumb(h, slider, {
                  input: h.input.attrs({ name: "max", "aria-label": "Maximum price" }),
                  index: 1
                })
              )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children("The thumbs stay at least $40 apart, and one pushes the other.")
    )
})
```

### With a label and value

A label for the thumb's input and an <output> for the value, with a fractional step.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Slider } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  SliderControl,
  SliderHeader,
  SliderIndicator,
  SliderLabel,
  SliderRoot,
  SliderThumb,
  SliderTrack,
  SliderValue
} from "#ui/slider"

const SliderWithValueMessage = UiSchema.TaggedEnum({ MovedSlider: { value: Schema.Number } })

export const SliderWithValue = Html.component({
  name: "SliderWithValue",
  model: Schema.Struct({ temperature: Schema.Number }),
  message: SliderWithValueMessage
}).make({
  init: () => ({ temperature: 0.7 }),
  update: {
    MovedSlider: ($, { value }) => $.evolve({ temperature: value })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Slider(h, {
        props: { value: model.temperature, min: 0, max: 2, step: 0.1, largeStep: 0.5 },
        onEmit: {
          Moved: ({ value }) =>
            typeof value === "number" ? SliderWithValueMessage.MovedSlider({ value }) : undefined,
          Committed: () => undefined
        },
        view: (slider) =>
          SliderRoot(h, slider).children(
            SliderHeader(h, slider).children(
              SliderLabel(h).attr("for", "slider-temperature").children("Temperature"),
              SliderValue(h, slider).children(model.temperature.toFixed(1))
            ),
            SliderControl(h, slider).children(
              SliderTrack(h, slider).children(
                SliderIndicator(h, slider),
                SliderThumb(h, slider, {
                  input: h.input.attrs({ id: "slider-temperature", name: "temperature" })
                })
              )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        model.temperature < 0.5
          ? "Focused and repeatable."
          : model.temperature < 1.3
          ? "Balanced."
          : "Varied and surprising."
      )
    )
})
```

### Steps and marks

Five stops with a mark under each.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Slider } from "@effect/ui-kit"
import { Schema } from "effect"
import { SliderControl, SliderIndicator, SliderRoot, SliderThumb, SliderTrack } from "#ui/slider"

const SliderStepsMessage = UiSchema.TaggedEnum({ MovedSlider: { value: Schema.Number } })

const sizes = [
  { value: 0, label: "XS" },
  { value: 1, label: "S" },
  { value: 2, label: "M" },
  { value: 3, label: "L" },
  { value: 4, label: "XL" }
]

export const SliderSteps = Html.component({
  name: "SliderSteps",
  model: Schema.Struct({ size: Schema.Number }),
  message: SliderStepsMessage
}).make({
  init: () => ({ size: 2 }),
  update: {
    MovedSlider: ($, { value }) => $.evolve({ size: value })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Slider(h, {
        props: { value: model.size, min: 0, max: 4, step: 1, largeStep: 2 },
        onEmit: {
          Moved: ({ value }) =>
            typeof value === "number" ? SliderStepsMessage.MovedSlider({ value }) : undefined,
          Committed: () => undefined
        },
        view: (slider) =>
          SliderRoot(h, slider).children(
            SliderControl(h, slider).children(
              SliderTrack(h, slider).children(
                SliderIndicator(h, slider),
                SliderThumb(h, slider, {
                  input: h.input.attrs({
                    name: "size",
                    "aria-label": "Size",
                    "aria-valuetext": sizes[model.size]?.label
                  })
                })
              )
            ),
            h.div.class("flex justify-between px-2").attr("aria-hidden", "true").children(
              sizes.map(({ label, value }) =>
                h.span.class(
                  "flex w-0 flex-col items-center gap-1 text-[11px] whitespace-nowrap text-muted-foreground tabular-nums before:h-1.5 before:w-px before:bg-input data-[active]:text-foreground"
                )
                  .attr("data-active", value === model.size ? "" : undefined)
                  .children(label)
              )
            )
          )
      })
    )
})
```

### Vertical

Three keyed sliders with orientation: "vertical".

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Slider } from "@effect/ui-kit"
import { Schema } from "effect"
import { SliderControl, SliderIndicator, SliderRoot, SliderThumb, SliderTrack } from "#ui/slider"

const bands = ["bass", "mid", "treble"] as const

const SliderVerticalMessage = UiSchema.TaggedEnum({
  MovedSlider: { band: Schema.Literals(bands), value: Schema.Number }
})

export const SliderVertical = Html.component({
  name: "SliderVertical",
  model: Schema.Struct({ bass: Schema.Number, mid: Schema.Number, treble: Schema.Number }),
  message: SliderVerticalMessage
}).make({
  init: () => ({ bass: 70, mid: 45, treble: 60 }),
  update: {
    MovedSlider: ($, { band, value }) => $.evolve({ [band]: value })
  },
  view: (h, model) =>
    h.div.class("flex items-center gap-7").children(
      bands.map((band) =>
        h.div.class("flex flex-col items-center gap-3.5").children(
          Slider(h, {
            key: band,
            props: { value: model[band], orientation: "vertical" },
            onEmit: {
              Moved: ({ value }) =>
                typeof value === "number" ? SliderVerticalMessage.MovedSlider({ band, value }) : undefined,
              Committed: () => undefined
            },
            view: (slider) =>
              SliderRoot(h, slider).children(
                SliderControl(h, slider).children(
                  SliderTrack(h, slider).children(
                    SliderIndicator(h, slider),
                    SliderThumb(h, slider, {
                      input: h.input.attrs({ name: band, "aria-label": band })
                    })
                  )
                )
              )
          }),
          h.span.class("text-xs text-muted-foreground tabular-nums").children(`${band} ${model[band]}`)
        )
      )
    )
})
```

### Disabled

A disabled slider takes no press and no key, and emits nothing.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Slider } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import {
  SliderControl,
  SliderHeader,
  SliderIndicator,
  SliderLabel,
  SliderRoot,
  SliderThumb,
  SliderTrack,
  SliderValue
} from "#ui/slider"

const SliderDisabledMessage = UiSchema.TaggedEnum({
  MovedSlider: { value: Schema.Number },
  PressedAutomatic: {}
})

export const SliderDisabled = Html.component({
  name: "SliderDisabled",
  model: Schema.Struct({ brightness: Schema.Number, automatic: Schema.Boolean }),
  message: SliderDisabledMessage
}).make({
  init: () => ({ brightness: 65, automatic: true }),
  update: {
    MovedSlider: ($, { value }) => $.evolve({ brightness: value }),
    PressedAutomatic: ($) => $.evolve({ automatic: (automatic) => !automatic })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Slider(h, {
        props: { value: model.brightness, disabled: model.automatic },
        onEmit: {
          Moved: ({ value }) =>
            typeof value === "number" ? SliderDisabledMessage.MovedSlider({ value }) : undefined,
          Committed: () => undefined
        },
        view: (slider) =>
          SliderRoot(h, slider).children(
            SliderHeader(h, slider).children(
              SliderLabel(h).attr("for", "slider-brightness").children("Brightness"),
              SliderValue(h, slider).children(`${model.brightness}%`)
            ),
            SliderControl(h, slider).children(
              SliderTrack(h, slider).children(
                SliderIndicator(h, slider),
                SliderThumb(h, slider, {
                  input: h.input.attrs({ id: "slider-brightness", name: "brightness" })
                })
              )
            )
          )
      }),
      h.div.children(
        Button(h, { variant: "outline", size: "sm", onPress: SliderDisabledMessage.PressedAutomatic() })
          .children(model.automatic ? "Adjust manually" : "Set automatically")
      )
    )
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `root` | Any element, role="group". |
| `value` | An <output> for the current value. |
| `control` | A <div>, the area that takes pointer presses. |
| `track` | Any element inside the control. |
| `indicator` | Any element inside the track, the filled range. |
| `thumb` | thumb({ element, input, index }): the element you see, with the <input type="range"> placed inside it. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `value` | `number \| number[]` | One number for one thumb, or one number per thumb. |
| `min / max` | `number` | 0 and 100 by default. |
| `step` | `number` | 1 by default. A drag lands on a multiple of it from min. |
| `largeStep` | `number` | What Shift with an arrow, PageUp and PageDown move by. 10 by default. |
| `minStepsBetweenValues` | `number` | How many steps apart two thumbs stay. |
| `orientation` | `"horizontal" \| "vertical"` | "horizontal" by default. |
| `thumbCollisionBehavior` | `"push" \| "swap" \| "none"` | What a thumb dragged into another does. "push" by default. |
| `disabled` | `boolean` | Disables every input, and the slider emits nothing. |

### Events

| Event | Description |
| --- | --- |
| `Moved` | Each value the user moves to, during a drag and for each key. |
| `Committed` | The value once the pointer is released, and after each key. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-orientation` | horizontal or vertical, on every part. |
| `data-dragging` | A thumb is being dragged. |
| `data-disabled` | The slider is disabled. |
| `data-index` | On a thumb, the value it shows. |
| `--slider-thumb-position` | On a thumb, a percentage from the left, or from the bottom when vertical. |
| `--slider-indicator-start / --slider-indicator-size` | On the indicator, where the filled range starts and how long it is. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
