Components

Slider

A value on a range: a 4px #363636 track, White up to the value, and a White thumb with the small corner. It follows the hand without easing.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add slider
<script type="module" src="/spyglass-ds/elements/slider.js"></script>
As a filter

Running for at least

30 days

Ads that run longer are the ones that work.

States

Usage

A rough value where the range matters more than the digit: how long an ad has run, a share, a budget. Show the value beside it.

Never

  • Exact values a person would rather type: use Input
  • A round, glowing or growing thumb
  • Animating the thumb: it follows the hand

Props

The web component takes the same as attributes or properties (<spyglass-slider>); title is heading there.

<Slider>

PropTypeDefault
labelstring

The name for assistive tech.

minnumber0
maxnumber100
stepnumber1
disabledboolean
valueTextstring

What a screen reader says for the value ("$40 a day" for 40).

valuenumber
defaultValuenumber0
onValueChange(value: number) => void
classNamestring

Examples

The same example in React and as web components; both render identically.

react/examples/slider/Filter.tsx
'use client'
import { useState } from 'react'
import { Slider } from '@/react/components/ui/Slider'
// A filter over a search: only ads that have run at least this many days, the count beside it.

export default function Filter() {
  const [days, setDays] = useState(30)
  return (
    <div className="flex w-96 max-w-full flex-col gap-2">
      <div className="flex items-baseline justify-between gap-4">
        <p className="type-label text-fg-soft">Running for at least</p>
        <p className="type-ui text-fg tabular-nums">{days} days</p>
      </div>
      <Slider label="Running for at least" min={0} max={90} value={days} onValueChange={setDays} valueText={`${days} days`} />
      <p className="type-caption text-fg-muted">Ads that run longer are the ones that work.</p>
    </div>
  )
}
elements/examples/slider/Filter.html
<!-- A filter over a search: only ads that have run at least this many days, the count beside it. -->
<div class="flex w-96 max-w-full flex-col gap-2">
  <div class="flex items-baseline justify-between gap-4">
    <p class="type-label text-fg-soft">Running for at least</p>
    <p id="slider-days" class="type-ui text-fg tabular-nums">30 days</p>
  </div>
  <spyglass-slider id="slider-filter" label="Running for at least" min="0" max="90" value="30" value-text="30 days"></spyglass-slider>
  <p class="type-caption text-fg-muted">Ads that run longer are the ones that work.</p>
</div>
<script type="module">
  const slider = document.getElementById('slider-filter')
  const out = document.getElementById('slider-days')
  slider.addEventListener('input', () => {
    out.textContent = `${slider.value} days`
    slider.valueText = `${slider.value} days`
  })
</script>
react/examples/slider/States.tsx
import { Slider } from '@/react/components/ui/Slider'
// The range's ends and middle, and one that can't be changed.

export default function States() {
  return (
    <div className="flex w-80 max-w-full flex-col gap-4">
      <Slider label="Share of video ads" defaultValue={0} />
      <Slider label="Share of image ads" defaultValue={50} />
      <Slider label="Share of new creatives" defaultValue={100} />
      <Slider label="Locked share" defaultValue={40} disabled />
    </div>
  )
}
elements/examples/slider/States.html
<!-- The range's ends and middle, and one that can't be changed. -->
<div class="flex w-80 max-w-full flex-col gap-4">
  <spyglass-slider label="Share of video ads" value="0"></spyglass-slider>
  <spyglass-slider label="Share of image ads" value="50"></spyglass-slider>
  <spyglass-slider label="Share of new creatives" value="100"></spyglass-slider>
  <spyglass-slider label="Locked share" value="40" disabled></spyglass-slider>
</div>

Source

react/components/ui/Slider.tsx
'use client'
import type { CSSProperties } from 'react'
import { useControllable } from '@/react/hooks/useControllable'

// A value on a range: a 4px #363636 track, White up to the value, and a 16px White thumb with the small corner, the
// White focus ring around it. It follows the pointer with no easing, since the hand is moving it; arrows step it, Page
// Up and Down by tens, Home and End to the ends. The whole 32px row takes the pointer (44px on phones). Show the value
// beside it in tabular figures. `value` with `onValueChange` controls it (or `defaultValue` alone).
export interface SliderProps {
  /** The name for assistive tech. */
  label: string
  min?: number
  max?: number
  step?: number
  disabled?: boolean
  /** What a screen reader says for the value ("$40 a day" for 40). */
  valueText?: string
  value?: number
  defaultValue?: number
  onValueChange?: (value: number) => void
  className?: string
}

