Skip to content
Brok UI

Loading…

No results

Slider

Open source Core

Numeric range controls — a draggable track (single or two-thumb range, with discrete pips and scrubber variants), an angle dial, an exposure ticker, a media scrubber, or a springy elastic slider that stretches past its bounds.

Version
v1.1.2
Stability
stable
License
MIT
Related
Slider
Angle Slider
Exposure Slider
Scrubber
3 of 5

Elastic Slider — A springy range slider: drag the handle along the track and the whole control stretches elastically past either end, then springs back on release. End icons scale as the value nears them; fully keyboard-accessible with a live value readout.

Preview

50
previews.components.elastic-slider.default.blade.php Blade
<div class="flex min-h-40 w-full items-center justify-center rounded-lg border border-border bg-card p-8">
    <x-ui.elastic-slider class="w-full max-w-xs" :value="50" />
</div>

Installation

terminal
php artisan ui:add elastic-slider

Note

This component ships an Alpine behavior module at resources/js/ui/elastic-slider.js. Import it once from your bundle so it registers on alpine:init:

resources/js/ui/index.js JS
import './elastic-slider.js';

Registry contract

php artisan ui:add elastic-slider writes only the files below. The CLI validates each file hash before writing and asks before it replaces a local change, unless you pass --force.

  • blade resources/views/components/ui/elastic-slider.blade.php
  • js resources/js/ui/elastic-slider.js
Registry dependencies
None — installs on its own.
Packages
composer: jml/brok:^0.2
npm: alpinejs

Use with AI

A brief for your coding agent: install command, usage, props, guidance and the rules. Copy it, or open a prompt about this component in an assistant.

elastic-slider.md
# Brok UI: Elastic Slider (`elastic-slider`)

A springy range slider: drag the handle along the track and the whole control stretches elastically past either end, then springs back on release. End icons scale as the value nears them; fully keyboard-accessible with a live value readout.

Brok UI is a Laravel Blade component registry. Installed components are plain Blade files the app owns.

## Install

```bash
php artisan ui:add elastic-slider
```

## Usage

```blade
<div class="flex min-h-40 w-full items-center justify-center rounded-lg border border-border bg-card p-8">
    <x-ui.elastic-slider class="w-full max-w-xs" :value="50" />
</div>
```

## Props

- `name` (mixed|null, default `null`) — Renders a hidden input with this name for form posts.
- `min` (int, default `0`) — Minimum value.
- `max` (int, default `100`) — Maximum value.
- `value` (int, default `50`) — Current value.
- `step` (int, default `1`) — Keyboard step.
- `showValue` (bool, default `true`) — Shows a live numeric readout above the track.
- `label` (mixed|null, default `null`) — Accessible label for the thumb; defaults to "Value".

## Use when

- Use when continuous adjustment or immediate visual feedback helps users choose a value.
- Wanting a playful, springy drag feel on a single numeric value, with end icons that scale as the value nears them.
- Building a lightweight volume/brightness-style control with optional start/end icon slots.

## Avoid when

- Do not use for precise values or broad ranges without good landmarks; direct entry is better when accuracy matters.
- Wanting a plain, non-elastic drag feel or a two-thumb range; use slider instead.

## Anti-patterns

- Using sliders for precise or unbounded values

## Rules

- Use the `<brok:elastic-slider>` tag (or `<x-ui.elastic-slider>`) in Blade; do not rewrite the component.
- Prefer the documented props and variants over utility-class overrides; when a utility must win, use the `!` important modifier.
- Use semantic design tokens (`bg-primary`, `text-muted-foreground`), never raw colour utilities.
- Keep the `data-slot` attributes; they are the styling and test hooks.

## Links

- Docs: https://brokui.dev/docs/components/elastic-slider
- Registry JSON (files, props, contract): https://brokui.dev/r/open/elastic-slider.json

Working in Claude Code, Cursor or Codex? Give the agent the whole registry through the MCP server or the Brok UI skill.

API

manifest knowledge + registry-derived coverage

Props

Props accepted by this component: name, type, default value and description.
Prop Type Default Description
name mixed | null null Renders a hidden input with this name for form posts.
min int 0 Minimum value.
max int 100 Maximum value.
value int 50 Current value.
step int 1 Keyboard step.
showValue bool true Shows a live numeric readout above the track.
label mixed | null null Accessible label for the thumb; defaults to "Value".

Slots

  • default — Not used by this component; present for attribute-bag compatibility.
  • left — Custom start icon, replacing the default minus glyph.
  • right — Custom end icon, replacing the default plus glyph.

Data slots

Stable hooks for CSS overrides and browser tests.

