Switch
Tap it, or grab the thumb and drag. It follows your finger, stretches as you press, and a flick decides.
npx shadcn@latest add https://captain-ui.vercel.app/r/switch.jsonLet agents run tests
Before every pull request
Ask before merging
You approve each merge to main
Pause at the spend cap
Stops every swarm at $50 this month
"use client";
// Captain UI · Switch, MIT. Tap it, or grab the thumb and drag: it follows the finger 1:1 and a flick decides.
import { animate, motion, useMotionValue, useTransform, useReducedMotion } from "motion/react";
import { useEffect, useId, useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
import { SPRING, SPRING_RELEASE, clamp, cx, rubber } from "@/registry/captain/ui/captain";
type SwitchProps = {
checked?: boolean;
defaultChecked?: boolean;
onCheckedChange?: (checked: boolean) => void;
disabled?: boolean;
/** Visible label. Pass `aria-label` instead when there is none. */
label?: React.ReactNode;
"aria-label"?: string;
size?: "sm" | "md";
className?: string;
};
const SIZES = { sm: { w: 36, h: 22, t: 16 }, md: { w: 46, h: 28, t: 22 } } as const;
export function Switch({ checked, defaultChecked = false, onCheckedChange, disabled, label, size = "md", className, ...rest }: SwitchProps) {
const [inner, setInner] = useState(defaultChecked);
const on = checked ?? inner;
const s = SIZES[size];
const pad = (s.h - s.t) / 2;
const travel = s.w - s.t - pad * 2;
const x = useMotionValue(on ? travel : 0);
const stretch = useMotionValue(0);
const reduce = useReducedMotion();
const drag = useRef<{ id: number; start: number; from: number; moved: boolean; t: number; last: number; v: number } | null>(null);
const id = useId();
const fill = useTransform(x, [0, travel], [0, 1]);
const thumbW = useTransform(stretch, (v) => s.t + v);
const thumbX = useTransform([x, stretch], ([xv, st]: number[]) => (xv as number) - ((st as number) * (xv as number)) / travel);
useEffect(() => {
if (drag.current) return;
animate(x, on ? travel : 0, reduce ? { duration: 0 } : SPRING);
}, [on, travel, x, reduce]);
const set = (next: boolean) => {
if (checked === undefined) setInner(next);
onCheckedChange?.(next);
};
const down = (e: PointerEvent<HTMLButtonElement>) => {
if (disabled || e.button !== 0) return;
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = { id: e.pointerId, start: e.clientX, from: x.get(), moved: false, t: performance.now(), last: e.clientX, v: 0 };
animate(stretch, 5, { duration: 0.16, ease: [0.23, 1, 0.32, 1] });
};
const move = (e: PointerEvent<HTMLButtonElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
const dx = e.clientX - d.start;
if (Math.abs(dx) > 3) d.moved = true;
const now = performance.now();
d.v = ((e.clientX - d.last) / Math.max(1, now - d.t)) * 1000;
d.t = now;
d.last = e.clientX;
const raw = d.from + dx;
const over = raw < 0 ? raw : raw > travel ? raw - travel : 0;
x.set(clamp(raw, 0, travel) + rubber(over, s.w * 0.25));
};
const up = (e: PointerEvent<HTMLButtonElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
drag.current = null;
animate(stretch, 0, { duration: 0.18, ease: [0.23, 1, 0.32, 1] });
let next = !on;
if (d.moved) {
const projected = x.get() + d.v * 0.08;
next = projected > travel / 2;
}
animate(x, next ? travel : 0, reduce ? { duration: 0 } : d.moved ? SPRING_RELEASE : SPRING);
if (next !== on) set(next);
};
const key = (e: KeyboardEvent<HTMLButtonElement>) => {
if (e.key === "Enter") {
e.preventDefault();
if (!disabled) set(!on);
}
};
return (
<span className={cx("inline-flex items-center gap-3 select-none", disabled && "opacity-45", className)}>
<button
type="button"
role="switch"
aria-checked={on}
aria-labelledby={label ? id : undefined}
aria-label={label ? undefined : rest["aria-label"]}
disabled={disabled}
onPointerDown={down}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
onClick={(e) => {
// Pointer input is handled on pointerup; this catches Space from the keyboard.
if (e.detail === 0 && !disabled) set(!on);
}}
onKeyDown={key}
className="group relative shrink-0 touch-none rounded-[9px] before:absolute before:-inset-2 before:content-[''] disabled:cursor-not-allowed"
style={{ width: s.w, height: s.h }}
>
<span className="well absolute inset-0 rounded-[inherit]" />
<motion.span className="absolute inset-0 rounded-[inherit] bg-primary" style={{ opacity: fill }} />
<span className="absolute inset-0 rounded-[inherit] transition-colors duration-150 group-hover:bg-hover group-focus-visible:bg-accent-tint" />
<motion.span
className="absolute rounded-[6px] bg-white shadow-[0_1px_1px_rgba(17,18,20,.12),0_2px_6px_rgba(17,18,20,.14),inset_0_-1px_0_rgba(17,18,20,.05)]"
style={{ top: pad, left: pad, height: s.t, width: thumbW, x: thumbX }}
/>
</button>
{label ? (
<span id={id} className="text-[14px] text-ink" onClick={() => !disabled && set(!on)}>
{label}
</span>
) : null}
</span>
);
}Usage
import { Switch } from "@/components/ui/switch"
<Switch label="Ask before merging" onCheckedChange={setAsk} />Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| checked | boolean | Controlled state. | |
| defaultChecked | boolean | false | Initial state when uncontrolled. |
| onCheckedChange | (checked: boolean) => void | Called on tap, drag release or keyboard. | |
| label | ReactNode | Visible label; clicking it toggles too. | |
| size | "sm" | "md" | "md" | 36×22 or 46×28. The hit area is always 44px. |
| disabled | boolean | Dims and ignores input. |
Keyboard
- Space
- Toggle
- Enter
- Toggle
Accessibility
- role=switch with aria-checked.
- The label is wired with aria-labelledby.
- Dragging is optional: tap and keyboard do the same thing.