export function Slider({ label, min = 0, max = 100, step = 1, disabled, valueText, value, defaultValue = 0, onValueChange, className }: SliderProps) {
  const [current, setCurrent] = useControllable(value, defaultValue, onValueChange)
  const share = max > min ? ((current - min) / (max - min)) * 100 : 0
  return (
    <>
      <style href="ds-slider" precedence="ds">{css}</style>
      <span data-ds="slider" className={className ? `ds-slider ${className}` : 'ds-slider'} style={{ '--p': `${share}%` } as CSSProperties} data-disabled={disabled || undefined}>
        <span className="ds-slider-track" aria-hidden="true"><span /></span>
        <input type="range" value={current} onChange={e => setCurrent(Number(e.target.value))} min={min} max={max} step={step} disabled={disabled} aria-label={label} aria-valuetext={valueText} />
      </span>
    </>
  )
}

export default Slider

const css = `
.ds-slider { position: relative; display: flex; width: 100%; height: var(--ds-size-control-sm); align-items: center; }
.ds-slider-track { position: absolute; right: 0; left: 0; height: var(--ds-space-xs); overflow: hidden; border-radius: var(--ds-radius-sm); background: var(--ds-color-edge-strong); pointer-events: none; }
.ds-slider-track > span { display: block; width: var(--p); height: 100%; background: var(--ds-color-action-primary); }
.ds-slider[data-disabled] .ds-slider-track > span { background: var(--ds-color-action-disabled-fg); }
.ds-slider > input { position: relative; width: 100%; height: 100%; margin: 0; background: transparent; appearance: none; cursor: pointer; }
.ds-slider > input:disabled { cursor: not-allowed; }
.ds-slider > input:focus-visible { outline: none; }
.ds-slider > input::-webkit-slider-runnable-track { height: var(--ds-space-xs); background: transparent; }
.ds-slider > input::-moz-range-track { height: var(--ds-space-xs); background: transparent; }
.ds-slider > input::-webkit-slider-thumb { width: var(--ds-size-icon-sm); height: var(--ds-size-icon-sm); margin-top: calc((var(--ds-space-xs) - var(--ds-size-icon-sm)) / 2); border: 0; border-radius: var(--ds-radius-sm); background: var(--ds-color-action-primary); appearance: none; }
.ds-slider > input::-moz-range-thumb { width: var(--ds-size-icon-sm); height: var(--ds-size-icon-sm); border: 0; border-radius: var(--ds-radius-sm); background: var(--ds-color-action-primary); }
.ds-slider > input:disabled::-webkit-slider-thumb { background: var(--ds-color-action-disabled-fg); }
.ds-slider > input:disabled::-moz-range-thumb { background: var(--ds-color-action-disabled-fg); }
.ds-slider > input:focus-visible::-webkit-slider-thumb { outline: var(--ds-border-focus) solid var(--ds-color-edge-focus); outline-offset: var(--ds-border-focus); }
.ds-slider > input:focus-visible::-moz-range-thumb { outline: var(--ds-border-focus) solid var(--ds-color-edge-focus); outline-offset: var(--ds-border-focus); }
@media (pointer: coarse), (max-width: 767px) { .ds-slider { height: var(--ds-size-control-touch); } }
`
react/hooks/useControllable.ts
'use client'
import { useCallback, useRef, useState } from 'react'

// Vue's defineModel in React: a value that is controlled when the caller passes it (value + onValueChange, as Radix
// does) and kept inside otherwise (defaultValue). setValue calls onChange either way.
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
	const [inner, setInner] = useState<T>(defaultValue)
	const controlled = value !== undefined
	const current = controlled ? value : inner
	const ref = useRef(onChange)
	ref.current = onChange
	const set = useCallback((next: T) => {
		if (!controlled) setInner(next)
		ref.current?.(next)
	}, [controlled])
	return [current, set] as const
}
elements/components/ui/slider.ts
import { html, LitElement, type PropertyValues } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { live } from 'lit/directives/live.js'
import { styleMap } from 'lit/directives/style-map.js'
import { DsFormElement, define } from '@/elements/lib/element'
import styles from 'virtual:tw'

// Slider.tsx as <spyglass-slider>: a value on a range: a 4px #363636 track, White up to the value, and a 16px White
// thumb with the small corner. It follows the pointer with no easing; arrows step it, Page Up and Down by tens, Home and
// End to the ends. The value is a numeric `value` with `input` (while it moves) and `change` (when it is let go), as a
// native range's. Form-associated: its `name` goes with the form.