elastic-slider elastic-slider-control elastic-slider-fill elastic-slider-icon-end elastic-slider-icon-start elastic-slider-thumb elastic-slider-track elastic-slider-wrapper

Behavior

  • Dragging the handle past either end of the track stretches the whole wrapper elastically (a JS-driven transform, no keyframes) and it springs back on release; arrow keys move the value by step.
  • The start and end icons scale subtly as the value approaches that end.
  • Installs a JavaScript behavior module when the registry item includes resources/js/ui files.
  • Declares registry capability flags: a11y, interactive, responsive, rtl, darkMode, localized.

Guidance

Continuous value control

Adjust an intuitive continuous value.

Use when

  • Use when continuous adjustment or immediate visual feedback helps users choose a value.
  • Wanting a playful, springy drag feel on a single numeric value, with end icons that scale as the value nears them.
  • Building a lightweight volume/brightness-style control with optional start/end icon slots.

Avoid when

  • Do not use for precise values or broad ranges without good landmarks; direct entry is better when accuracy matters.
  • Wanting a plain, non-elastic drag feel or a two-thumb range; use slider instead.

Use instead

  • Number field for precise entry
  • Select for discrete values

Anti-patterns

  • Using sliders for precise or unbounded values
Anatomy
root elastic-slider-wrapper elastic-slider-icon-start elastic-slider-control elastic-slider-track elastic-slider-fill elastic-slider-thumb elastic-slider-icon-end
Theming hooks
slider

Accessibility

WCAG 2.2 AA Keyboard focus-visible RTL-ready Localized labels Dark mode
Keyboard
ArrowUp ArrowDown ArrowLeft ArrowRight Home End PageUp PageDown
Focus
managed
  • The thumb is a role="slider" with aria-valuemin/max/now and the label prop as its accessible name, fully operable via onKey.
  • The spring-back transition is disabled while dragging and respects prefers-reduced-motion.
  • Semantic HTML and a stable data-slot attribute for styling and scripting hooks.
  • Focus-visible rings use the ring token, so keyboard focus is always visible.
  • Disabled and invalid states are conveyed to assistive tech, not by color alone.
  • Targets WCAG 2.2 AA; verify contrast in light, dark, admin and customer surfaces in the preview.
  • Labels go through __() and layout uses logical properties (ms-*, text-start), so it mirrors under dir="rtl" — flip the preview to RTL to confirm.
  • Dark mode uses the same semantic tokens under the dark class; high contrast follows forced-color system tokens.

Livewire

Needs wire:key

Add a stable wire:key when Livewire can reorder this interactive component.

livewire-component.blade.php Blade
<div wire:key="elastic-slider-{{ $record->id }}">
    <div class="flex min-h-40 w-full items-center justify-center rounded-lg border border-border bg-card p-8">
        <x-ui.elastic-slider class="w-full max-w-xs" :value="50" />
    </div>
</div>

Validation

Validation support: native. Keep the error message connected with aria-describedby.

livewire-form.blade.php Blade
<form wire:submit="save" class="space-y-2">
    <brok:elastic-slider
        wire:model="value"
        :aria-invalid="$errors->has('value') ? 'true' : 'false'"
        aria-describedby="value-error"
    />

    @error('value')
        <p id="value-error" role="alert">{{ $message }}</p>
    @enderror

    <brok:button type="submit" wire:loading.attr="disabled">
        <span wire:loading.remove>Save</span>
        <span wire:loading>Saving…</span>
    </brok:button>
</form>

Source

The exact, editable files ui:add writes into your app. Previews render this same code; there are no preview-only components.

resources/views/components/ui/elastic-slider.blade.php Blade
@props([
    'name' => null,
    'min' => 0,
    'max' => 100,
    'value' => 50,
    'step' => 1,
    'showValue' => true,
    'label' => null,
])

@php
    $styles = require base_path(config('ui.component_path', 'resources/views/components/ui').'/_styles.php');
    $recipe = $styles['slider'];
    $min = (int) $min;
    $max = (int) $max;
    $step = (int) $step;
    $value = max($min, min($max, (int) $value));
    $showValue = filter_var($showValue, FILTER_VALIDATE_BOOL);
    $ariaLabel = $label ? __($label) : __('Value');
@endphp

{{--
    Elastic Slider — a draggable, keyboard-accessible numeric control that stretches
    elastically while the pointer is dragged past either end of the track, then springs
    back on release (JS-driven `transform` on the wrapper, no keyframes). The fill and
    handle are positioned with the logical `inset-inline-start` so it mirrors under
    dir="rtl". End glyphs scale subtly as the value nears that end. Optional live value
    readout; an optional hidden input tracks the value for form posts.
--}}
<div
    data-slot="elastic-slider"
    x-data="uiElasticSlider({ min: @js($min), max: @js($max), value: @js($value), step: @js($step) })"
    {{-- Modelable: `x-model` (Alpine) and `wire:model` (Livewire binds through
         the same x-model contract) attach to the root. Inert without either. --}}
    x-modelable="value"
    {{ $attributes->merge(['class' => 'flex flex-col gap-2']) }}
