Moved to 40, committed at 40

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/slider.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
      })
    
  3. Import it

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

Usage

Basic.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.

Price$120 – $480

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.

0.7

Balanced.

Steps and marks

Five stops with a mark under each.

Vertical

Three keyed sliders with orientation: "vertical".

bass 70
mid 45
treble 60

Disabled

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

65%

Anatomy

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

PartDescription
rootAny element, role="group".
valueAn <output> for the current value.
controlA <div>, the area that takes pointer presses.
trackAny element inside the control.
indicatorAny element inside the track, the filled range.
thumbthumb({ element, input, index }): the element you see, with the <input type="range"> placed inside it.

API reference

Props

PropTypeDescription
valuenumber | number[]One number for one thumb, or one number per thumb.
min / maxnumber0 and 100 by default.
stepnumber1 by default. A drag lands on a multiple of it from min.
largeStepnumberWhat Shift with an arrow, PageUp and PageDown move by. 10 by default.
minStepsBetweenValuesnumberHow 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.
disabledbooleanDisables every input, and the slider emits nothing.

Events

EventDescription
MovedEach value the user moves to, during a drag and for each key.
CommittedThe value once the pointer is released, and after each key.

Data attributes

AttributeDescription
data-orientationhorizontal or vertical, on every part.
data-draggingA thumb is being dragged.
data-disabledThe slider is disabled.
data-indexOn a thumb, the value it shows.
--slider-thumb-positionOn a thumb, a percentage from the left, or from the bottom when vertical.
--slider-indicator-start / --slider-indicator-sizeOn the indicator, where the filled range starts and how long it is.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.