Skip to content

Spring Switch

A thumb with squash, stretch and a double bounce.

Installation

CLI

npx shadcn@latest add https://hantui-theta.vercel.app/r/spring-switch.json

Manual

  1. Install the dependencies

    npm install clsx motion tailwind-merge
  2. Add the shared helpers

    Components use cn() from lib/utils.ts and the motion tokens below. See Installation if you have not set them up yet.

    lib/motion.ts
    import type { Transition, Variants } from "motion/react";
    
    /** Durations in seconds. */
    export const duration = {
      instant: 0.1,
      quick: 0.18,
      base: 0.28,
      slow: 0.45,
    } as const;
    
    /** Cubic-bezier curves. */
    export const ease = {
      /** Entering, UI response. */
      out: [0.22, 1, 0.36, 1],
      /** Moving on screen. */
      inOut: [0.65, 0, 0.35, 1],
      /** Sheets and the mobile menu. */
      drawer: [0.32, 0.72, 0, 1],
    } as const;
    
    /** Everyday UI: presses, icon swaps, popovers and modals. Exits run at `exitFactor` of the enter. */
    export const ui = {
      press: { scale: 0.96, duration: 0.12 },
      icon: { type: "spring", duration: 0.3, bounce: 0 },
      popover: { duration: 0.18, ease: ease.out },
      modal: { duration: 0.24, ease: ease.out },
      exitFactor: 0.6,
    } as const;
    
    /** Once-per-visit motion on the landing page: hero letters, the reel and the afterimage. */
    export const kinetic = {
      heroLetter: { duration: 0.6, ease: ease.out },
      /** Delay per letter, eased so the wave slows toward the end. */
      heroStep: 0.035,
      reelSwap: { type: "spring", duration: 0.5, bounce: 0.1 },
      /** Two afterimages: lag in seconds and opacity of each. */
      ghost: { lag: [0.04, 0.09], opacity: [0.14, 0.06] },
    } as const;
    
    /** Spring presets. */
    export const spring = {
      snappy: { type: "spring", stiffness: 500, damping: 30 },
      smooth: { type: "spring", stiffness: 260, damping: 26 },
      bouncy: { type: "spring", stiffness: 300, damping: 15 },
    } as const satisfies Record<string, Transition>;
    
    /** Stagger between siblings, in seconds (0.03–0.06). */
    export const stagger = {
      tight: 0.03,
      base: 0.045,
      loose: 0.06,
    } as const;
    
    /** Blur + fade + y-offset. Falls back to a plain fade under reduced motion. */
    export function enterVariants(reduceMotion?: boolean | null, y = 8): Variants {
      if (reduceMotion) {
        return {
          hidden: { opacity: 0 },
          visible: { opacity: 1, transition: { duration: duration.base } },
          exit: { opacity: 0, transition: { duration: duration.quick } },
        };
      }
      return {
        hidden: { opacity: 0, y, filter: "blur(4px)" },
        visible: {
          opacity: 1,
          y: 0,
          filter: "blur(0px)",
          transition: { duration: duration.base, ease: ease.out },
        },
        exit: {
          opacity: 0,
          y: -y / 2,
          filter: "blur(4px)",
          transition: { duration: duration.quick, ease: ease.out },
        },
      };
    }
    
    /** Scale 0.96 → 1 for popovers, menus and dialogs. */
    export function overlayVariants(reduceMotion?: boolean | null): Variants {
      if (reduceMotion) {
        return {
          hidden: { opacity: 0 },
          visible: { opacity: 1, transition: { duration: duration.quick } },
          exit: { opacity: 0, transition: { duration: duration.instant } },
        };
      }
      return {
        hidden: { opacity: 0, scale: 0.96, filter: "blur(2px)" },
        visible: {
          opacity: 1,
          scale: 1,
          filter: "blur(0px)",
          transition: { duration: duration.quick, ease: ease.out },
        },
        exit: {
          opacity: 0,
          scale: 0.96,
          filter: "blur(2px)",
          transition: { duration: duration.instant + 0.02, ease: ease.out },
        },
      };
    }
    
    /** Parent variants that stagger their children in. */
    export function staggerVariants(gap: number = stagger.base, delayChildren = 0): Variants {
      return {
        hidden: {},
        visible: { transition: { staggerChildren: gap, delayChildren } },
        exit: { transition: { staggerChildren: gap / 2, staggerDirection: -1 } },
      };
    }
  3. Copy the source

    components/ui/spring-switch/spring-switch.tsx
    "use client";
    
    import { useEffect, useRef, useState, type ComponentProps } from "react";
    import { motion, useAnimate, useReducedMotion } from "motion/react";
    import { cn } from "@/lib/utils";
    import { duration } from "@/lib/motion";
    
    export interface SpringSwitchProps
      extends Omit<
        ComponentProps<"button">,
        "value" | "defaultValue" | "onChange" | "role" | "onAnimationStart" | "onDrag" | "onDragStart" | "onDragEnd"
      > {
      /** Controlled state. */
      checked?: boolean;
      /** Initial state when uncontrolled. @default false */
      defaultChecked?: boolean;
      /** Called with the new state when toggled. */
      onCheckedChange?: (checked: boolean) => void;
      /** Switch size. @default "md" */
      size?: "sm" | "md" | "lg";
      /** Submits "on" under this name while checked, like a checkbox. */
      name?: string;
    }
    
    // Track padding is 2px; travel = track width − thumb − 4.
    const sizes = {
      sm: { track: "h-5 w-8 after:-inset-2.5", thumb: "size-4", travel: 12 },
      md: { track: "h-6 w-11 after:-inset-2", thumb: "size-5", travel: 20 },
      lg: { track: "h-8 w-14 after:-inset-1", thumb: "size-7", travel: 24 },
    } as const;
    
    // Low damping gives the thumb an overshoot and a second, smaller bounce.
    const TRAVEL = { type: "spring", stiffness: 560, damping: 17, mass: 0.8 } as const;
    
    export function SpringSwitch({
      checked,
      defaultChecked = false,
      onCheckedChange,
      size = "md",
      name,
      disabled,
      className,
      onClick,
      type = "button",
      ...props
    }: SpringSwitchProps) {
      const [internal, setInternal] = useState(defaultChecked);
      const on = checked ?? internal;
      const [thumb, animate] = useAnimate<HTMLSpanElement>();
      const previous = useRef(on);
      const reduceMotion = useReducedMotion();
      const s = sizes[size];
    
      // Squash and stretch on every change, including ones driven by a controlled prop.
      useEffect(() => {
        if (previous.current === on) return;
        previous.current = on;
        if (reduceMotion || !thumb.current) return;
        animate(
          thumb.current,
          { scaleX: [1, 1.3, 0.86, 1.06, 0.98, 1], scaleY: [1, 0.8, 1.12, 0.95, 1.01, 1] },
          { duration: 0.55, times: [0, 0.2, 0.45, 0.65, 0.82, 1], ease: "easeOut" },
        );
      }, [on, reduceMotion, animate, thumb]);
    
      return (
        <>
          <button
            type={type}
            role="switch"
            aria-checked={on}
            disabled={disabled}
            onClick={(event) => {
              onClick?.(event);
              if (event.defaultPrevented) return;
              if (checked === undefined) setInternal(!on);
              onCheckedChange?.(!on);
            }}
            className={cn(
              "relative inline-flex shrink-0 cursor-pointer rounded-full bg-[color-mix(in_oklab,var(--foreground)_15%,var(--background))] outline-none",
              "after:absolute after:content-[''] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
              "disabled:cursor-not-allowed disabled:opacity-50",
              s.track,
              className,
            )}
            {...props}
          >
            {/* The "on" color fades in as a layer rather than animating background-color. */}
            <motion.span
              aria-hidden="true"
              className="absolute inset-0 rounded-full bg-primary"
              initial={false}
              animate={{ opacity: on ? 1 : 0 }}
              transition={{ duration: duration.quick }}
            />
            <motion.span
              ref={thumb}
              aria-hidden="true"
              className={cn(
                "absolute top-0.5 left-0.5 rounded-full bg-white shadow-[0_1px_2px_rgb(0_0_0/0.2),0_2px_6px_-1px_rgb(0_0_0/0.15)]",
                s.thumb,
              )}
              initial={false}
              animate={{ x: on ? s.travel : 0 }}
              transition={reduceMotion ? { duration: duration.quick } : TRAVEL}
            />
          </button>
          {name && on ? <input type="hidden" name={name} value="on" /> : null}
        </>
      );
    }