>
    @if ($showValue)
        <output class="text-center text-sm font-medium tabular-nums text-foreground" x-text="value">{{ $value }}</output>
    @endif

    {{-- Wrapper that stretches elastically. The spring-back transition is disabled while dragging. --}}
    <div
        data-slot="elastic-slider-wrapper"
        class="flex items-center gap-3 transition-transform duration-300 ease-out will-change-transform motion-reduce:transition-none"
        :class="dragging ? 'transition-none' : ''"
        x-bind:style="wrapperTransform"
    >
        {{-- Start icon (smaller glyph) --}}
        <span
            data-slot="elastic-slider-icon-start"
            aria-hidden="true"
            class="shrink-0 text-muted-foreground transition-transform duration-200 ease-out motion-reduce:transition-none"
            x-bind:style="`transform: scale(${leftIconScale})`"
        >
            {{ $left ?? '' }}
            @if (! isset($left))
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/></svg>
            @endif
        </span>

        {{-- Track + fill + handle --}}
        <div
            data-slot="elastic-slider-control"
            @pointerdown="startDrag($event)"
            class="{{ $recipe['control'] }} w-full grow py-2"
        >
            <div
                x-ref="track"
                data-slot="elastic-slider-track"
                class="{{ $recipe['track'] }}"
            >
                <div
                    data-slot="elastic-slider-fill"
                    class="{{ $recipe['fill'] }}"
                    :style="`inset-inline-start: 0; width: ${percent(value)}%`"
                ></div>
            </div>

            <span
                data-slot="elastic-slider-thumb"
                role="slider"
                tabindex="0"
                aria-orientation="horizontal"
                :aria-valuemin="min"
                :aria-valuemax="max"
                :aria-valuenow="value"
                aria-label="{{ $ariaLabel }}"
                @keydown="onKey($event)"
                class="{{ $recipe['thumb'] }} {{ $recipe['thumbCentered'] }} {{ $recipe['thumbSizes']['md'] }}"
                x-bind:style="`inset-inline-start: ${percent(value)}%`"
            ></span>
        </div>

        {{-- End icon (larger glyph) --}}
        <span
            data-slot="elastic-slider-icon-end"
            aria-hidden="true"
            class="shrink-0 text-muted-foreground transition-transform duration-200 ease-out motion-reduce:transition-none"
            x-bind:style="`transform: scale(${rightIconScale})`"
        >
            {{ $right ?? '' }}
            @if (! isset($right))
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14"/><path d="M5 12h14"/></svg>
            @endif
        </span>
    </div>

    @if ($name)
        <input type="hidden" name="{{ $name }}" :value="value" />
    @endif
</div>
resources/js/ui/elastic-slider.js JS
/**
 * Elastic Slider behavior — an springy, elastic range slider.
 *
 * Holds one numeric `value`, clamped to [min, max] and snapped to `step`. The fill
 * and handle are positioned with the logical `inset-inline-start`, so the control
 * mirrors automatically under `dir="rtl"`; pointer and keyboard input account for
 * direction so dragging and arrow keys always feel correct.
 *
 * While dragging past either end of the track, the whole control stretches: a damped
 * overshoot (`sqrt(distancePastEnd) * k`) drives a `transform` (slight scaleX + a
 * translate toward the over-dragged side) on the wrapper. On release the overshoot is
 * cleared and a CSS `transition-transform` springs it back. The end icons scale up
 * subtly as the value approaches that end. Under
 * `prefers-reduced-motion: reduce` the elastic stretch is skipped (still functional).
 *
 * Pointer listeners are added to `document` only for the duration of a drag and are
 * always removed on pointerup AND in `destroy()`, so unmounting mid-drag can't leak.
 *
 * Self-registers on `alpine:init` so import order does not matter — import this
 * file once from your bundle (e.g. resources/js/ui/index.js).
 */
