Try 'magnetic button'
View code

Number 94: Price range over the prices it filters

Specification

Catalogue
No. 94 of 110
Interaction
Drag
Element
Input, Chart, Picker
Preview
Live component
Imports
react 19.3.1, @number-flow/react 0.6.2, framer-motion 12.40.0
Added

Notes

A two-thumb price range drawn over a histogram of the prices it filters. Bars inside the range are dark, bars outside are pale, and a line below says how many results the range holds.

A shopper or a holiday-let guest sees where the prices actually are before choosing, and the count tells them the effect of every move. It filters a list, where the estimate slider prices one quantity.

The thumbs follow the pointer one to one and never cross. Past either end they stretch at most 10px ((1 - 1 / (d x 0.55 / 10 + 1)) x 10). On release a thumb carries its momentum at most one bar further (velocity x 0.099), then settles on the nearest bar edge within 9px, so a range never cuts a bar in half; the settle is a 0.2s spring with no bounce. One clip cuts both the dark bars and the track fill at the thumbs on the same frame. A press anywhere on the bars springs the nearest thumb there, and a held thumb grows to 1.18. Each thumb is a slider: arrows step £5, Shift with an arrow or Page Up and Page Down move one bar, Home and End go to the limit. Visible thumbs are 22px inside 44px targets. The count rolls with NumberFlow. Instant under reduced motion.

The prices are sample content; a client build counts the client's own listings.

Code

React and plain CSS
"use client";

import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from "react";
import { animate, motion, useMotionValue, useTransform, type MotionValue } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { physicalSpring } from "@/components/pieces/kit/physical-spring";
import { tourDrag, tourTap } from "@/components/pieces/kit/tour-drag";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { layoutScale } from "@/components/pieces/motion-helpers";
import { Num } from "@/components/pieces/shared";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./price-histogram.css";

const MIN = 40;
const MAX = 400;
const STEP = 5;
const BINS = 24;
const BIN = (MAX - MIN) / BINS;
const SETTLE = physicalSpring(0.2);
/** Rubber band past either end, at most 10px; a release settles on a bar edge within 9px. */
const STRETCH = 10;
const SNAP_PX = 9;
const rubber = (d: number) => Math.sign(d) * (1 - 1 / ((Math.abs(d) * 0.55) / STRETCH + 1)) * STRETCH;
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
const pct = (v: number) => ((v - MIN) / (MAX - MIN)) * 100;
const valueAt = (p: number) => MIN + (p / 100) * (MAX - MIN);
const snap = (v: number) => MIN + Math.round((v - MIN) / STEP) * STEP;
const money = (v: number) => `£${v}`;

/** 480 nightly prices for sample holiday lets: most between £80 and £180, a long tail above. Seeded, so every render agrees. */
function samplePrices(): number[] {
  let seed = 7;
  const rand = () => {
    seed = (seed * 16807) % 2147483647;
    return seed / 2147483647;
  };
  return Array.from({ length: 480 }, (_, i) => {
    const gauss = (rand() + rand() + rand() + rand() - 2) * 0.9;
    const p = i % 5 === 0 ? 170 + rand() ** 1.6 * 225 : 125 + gauss * 55;
    return Math.round(clamp(p, MIN, MAX));
  });
}

type Drag = { index: 0 | 1; grab: number; raw: number; samples: { t: number; p: number }[] };

