labs

elastic slider

2026-09-03

spending the overshoot

past either end the pull is resisted rather than ignored, and the overshoot is spent twice: the group stretches from the end that is not being pulled, and the track's control point leaves the centreline so the band bows under the thumb.

keeping the readout sharp

the readout rides inside that stretch and would be resampled with it, so it carries the inverse scale, which sounds like the card that expands in place and is a different problem: there the delta is measured once and the inverse is known before anything moves, here the scale changes every frame under a live gesture, so the inverse has to come out of the same frame.

the fill is the track's own curve cut at the thumb, because a second curve drawn near the first parts company with it the moment either bows.

take it with you

three steps, and the stage above runs in your own project.

  1. install

    nothing to add. it runs on react alone, 18 or newer.

  2. copy

    6 files, kept together in one folder, elastic-slider/. the styles travel with them.

    "use client";
    
    import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from "react";
    import { useReducedMotion } from "./motion";
    import { settled, step as stepSpring, type SpringState } from "./spring";
    import { counter, deformation, fillPath, overshootFor, splitAt, trackPath, valueAt } from "./elastic";
    import "./elastic-slider.css";
    
    interface Props {
      defaultValue?: number;
      min?: number;
      max?: number;
      step?: number;
      label?: string;
      // 0 to 1: how hard the pull past an end fights back, higher gives less
      resistance?: number;
      // how much the bar stretches for each px of overshoot
      stretch?: number;
      // px the track sags at full pull
      bow?: number;
      // fires on every step, which is where a tick sound or a haptic goes
      onChange?: (value: number) => void;
    }
    
    const HEIGHT = 44;
    const CY = HEIGHT / 2;
    
    const RETURN = { stiffness: 420, damping: 34 };
    
    export default function ElasticSlider({
      defaultValue = 62,
      min = 0,
      max = 100,
      step = 1,
      label = "value",
      resistance = 0.55,
      stretch = 0.9,
      bow = 22,
      onChange,
    }: Props) {
      const [value, setValue] = useState(defaultValue);
      const [width, setWidth] = useState(0);
      const reduced = useReducedMotion();
    
      const wrap = useRef<HTMLDivElement>(null);
      const group = useRef<HTMLDivElement>(null);
      const readout = useRef<HTMLSpanElement>(null);
      const track = useRef<SVGPathElement>(null);
      const fill = useRef<SVGPathElement>(null);
      const thumb = useRef<SVGCircleElement>(null);
    
      const overshoot = useRef(0);
      const dragging = useRef(false);
      const spring = useRef<SpringState>({ x: 0, v: 0 });
      const frame = useRef(0);
      const lastValue = useRef(value);
    
      useEffect(() => {
        const el = wrap.current;
        if (!el) return;
        const observer = new ResizeObserver(([entry]) => {
          setWidth(entry!.contentRect.width);
        });
        observer.observe(el);
        return () => observer.disconnect();
      }, []);
    
      const draw = useCallback(
        (next: number, over: number) => {
          if (width <= 0) return;
          const x = ((next - min) / (max - min)) * width;
          const sagMax = reduced ? 0 : bow;
          const pull = Math.min(1, Math.abs(over) / (width * 0.2));
          const sag = sagMax * pull * (over < 0 ? -1 : 1);
          const cx = Math.min(width, Math.max(0, x));
    
          track.current?.setAttribute("d", trackPath(width, CY, cx, sag));
          fill.current?.setAttribute("d", fillPath(width, CY, cx, sag, x));
          const { end } = splitAt(width, CY, cx, sag, x);
          thumb.current?.setAttribute("cx", String(end.x));
          thumb.current?.setAttribute("cy", String(end.y));
    
          const d = deformation(over, width, reduced ? 0 : stretch);
          const g = group.current;
          if (g) {
            g.style.transformOrigin = d.originX === 0 ? "left center" : "right center";
            g.style.transform = `scale(${d.scaleX}, ${d.scaleY})`;
          }
          const c = counter(d);
          if (readout.current) readout.current.style.transform = `scale(${c.scaleX}, ${c.scaleY})`;
        },
        [width, min, max, bow, stretch, reduced],
      );
    
      useEffect(() => {
        draw(value, overshoot.current);
      }, [draw, value]);
    
      const settle = useCallback(() => {
        cancelAnimationFrame(frame.current);
        if (reduced) {
          overshoot.current = 0;
          spring.current = { x: 0, v: 0 };
          draw(lastValue.current, 0);
          return;
        }
        spring.current = { x: overshoot.current, v: 0 };
        let previous = performance.now();
        const tick = (now: number) => {
          spring.current = stepSpring(spring.current, 0, now - previous, RETURN);
          previous = now;
          overshoot.current = spring.current.x;
          draw(lastValue.current, overshoot.current);
          if (settled(spring.current, 0)) {
            overshoot.current = 0;
            draw(lastValue.current, 0);
            return;
          }
          frame.current = requestAnimationFrame(tick);
        };
        frame.current = requestAnimationFrame(tick);
      }, [draw, reduced]);
    
      useEffect(() => () => cancelAnimationFrame(frame.current), []);
    
      const commit = useCallback(
        (next: number) => {
          if (next === lastValue.current) return;
          lastValue.current = next;
          setValue(next);
          onChange?.(next);
        },
        [onChange],
      );
    
      const move = (clientX: number) => {
        const rect = wrap.current?.getBoundingClientRect();
        if (!rect || rect.width <= 0) return;
        const x = clientX - rect.left;
        overshoot.current = overshootFor(x, rect.width, resistance);
        const next = valueAt(x, rect.width, min, max, step);
        if (next === lastValue.current) draw(next, overshoot.current);
        commit(next);
      };
    
      const onKeyDown = (event: KeyboardEvent) => {
        const by =
          event.key === "ArrowRight" || event.key === "ArrowUp"
            ? step
            : event.key === "ArrowLeft" || event.key === "ArrowDown"
              ? -step
              : 0;
        if (by !== 0) {
          event.preventDefault();
          commit(Math.min(max, Math.max(min, lastValue.current + by)));
          return;
        }
        if (event.key === "Home") {
          event.preventDefault();
          commit(min);
        }
        if (event.key === "End") {
          event.preventDefault();
          commit(max);
        }
      };
    
      return (
        <div
          className="es-wrap"
          ref={wrap}
          role="slider"
          tabIndex={0}
          aria-label={label}
          aria-valuemin={min}
          aria-valuemax={max}
          aria-valuenow={value}
          onKeyDown={onKeyDown}
          onPointerDown={(event) => {
            dragging.current = true;
            try {
              event.currentTarget.setPointerCapture(event.pointerId);
            } catch {}
            event.currentTarget.focus({ focusVisible: false });
            move(event.clientX);
          }}
          onPointerMove={(event) => {
            if (!dragging.current) return;
            move(event.clientX);
          }}
          onPointerUp={(event) => {
            dragging.current = false;
            if (event.currentTarget.hasPointerCapture(event.pointerId)) {
              event.currentTarget.releasePointerCapture(event.pointerId);
            }
            settle();
          }}
          onPointerCancel={() => {
            dragging.current = false;
            settle();
          }}
          onLostPointerCapture={() => {
            if (!dragging.current) return;
            dragging.current = false;
            settle();
          }}
        >
          <div className="es-group" ref={group}>
            <span className="es-label" ref={readout}>
              {value}
            </span>
            <svg
              className="es-svg"
              width={width || 1}
              height={HEIGHT}
              viewBox={`0 0 ${width || 1} ${HEIGHT}`}
              aria-hidden="true"
            >
              <path className="es-track" ref={track} />
              <path className="es-fill" ref={fill} />
              <circle className="es-thumb" ref={thumb} r="7" />
            </svg>
          </div>
        </div>
      );
    }
    
  3. use

    the stage above, exactly as it runs here. the comments mark what to change.

    example.tsx
    "use client";
    
    import { BURSTS, haptic, playBurst } from "./elastic-slider/feedback";
    import ElasticSlider from "./elastic-slider/ElasticSlider";
    
    export default function ElasticSliderExample({ sound = true }: { sound?: boolean }) {
      return (
        <div className="es-lab">
          <ElasticSlider
            defaultValue={62}
            label="gain"
            resistance={0.55}
            stretch={0.9}
            bow={22}
            onChange={(value) => {
              if (!sound) return;
              // a tick that gets louder as the value climbs; drop this to keep it silent
              playBurst({ ...BURSTS.tick, gain: 0.05 + (value / 100) * 0.5 });
              haptic("tick");
            }}
          />
          <p className="es-hint">drag past either end</p>
        </div>
      );
    }