document.addEventListener('alpine:init', () => {
    window.Alpine.data('uiElasticSlider', (config = {}) => ({
        min: config.min ?? 0,
        max: config.max ?? 100,
        step: config.step ?? 1,
        value: config.value ?? 50,

        /** Live elastic overshoot in CSS pixels (signed: negative = past start). */
        overflow: 0,
        dragging: false,

        // Bound listener refs so we can remove exactly what we added.
        _move: null,
        _up: null,

        init() {
            this.value = this.clamp(this.value);
            this._move = (e) => this.onMove(e);
            this._up = () => this.endDrag();
        },

        destroy() {
            // Remove any listeners still attached if unmounted mid-drag.
            document.removeEventListener('pointermove', this._move);
            document.removeEventListener('pointerup', this._up);
        },

        get reduceMotion() {
            return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        },

        clamp(v) {
            v = Math.round(v / this.step) * this.step;
            v = Math.min(this.max, Math.max(this.min, v));
            const fromStep = String(this.step).split('.')[1]?.length ?? 0;
            return fromStep ? Number(v.toFixed(fromStep)) : v;
        },

        percent(v) {
            return this.max > this.min
                ? ((v - this.min) / (this.max - this.min)) * 100
                : 0;
        },

        /** 0 at start … 1 at end — drives the end-icon scaling. */
        get progress() {
            return this.percent(this.value) / 100;
        },

        /** Subtle scale for the end glyphs as the value nears that end. */
        get leftIconScale() {
            return 1 + (1 - this.progress) * 0.25;
        },
        get rightIconScale() {
            return 1 + this.progress * 0.25;
        },

        /**
         * Transform string for the wrapper. While dragging past an end we scale the
         * whole control up slightly and nudge it toward the over-dragged side, so it
         * reads as an elastic stretch that springs back when `overflow` returns to 0.
         */
        get wrapperTransform() {
            if (!this.overflow) return 'transform: scaleX(1) translateX(0)';
            const sign = this.overflow < 0 ? -1 : 1;
            const mag = Math.min(Math.abs(this.overflow), 64);
            const scale = 1 + mag / 800;
            const shift = sign * mag * 0.25;
            return `transform: scaleX(${scale.toFixed(4)}) translateX(${shift.toFixed(2)}px); transform-origin: ${sign < 0 ? '0% 50%' : '100% 50%'}`;
        },

        valueFromClientX(clientX) {
            const r = this.$refs.track.getBoundingClientRect();
            let ratio = (clientX - r.left) / r.width;
            if (getComputedStyle(this.$el).direction === 'rtl') ratio = 1 - ratio;
            return this.min + ratio * (this.max - this.min);
        },

        /** Signed distance (px) the pointer is past an end of the track, else 0. */
        overflowFromClientX(clientX) {
            const r = this.$refs.track.getBoundingClientRect();
            const rtl = getComputedStyle(this.$el).direction === 'rtl';
            let pastStart = r.left - clientX; // > 0 when left of the track
            let pastEnd = clientX - r.right; // > 0 when right of the track
            if (rtl) [pastStart, pastEnd] = [pastEnd, pastStart];
            const k = 0.9;
            if (pastStart > 0) return -Math.sqrt(pastStart) * k * 6;
            if (pastEnd > 0) return Math.sqrt(pastEnd) * k * 6;
            return 0;
        },

        startDrag(e) {
            e.preventDefault();
            this.dragging = true;
            this.apply(e.clientX);
            document.addEventListener('pointermove', this._move);
            document.addEventListener('pointerup', this._up);
        },

        onMove(e) {
            this.apply(e.clientX);
        },

        apply(clientX) {
            this.value = this.clamp(this.valueFromClientX(clientX));
            this.overflow = this.reduceMotion ? 0 : this.overflowFromClientX(clientX);
        },

        endDrag() {
            this.dragging = false;
            this.overflow = 0; // springs back via the CSS transition
            document.removeEventListener('pointermove', this._move);
            document.removeEventListener('pointerup', this._up);
        },

        onKey(e) {
            const big = Math.max(this.step, (this.max - this.min) / 10);
            switch (e.key) {
                case 'ArrowLeft':
                case 'ArrowDown':
                    e.preventDefault();
                    this.value = this.clamp(this.value - this.step);
                    break;
                case 'ArrowRight':
                case 'ArrowUp':
                    e.preventDefault();
                    this.value = this.clamp(this.value + this.step);
                    break;
                case 'PageDown':
                    e.preventDefault();
                    this.value = this.clamp(this.value - big);
                    break;
                case 'PageUp':
                    e.preventDefault();
                    this.value = this.clamp(this.value + big);
                    break;
                case 'Home':
                    e.preventDefault();
                    this.value = this.min;
                    break;
                case 'End':
                    e.preventDefault();
                    this.value = this.max;
                    break;
            }
        },
    }));
});

Ownership & lifecycle

Owner, release state, review evidence and adoption for this item.
Owner
Platform UI (@JoshJML)
Current version
1.1.2
Status
Stable
License
open
Accessibility reviewed
No review date recorded
Last breaking change
No date recorded
Deprecation
Not deprecated
Contract
v6
Foundation
≥ 1.0.0