/**
 * @summary A value on a range.
 * @fires input - While it moves (read `value`).
 * @fires change - When it is let go (read `value`).
 */
export class Slider extends DsFormElement {
	static styles = [DsFormElement.styles, styles]
	static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }
	static dsField = true
	static properties = {
		value: { type: Number },
		label: {},
		min: { type: Number },
		max: { type: Number },
		step: { type: Number },
		disabled: { type: Boolean, reflect: true },
		valueText: { attribute: 'value-text' },
		name: {},
	}

	value = 0
	/** The name for assistive tech. */
	label = ''
	min = 0
	max = 100
	step = 1
	disabled = false
	/** What a screen reader says for the value ("$40 a day" for 40). */
	valueText?: string
	name?: string

	protected updated(changed: PropertyValues) {
		super.updated(changed)
		if (changed.has('value')) this.internals.setFormValue(String(this.value))
	}
	protected validityControl() {
		return this.renderRoot.querySelector<HTMLInputElement>('input')
	}
	formResetCallback() {
		this.value = Number(this.getAttribute('value') ?? 0)
	}
	private onInput(event: Event) {
		this.value = Number((event.target as HTMLInputElement).value)
	}
	// The inner change does not leave the shadow root: the element sends its own.
	private onChange() {
		this.dispatchEvent(new Event('change', { bubbles: true, composed: true }))
	}

	render() {
		const share = this.max > this.min ? ((this.value - this.min) / (this.max - this.min)) * 100 : 0
		return html`<span data-ds="slider" class="ds-slider" style=${styleMap({ '--p': `${share}%` })} data-disabled=${ifDefined(this.inactive ? 'true' : undefined)}>
			<span class="ds-slider-track" aria-hidden="true"><span></span></span>
			<input type="range" min=${this.min} max=${this.max} step=${this.step} .value=${live(String(this.value))} ?disabled=${this.inactive} aria-label=${this.label} aria-valuetext=${ifDefined(this.valueText)} @input=${this.onInput} @change=${this.onChange}>
		</span>`
	}
}

define('slider', Slider)
elements/components/ui/slider.css
/* Slider.tsx's styles, as they are. */
.ds-slider { position: relative; display: flex; width: 100%; height: var(--ds-size-control-sm); align-items: center; }
.ds-slider-track { position: absolute; right: 0; left: 0; height: var(--ds-space-xs); overflow: hidden; border-radius: var(--ds-radius-sm); background: var(--ds-color-edge-strong); pointer-events: none; }
.ds-slider-track > span { display: block; width: var(--p); height: 100%; background: var(--ds-color-action-primary); }
.ds-slider[data-disabled] .ds-slider-track > span { background: var(--ds-color-action-disabled-fg); }
.ds-slider > input { position: relative; width: 100%; height: 100%; margin: 0; background: transparent; appearance: none; cursor: pointer; }
.ds-slider > input:disabled { cursor: not-allowed; }
.ds-slider > input:focus-visible { outline: none; }
.ds-slider > input::-webkit-slider-runnable-track { height: var(--ds-space-xs); background: transparent; }
.ds-slider > input::-moz-range-track { height: var(--ds-space-xs); background: transparent; }
.ds-slider > input::-webkit-slider-thumb { width: var(--ds-size-icon-sm); height: var(--ds-size-icon-sm); margin-top: calc((var(--ds-space-xs) - var(--ds-size-icon-sm)) / 2); border: 0; border-radius: var(--ds-radius-sm); background: var(--ds-color-action-primary); appearance: none; }
.ds-slider > input::-moz-range-thumb { width: var(--ds-size-icon-sm); height: var(--ds-size-icon-sm); border: 0; border-radius: var(--ds-radius-sm); background: var(--ds-color-action-primary); }
.ds-slider > input:disabled::-webkit-slider-thumb { background: var(--ds-color-action-disabled-fg); }
.ds-slider > input:disabled::-moz-range-thumb { background: var(--ds-color-action-disabled-fg); }
.ds-slider > input:focus-visible::-webkit-slider-thumb { outline: var(--ds-border-focus) solid var(--ds-color-edge-focus); outline-offset: var(--ds-border-focus); }
.ds-slider > input:focus-visible::-moz-range-thumb { outline: var(--ds-border-focus) solid var(--ds-color-edge-focus); outline-offset: var(--ds-border-focus); }
@media (pointer: coarse), (max-width: 767px) { .ds-slider { height: var(--ds-size-control-touch); } }

Reference: Derived from the brand guidelines (no slider in the brand assets): White for the filled part, the neutral steps for the track, the small corner.