1"use client";2
3import React, { useCallback, useId, useRef, useState } from "react";4import { AnimatePresence, motion, useReducedMotion } from "motion/react";5import { cn } from "@/lib/utils";6
7export type ToggleSwitchProps = {8 checked?: boolean;9 defaultChecked?: boolean;10 onCheckedChange?: (checked: boolean) => void;11 label?: string;12 13 description?: string;14 15 loading?: boolean;16 size?: "sm" | "md" | "lg";17 disabled?: boolean;18 className?: string;19 20 "aria-label"?: string;21};22
23const SIZES = {24 sm: { w: 36, h: 20, thumb: 16 },25 md: { w: 48, h: 28, thumb: 24 },26 lg: { w: 60, h: 34, thumb: 30 },27};28const PAD = 2;29const SPRING = { type: "spring" as const, stiffness: 700, damping: 38, mass: 0.7 };30
31export function ToggleSwitch({32 checked: checkedProp,33 defaultChecked = false,34 onCheckedChange,35 label,36 description,37 loading = false,38 size = "md",39 disabled,40 className,41 "aria-label": ariaLabel = "Toggle",42}: ToggleSwitchProps) {43 const reduce = !!useReducedMotion();44 const id = useId();45 const isControlled = checkedProp !== undefined;46 const [uncontrolled, setUncontrolled] = useState(defaultChecked);47 const checked = isControlled ? checkedProp : uncontrolled;48 const [pressed, setPressed] = useState(false);49 const [dragX, setDragX] = useState<number | null>(null);50 const drag = useRef<{ x: number; moved: boolean } | null>(null);51 const suppressClick = useRef(false);52 const inert = disabled || loading;53
54 const { w, h, thumb } = SIZES[size];55 const travel = w - thumb - PAD * 2;56 57 const stretch = pressed && !reduce ? Math.round(thumb * 0.28) : 0;58 const baseX = checked ? travel : 0;59 const x = dragX ?? (checked ? baseX - stretch : baseX);60
61 const setChecked = useCallback(62 (next: boolean) => {63 if (!isControlled) setUncontrolled(next);64 onCheckedChange?.(next);65 },66 [isControlled, onCheckedChange],67 );68
69 const onPointerDown = (e: React.PointerEvent<HTMLButtonElement>) => {70 if (inert || e.button !== 0) return;71 setPressed(true);72 drag.current = { x: e.clientX, moved: false };73 try {74 e.currentTarget.setPointerCapture(e.pointerId);75 } catch {76 77 }78 };79
80 const onPointerMove = (e: React.PointerEvent<HTMLButtonElement>) => {81 const d = drag.current;82 if (!d) return;83 const dx = e.clientX - d.x;84 if (!d.moved && Math.abs(dx) < 3) return;85 d.moved = true;86 setDragX(Math.min(travel - stretch, Math.max(0, baseX - (checked ? stretch : 0) + dx)));87 };88
89 const endDrag = (cancelled: boolean) => {90 const d = drag.current;91 drag.current = null;92 setPressed(false);93 if (d?.moved && dragX !== null && !cancelled) {94 95 96 suppressClick.current = true;97 const next = dragX + (thumb + stretch) / 2 > w / 2 - PAD;98 if (next !== checked) setChecked(next);99 }100 setDragX(null);101 };102
103 return (104 <div className={cn("inline-flex items-start gap-3", inert && disabled && "opacity-50", className)}>105 <motion.button106 id={id}107 type="button"108 role="switch"109 aria-checked={checked}110 aria-busy={loading || undefined}111 aria-labelledby={label ? `${id}-label` : undefined}112 aria-describedby={description ? `${id}-desc` : undefined}113 aria-label={label ? undefined : ariaLabel}114 disabled={disabled}115 onClick={() => {116 if (suppressClick.current) {117 suppressClick.current = false;118 return;119 }120 if (!inert) setChecked(!checked);121 }}122 onPointerDown={onPointerDown}123 onPointerMove={onPointerMove}124 onPointerUp={() => endDrag(false)}125 onPointerCancel={() => endDrag(true)}126 onKeyDown={(e) => {127 128 if (inert) return;129 if (e.key === "ArrowRight" && !checked) setChecked(true);130 if (e.key === "ArrowLeft" && checked) setChecked(false);131 }}132 className={cn(133 "relative shrink-0 touch-none rounded-full outline-none select-none",134 "transition-[background-color,box-shadow] duration-300 ease-out",135 "focus-visible:ring-2 focus-visible:ring-(--color-focus) focus-visible:ring-offset-2 focus-visible:ring-offset-(--color-paper)",136 inert ? "cursor-not-allowed" : "cursor-pointer",137 checked138 ? "bg-(--color-ink) shadow-[inset_0_1px_2px_rgba(0,0,0,0.25)]"139 : "bg-(--color-paper-2) shadow-[inset_0_0_0_1px_var(--color-rule),inset_0_1px_2px_rgba(0,0,0,0.06)]",140 )}141 style={{ width: w, height: h }}142 >143 <motion.span144 aria-hidden145 className="absolute flex items-center justify-center rounded-full bg-(--color-paper) shadow-[0_1px_1px_rgba(0,0,0,0.06),0_2px_6px_rgba(0,0,0,0.18)]"146 style={{ top: PAD, left: PAD, height: thumb }}147 initial={false}148 animate={{ x, width: thumb + stretch }}149 transition={dragX !== null || reduce ? { duration: 0 } : SPRING}150 >151 <AnimatePresence initial={false} mode="popLayout">152 {loading ? (153 <motion.svg154 key="spin"155 viewBox="0 0 16 16"156 className="text-(--color-neutral)"157 style={{ width: thumb * 0.55, height: thumb * 0.55 }}158 initial={{ opacity: 0, scale: 0.5 }}159 animate={{ opacity: 1, scale: 1, rotate: 360 }}160 exit={{ opacity: 0, scale: 0.5 }}161 transition={{ rotate: { repeat: Infinity, ease: "linear", duration: 0.8 }, default: { duration: 0.2 } }}162 >163 <circle cx="8" cy="8" r="6" fill="none" stroke="currentColor" strokeOpacity="0.25" strokeWidth="2.2" />164 <path d="M14 8a6 6 0 0 0-6-6" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" />165 </motion.svg>166 ) : checked ? (167 <motion.svg168 key="on"169 viewBox="0 0 16 16"170 className="text-(--color-ink)"171 style={{ width: thumb * 0.5, height: thumb * 0.5 }}172 fill="none"173 stroke="currentColor"174 strokeWidth="2.6"175 strokeLinecap="round"176 strokeLinejoin="round"177 initial={{ opacity: 0, scale: 0.5 }}178 animate={{ opacity: 1, scale: 1 }}179 exit={{ opacity: 0, scale: 0.5 }}180 transition={{ duration: 0.18 }}181 >182 <motion.path183 d="M3.5 8.5l3 3 6-7"184 initial={{ pathLength: reduce ? 1 : 0 }}185 animate={{ pathLength: 1 }}186 transition={{ duration: 0.25, delay: 0.05 }}187 />188 </motion.svg>189 ) : null}190 </AnimatePresence>191 </motion.span>192 </motion.button>193
194 {label || description ? (195 <div className={cn("flex min-w-0 flex-col", size === "sm" ? "pt-px" : size === "lg" ? "pt-1.5" : "pt-[3px]")}>196 {label ? (197 <label198 htmlFor={id}199 id={`${id}-label`}200 className={cn("text-[14px] leading-snug font-medium text-(--color-ink)", !inert && "cursor-pointer")}201 >202 {label}203 </label>204 ) : null}205 {description ? (206 <span id={`${id}-desc`} className="mt-0.5 text-[12.5px] leading-snug text-(--color-neutral)">207 {description}208 </span>209 ) : null}210 </div>211 ) : null}212 </div>213 );214}