function PriceHistogramDemo() {
  const reduce = useSafeReducedMotion();
  const uid = useId();
  const prices = useMemo(samplePrices, []);
  const counts = useMemo(() => {
    const c = new Array<number>(BINS).fill(0);
    for (const p of prices) c[Math.min(BINS - 1, Math.floor((p - MIN) / BIN))]! += 1;
    return c;
  }, [prices]);
  const tallest = Math.max(...counts);
  const [vals, setVals] = useState<[number, number]>([70, 205]);
  const latest = useRef(vals);
  const [held, setHeld] = useState<0 | 1 | null>(null);
  const area = useRef<HTMLDivElement>(null);
  const drag = useRef<Drag | null>(null);
  const detach = useRef<(() => void) | null>(null);

  const pos0 = useMotionValue(pct(vals[0]));
  const pos1 = useMotionValue(pct(vals[1]));
  const pos: [MotionValue<number>, MotionValue<number>] = [pos0, pos1];
  // One clip reveals the dark copy of the bars and the track fill, so both cut at the thumbs on the same frame.
  const clip = useTransform(() => `inset(0 ${(100 - clamp(pos1.get(), 0, 100)).toFixed(3)}% 0 ${clamp(pos0.get(), 0, 100).toFixed(3)}%)`);
  const left0 = useTransform(pos0, (v) => `${v}%`);
  const left1 = useTransform(pos1, (v) => `${v}%`);

  useEffect(() => () => detach.current?.(), []);

  const lowOf = (i: 0 | 1, cur: [number, number]) => (i === 1 ? cur[0] + STEP : MIN);
  const highOf = (i: 0 | 1, cur: [number, number]) => (i === 0 ? cur[1] - STEP : MAX);
  const settleValue = (i: 0 | 1, v: number, cur: [number, number]) => clamp(snap(clamp(v, MIN, MAX)), lowOf(i, cur), highOf(i, cur));

  const commit = (i: 0 | 1, v: number) => {
    const cur = latest.current;
    if (cur[i] === v) return;
    const next: [number, number] = i === 0 ? [v, cur[1]] : [cur[0], v];
    latest.current = next;
    setVals(next);
  };
  const glideTo = (i: 0 | 1, v: number) => {
    commit(i, v);
    if (reduce) pos[i].jump(pct(v));
    else animate(pos[i], pct(v), SETTLE);
  };

  const geometry = () => {
    const el = area.current;
    if (!el) return null;
    const r = el.getBoundingClientRect();
    return { left: r.left, width: r.width || 1, layoutWidth: (r.width || 1) / layoutScale(el) };
  };

  const onDown = (e: ReactPointerEvent<HTMLDivElement>) => {
    if (e.button !== 0 || !e.isPrimary) return;
    const g = geometry();
    if (!g) return;
    e.preventDefault();
    const at = ((e.clientX - g.left) / g.width) * 100;
    const cur = latest.current;
    const grabbed = (e.target as HTMLElement).closest<HTMLElement>("[data-thumb]");
    const index: 0 | 1 = grabbed ? (Number(grabbed.dataset.thumb) as 0 | 1) : Math.abs(at - pct(cur[0])) <= Math.abs(at - pct(cur[1])) ? 0 : 1;
    pos[index].stop();
    const state: Drag = { index, grab: grabbed ? at - pos[index].get() : 0, raw: at, samples: [{ t: e.timeStamp, p: pos[index].get() }] };
    drag.current = state;
    setHeld(index);
    area.current?.querySelector<HTMLElement>(`[data-thumb="${index}"]`)?.focus({ preventScroll: true });
    // A press on the bars springs the nearest thumb there.
    if (!grabbed) glideTo(index, settleValue(index, valueAt(at), cur));

    const move = (ev: PointerEvent) => {
      const s = drag.current;
      const gg = geometry();
      if (!s || !gg) return;
      const raw = ((ev.clientX - gg.left) / gg.width) * 100 - s.grab;
      const c = latest.current;
      const edge = clamp(raw, pct(lowOf(s.index, c)), pct(highOf(s.index, c)));
      const over = ((raw - edge) / 100) * gg.layoutWidth;
      const placed = reduce ? edge : edge + (rubber(over) / gg.layoutWidth) * 100;
      pos[s.index].stop();
      pos[s.index].set(placed);
      s.raw = raw;
      s.samples.push({ t: ev.timeStamp, p: placed });
      if (s.samples.length > 6) s.samples.shift();
      commit(s.index, settleValue(s.index, valueAt(raw), c));
    };
    const up = (ev: PointerEvent) => {
      const s = drag.current;
      const gg = geometry();
      stop();
      if (!s || !gg) return;
      const first = s.samples[0]!;
      const last = s.samples[s.samples.length - 1]!;
      const secs = (last.t - first.t) / 1000;
      const velocity = secs > 0.008 && ev.timeStamp - last.t < 60 ? (last.p - first.p) / secs : 0;
      // Momentum carries the thumb at most one bar further; then a bar edge within 9px claims it.
      const binPct = 100 / BINS;
      const landing = clamp(s.raw + clamp(velocity * 0.099, -binPct, binPct), 0, 100);
      let target = valueAt(landing);
      const edgeValue = MIN + Math.round((target - MIN) / BIN) * BIN;
      if ((Math.abs(pct(edgeValue) - landing) / 100) * gg.layoutWidth <= SNAP_PX) target = edgeValue;
      glideTo(s.index, settleValue(s.index, target, latest.current));
    };
    const stop = () => {
      drag.current = null;
      setHeld(null);
      window.removeEventListener("pointermove", move);
      window.removeEventListener("pointerup", up);
      window.removeEventListener("pointercancel", up);
      detach.current = null;
    };
    detach.current?.();
    window.addEventListener("pointermove", move);
    window.addEventListener("pointerup", up);
    window.addEventListener("pointercancel", up);
    detach.current = stop;
  };

  const onKey = (i: 0 | 1) => (e: KeyboardEvent<HTMLSpanElement>) => {
    const cur = latest.current;
    const big = e.shiftKey || e.key === "PageUp" || e.key === "PageDown";
    const dir = e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "PageUp" ? 1 : e.key === "ArrowLeft" || e.key === "ArrowDown" || e.key === "PageDown" ? -1 : 0;
    let next: number | null = null;
    if (dir) next = cur[i] + dir * (big ? BIN : STEP);
    else if (e.key === "Home") next = lowOf(i, cur);
    else if (e.key === "End") next = highOf(i, cur);
    if (next === null) return;
    e.preventDefault();
    glideTo(i, settleValue(i, next, cur));
  };

  const inRange = prices.filter((p) => p >= vals[0] && p <= vals[1]).length;
  const bars = (lit: boolean) => (
    <div className="ph-bars" data-lit={lit || undefined} aria-hidden="true">
      {counts.map((c, i) => (
        <span key={i} style={{ height: `${Math.max(2, (c / tallest) * 100)}%` }} />
      ))}
    </div>
  );

  return (
    <div className="ph">
      <div className="ph-head">
        <span id={`${uid}-l`} className="ph-label">
          Price per night
        </span>
        <span className="ph-readout" aria-hidden="true">
          {money(vals[0])} to {money(vals[1])}
          {vals[1] === MAX ? "+" : ""}
        </span>
      </div>
      <div ref={area} className="ph-area" onPointerDown={onDown}>
        <div className="ph-plot">
          {bars(false)}
          <motion.div className="ph-lit" style={{ clipPath: clip }}>
            {bars(true)}
          </motion.div>
        </div>
        <div className="ph-track" aria-hidden="true">
          <motion.span className="ph-fill" style={{ clipPath: clip }} />
        </div>
        {([0, 1] as const).map((i) => (
          <motion.span
            key={i}
            className="ph-thumb"
            data-thumb={i}
            data-held={held === i || undefined}
            role="slider"
            tabIndex={0}
            aria-labelledby={`${uid}-l ${uid}-t${i}`}
            aria-valuemin={lowOf(i, vals)}
            aria-valuemax={highOf(i, vals)}
            aria-valuenow={vals[i]}
            aria-valuetext={money(vals[i])}
            style={{ left: i === 0 ? left0 : left1 }}
            onKeyDown={onKey(i)}
          >
            <span id={`${uid}-t${i}`} className="sr-only">
              {i === 0 ? "minimum" : "maximum"}
            </span>
          </motion.span>
        ))}
      </div>
      <p className="ph-count" aria-live="polite">
        <span className="ph-num">
          <Num value={inRange} />
        </span>{" "}
        of {prices.length} stays in this range
      </p>
    </div>
  );
}

// What a hovered card shows: the upper thumb dragged down, then a press near the low end pulls the lower thumb there.
const TOUR: Tour = [
  { run: (root) => {
      const thumb = root.querySelector(".ph-thumb[data-thumb='1']");
      const box = root.querySelector(".ph-area");
      if (thumb && box) tourDrag(thumb, [0.47, 0.83], [0.6, 0.83], 900, { box });
    }, wait: 1500 },
  { run: (root) => {
      const box = root.querySelector(".ph-plot");
      if (box) tourTap(box, [0.1, 0.6]);
    }, wait: 1400 },
];

export default function PriceHistogramEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Price range over the prices it filters" tour={TOUR} sample>
      <PriceHistogramDemo />
    </PieceStage>
  );
}

More like this

Time ruler you can fling

DragPickers and booking

Option cards with a sliding ring

Press, Layout AnimationPickers and booking

Booking rail with free times

DragPickers and booking

Select with a gliding highlight

HoverForms and inputs

Estimate slider

Drag, TypeForms and inputs

Date range with nightly prices

PressPickers and booking