Usage

import { SpringSwitch } from "@/components/ui/spring-switch/spring-switch";

export function NotificationsSetting() {
  const [enabled, setEnabled] = useState(true);
  return (
    <div className="flex items-center gap-3">
      <label htmlFor="notifications">Notifications</label>
      <SpringSwitch id="notifications" checked={enabled} onCheckedChange={setEnabled} />
    </div>
  );
}

API reference

PropTypeDefaultDescription
checkedboolean–Controlled state.
defaultCheckedbooleanfalseInitial state when uncontrolled.
onCheckedChange(checked: boolean) => void–Called with the new state when toggled.
size"sm" | "md" | "lg""md"Switch size.
namestring–Submits "on" under this name while checked, like a checkbox.

Also accepts every native <button> attribute, including ref and className.

  • The squash and stretch runs on every change, including changes from a controlled checked prop.
  • Pass name to submit "on" with a form while checked, like a native checkbox.

Accessibility

  • A native button with role="switch" and aria-checked, so it is announced as a switch and toggles with Space or Enter.
  • Pair it with a <label htmlFor> or pass aria-label; the thumb and color layers are aria-hidden.
  • Small and medium sizes extend their hit area to about 40px without changing the layout.
  • With reduced motion enabled, the thumb glides without overshoot, squash or stretch.