Segmented control
A raised thumb in a well. Tap a segment and it springs over, or grab the thumb and slide it: it squishes as you press and a flick decides where it lands.
npx shadcn@latest add https://captain-ui.vercel.app/r/segmented.json$240 per year
Billed $240 once, two months free
"use client";
// Captain UI · Segmented control, MIT. Tap a segment, or grab the raised thumb and slide it across: it follows 1:1 and a flick decides.
import { animate, motion, useMotionValue, useReducedMotion } from "motion/react";
import { useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from "react";
import { EASE, SPRING, SPRING_RELEASE, clamp, cx, project, rubber, useIsoLayoutEffect } from "@/registry/captain/ui/captain";
type Option<T extends string> = { value: T; label: ReactNode; disabled?: boolean };
type SegmentedProps<T extends string> = {
options: Option<T>[];
value?: T;
defaultValue?: T;
onValueChange?: (value: T) => void;
"aria-label": string;
size?: "sm" | "md";
disabled?: boolean;
className?: string;
};
const PAD = 3;
export function Segmented<T extends string>({ options, value, defaultValue, onValueChange, size = "md", disabled, className, ...rest }: SegmentedProps<T>) {
const [inner, setInner] = useState<T>(defaultValue ?? (options[0]?.value as T));
const current = value ?? inner;
const index = Math.max(0, options.findIndex((o) => o.value === current));
const n = options.length;
const root = useRef<HTMLDivElement>(null);
const buttons = useRef<Array<HTMLButtonElement | null>>([]);
const seg = useRef(0);
const x = useMotionValue(0);
const squish = useMotionValue(1);
const reduce = useReducedMotion();
const [hot, setHot] = useState<number | null>(null); // label lit while dragging
const [pressed, setPressed] = useState<number | null>(null);
const skip = useRef(false); // the release spring already owns x
const drag = useRef<{ id: number; start: number; from: number; on: boolean; moved: boolean; t: number; last: number; v: number; at: number } | null>(null);
useIsoLayoutEffect(() => {
const el = root.current;
if (!el) return;
const measure = () => {
seg.current = (el.clientWidth - PAD * 2) / n;
if (!drag.current) x.jump(index * seg.current);
};
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
return () => ro.disconnect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [n]);
useIsoLayoutEffect(() => {
if (skip.current) {
skip.current = false;
return;
}
if (drag.current?.moved) return;
animate(x, index * seg.current, reduce ? { duration: 0 } : SPRING);
}, [index, reduce, x]);
const select = (i: number) => {
const o = options[i];
if (!o || o.disabled || disabled) return;
if (value === undefined) setInner(o.value);
if (o.value !== current) onValueChange?.(o.value);
};
const indexAt = (clientX: number) => {
const r = root.current!.getBoundingClientRect();
return clamp(Math.floor((clientX - r.left - PAD) / seg.current), 0, n - 1);
};
const down = (e: PointerEvent<HTMLDivElement>) => {
if (disabled || e.button !== 0) return;
const at = indexAt(e.clientX);
if (options[at]?.disabled) return;
e.currentTarget.setPointerCapture(e.pointerId);
const on = at === index;
drag.current = { id: e.pointerId, start: e.clientX, from: x.get(), on, moved: false, t: performance.now(), last: e.clientX, v: 0, at };
if (on) animate(squish, 0.95, { duration: 0.16, ease: EASE });
else setPressed(at);
};
const move = (e: PointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
const now = performance.now();
d.v = ((e.clientX - d.last) / Math.max(1, now - d.t)) * 1000;
d.t = now;
d.last = e.clientX;
if (!d.on) {
setPressed(indexAt(e.clientX) === d.at ? d.at : null);
return;
}
const dx = e.clientX - d.start;
if (!d.moved && Math.abs(dx) < 3) return;
d.moved = true;
const maxX = (n - 1) * seg.current;
const raw = d.from + dx;
const over = raw < 0 ? raw : raw > maxX ? raw - maxX : 0;
const next = clamp(raw, 0, maxX) + rubber(over, seg.current * 0.3);
x.set(next);
setHot(clamp(Math.round(next / seg.current), 0, n - 1));
};
const up = (e: PointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
animate(squish, 1, reduce ? { duration: 0 } : SPRING_RELEASE);
setPressed(null);
setHot(null);
if (d.on && d.moved) {
let target = clamp(Math.round((x.get() + project(d.v) * 0.18) / seg.current), 0, n - 1);
while (options[target]?.disabled && target > 0) target--;
drag.current = null;
skip.current = target !== index;
animate(x, target * seg.current, reduce ? { duration: 0 } : { ...SPRING_RELEASE, velocity: d.v });
select(target);
return;
}
drag.current = null;
if (!d.on && e.type === "pointerup" && indexAt(e.clientX) === d.at) select(d.at);
};
const key = (e: KeyboardEvent<HTMLButtonElement>) => {
const dir = e.key === "ArrowRight" || e.key === "ArrowDown" ? 1 : e.key === "ArrowLeft" || e.key === "ArrowUp" ? -1 : 0;
let to = e.key === "Home" ? 0 : e.key === "End" ? n - 1 : dir ? index : -1;
if (to < 0) return;
e.preventDefault();
for (let k = 0; k < n; k++) {
if (dir) to = (to + dir + n) % n;
if (!options[to]?.disabled) break;
if (!dir) to = clamp(to + (e.key === "Home" ? 1 : -1), 0, n - 1);
}
select(to);
buttons.current[to]?.focus();
};
const lit = hot ?? index;
return (
<div
ref={root}
role="radiogroup"
aria-label={rest["aria-label"]}
aria-disabled={disabled || undefined}
onPointerDown={down}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
className={cx(
"well relative inline-grid touch-pan-y rounded-inner select-none",
size === "sm" ? "h-8 text-[12.5px]" : "h-9 text-[13px]",
disabled && "opacity-45",
className,
)}
style={{ gridTemplateColumns: `repeat(${n}, minmax(0, 1fr))`, padding: PAD }}
>
<motion.div
aria-hidden
className="raised absolute rounded-[6px]"
style={{ top: PAD, bottom: PAD, left: PAD, width: `calc((100% - ${PAD * 2}px) / ${n})`, x, scale: squish }}
/>
{options.map((o, i) => (
<button
key={o.value}
ref={(el) => {
buttons.current[i] = el;
}}
type="button"
role="radio"
aria-checked={i === index}
tabIndex={i === index ? 0 : -1}
disabled={o.disabled || disabled}
onClick={(e) => {
// Pointer input is handled on pointerup; this catches Space and Enter.
if (e.detail === 0) select(i);
}}
onKeyDown={key}
className={cx(
"relative z-10 rounded-[6px] px-4 font-medium whitespace-nowrap transition-[color,opacity] duration-150 ease-snap focus-visible:bg-accent-tint disabled:cursor-not-allowed disabled:opacity-45",
i === lit ? "text-ink" : "text-ink-2 hover:text-ink",
pressed === i && "opacity-55",
)}
>
{o.label}
</button>
))}
</div>
);
}Usage
import { Segmented } from "@/components/ui/segmented"
<Segmented
aria-label="Billing period"
defaultValue="yearly"
options={[{ value: "monthly", label: "Monthly" }, { value: "yearly", label: "Yearly" }]}
/>Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| options | { value: string; label: ReactNode; disabled?: boolean }[] | The segments, all the same width. | |
| value | string | Controlled value. | |
| defaultValue | string | options[0].value | Initial value when uncontrolled. |
| onValueChange | (value: string) => void | Called on tap, drag release or arrow key. | |
| aria-label | string | Names the group. Required. | |
| size | "sm" | "md" | "md" | 32 or 36px tall. |
| disabled | boolean | Dims and ignores input. |
Keyboard
- ← →
- Previous / next segment
- Home / End
- First / last segment
Accessibility
- role=radiogroup with a role=radio per segment and aria-checked.
- Roving tabindex: Tab lands on the selected segment, arrows move and select.
- Dragging is optional: tap and keyboard do the same thing.