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://uimaxxer.com/r/switch.jsonPasskeysSettings · Permissions
Permissions
Swarm on #482
Four agents fixing duplicate Stripe charges, $40.00 cap
Run tests before every push
Agents push without running the suite.
Ask before merging into main
Agents merge as soon as every check passes.
Stop at the spend cap
All four agents pause at $40.00 for this run.
"use client";
// uimaxxer · Switch, MIT. Idea: the thumb follows the finger 1:1, stretches as you press, and a flick decides. Delight: on a tap or a key press the thumb stretches toward where it is going, then lands round again.
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;
/** sm 36×22, md 46×28, lg 60×36 for a settings panel at reading size. */
size?: "sm" | "md" | "lg";
className?: string;
};
const SIZES = { sm: { w: 36, h: 22, t: 16 }, md: { w: 46, h: 28, t: 22 }, lg: { w: 60, h: 36, t: 30 } } 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;
// How far the thumb stretches under a press: about a quarter of its width at every size.
const grow = Math.round(s.t * (size === "lg" ? 0.3 : 0.24));
const outer = Math.round(s.h * 0.32);
const thumbR = Math.round(s.t * 0.27);
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 byPointer = useRef(false);
const first = useRef(true);
const id = useId();
// The ink runs from the left edge to the thumb's middle, so mid-travel reads as the thumb pulling it along.
const fill = useTransform(x, [0, travel * 0.3], [0, 1], { clamp: true });
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);
const fillW = useTransform([x, stretch], ([xv, st]: number[]) => {
const left = (xv as number) - ((st as number) * (xv as number)) / travel;
// Past the middle the ink also covers the far end, so the on state is solid all the way round.
const reach = clamp((xv as number) / travel, 0, 1) * (s.t / 2 + pad);
return Math.min(s.w, Math.max(0, pad + left + (s.t + (st as number)) / 2 + reach));
});
useEffect(() => {
if (drag.current) return;
animate(x, on ? travel : 0, reduce ? { duration: 0 } : SPRING);
// A tap or key press that did not come with a held press still shows the stretch, toward where the thumb is going.
if (!first.current && !byPointer.current && !reduce) animate(stretch, [0, grow, 0], { duration: 0.28, times: [0, 0.35, 1], ease: [0.23, 1, 0.32, 1] });
first.current = false;
byPointer.current = false;
}, [on, travel, x, reduce, grow, stretch]);
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, grow, { 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] });
// A cancelled gesture (the page scrolled, the OS took the pointer) settles back and never toggles.
let next = e.type === "pointercancel" ? on : !on;
if (d.moved && e.type !== "pointercancel") {
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) {
byPointer.current = true;
set(next);
}
};
const key = (e: KeyboardEvent<HTMLButtonElement>) => {
if (e.key === "Enter") {
e.preventDefault();
if (!disabled && !e.repeat) 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 before:absolute before:-inset-2 before:content-[''] disabled:cursor-not-allowed"
style={{ width: s.w, height: s.h, borderRadius: outer }}
>
<span className="well absolute inset-0 rounded-[inherit]" />
<motion.span className="absolute inset-y-0 left-0 rounded-[inherit] bg-primary [.dark_&]:bg-accent [[data-theme=dark]_&]:bg-accent" style={{ opacity: fill, width: fillW }} />
<span className="absolute inset-0 rounded-[inherit] transition-colors duration-150 group-hover:bg-hover group-focus-visible:bg-accent-tint" />
<motion.span
className={cx(
"absolute bg-white",
size === "lg"
? "shadow-[0_0_0_0.5px_rgba(17,18,20,.06),0_1px_1px_rgba(17,18,20,.12),0_3px_8px_-1px_rgba(17,18,20,.18),inset_0_-1px_0_rgba(17,18,20,.06)]"
: "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, borderRadius: thumbR }}
/>
</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" | "lg" | "md" | 36×22, 46×28 or 60×36. The hit area is always at least 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.