Skip to content

Action Swap Button

Label and icon swap with blur and a vertical slide.

Installation

CLI

npx shadcn@latest add https://hantui-theta.vercel.app/r/action-swap-button.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/action-swap-button/action-swap-button.tsx
    "use client";
    
    import { useState, type ComponentProps, type MouseEvent, type ReactNode } from "react";
    import { AnimatePresence, motion, useReducedMotion, type Variants } from "motion/react";
    import { cn } from "@/lib/utils";
    import { duration, ease, spring } from "@/lib/motion";
    
    type Look = "solid" | "primary" | "outline" | "ghost";
    
    export interface ActionSwapButtonProps
      extends Omit<ComponentProps<"button">, "children" | "onAnimationStart" | "onDrag" | "onDragStart" | "onDragEnd"> {
      /** Controlled state. */
      pressed?: boolean;
      /** Initial state when uncontrolled. @default false */
      defaultPressed?: boolean;
      /** Called when the button toggles. */
      onPressedChange?: (pressed: boolean) => void;
      /** Label in the default state. Used as the accessible name when iconOnly. */
      label: ReactNode;
      /** Label once toggled. */
      pressedLabel: ReactNode;
      /** Icon in the default state. */
      icon?: ReactNode;
      /** Icon once toggled. */
      pressedIcon?: ReactNode;
      /** Look in the default state. @default "solid" */
      variant?: Look;
      /** Look once toggled. @default "outline" */
      pressedVariant?: Look;
      /** Button size. @default "md" */
      size?: "sm" | "md" | "lg";
      /** Show icons only; labels become the accessible name. @default false */
      iconOnly?: boolean;
    }
    
    const layerClasses: Record<Look, string> = {
      solid:
        "bg-foreground shadow-[inset_0_1px_0_rgb(255_255_255/0.14),0_1px_2px_rgb(0_0_0/0.14),0_4px_12px_-2px_rgb(0_0_0/0.12)] group-hover:bg-foreground/90",
      primary:
        "bg-primary shadow-[inset_0_1px_0_rgb(255_255_255/0.2),0_1px_2px_rgb(0_0_0/0.12),0_4px_12px_-2px_color-mix(in_oklab,var(--primary)_40%,transparent)] group-hover:bg-primary/90",
      outline: "border border-border bg-background shadow-xs group-hover:bg-accent",
      ghost: "group-hover:bg-accent",
    };
    
    const textClasses: Record<Look, string> = {
      solid: "text-background",
      primary: "text-primary-foreground",
      outline: "text-foreground",
      ghost: "text-foreground",
    };
    
    const sizeClasses = {
      sm: { base: "h-8 px-3 text-[13px] rounded-md", icon: "size-8 rounded-md" },
      md: { base: "h-10 px-4 text-sm rounded-md", icon: "size-10 rounded-md" },
      lg: { base: "h-12 px-6 text-[15px] rounded-lg", icon: "size-12 rounded-lg [&_svg]:size-5" },
    } as const;
    
    export function ActionSwapButton({
      pressed: pressedProp,
      defaultPressed = false,
      onPressedChange,
      label,
      pressedLabel,
      icon,
      pressedIcon,
      variant = "solid",
      pressedVariant = "outline",
      size = "md",
      iconOnly = false,
      type = "button",
      className,
      onClick,
      "aria-label": ariaLabel,
      ...props
    }: ActionSwapButtonProps) {
      const [internalPressed, setInternalPressed] = useState(defaultPressed);
      const pressed = pressedProp ?? internalPressed;
      const [toggled, setToggled] = useState(false);
      const reduceMotion = useReducedMotion();
      // Toggling on slides the new content up from below; toggling off reverses it.
      const direction = pressed ? 1 : -1;
    
      function toggle(event: MouseEvent<HTMLButtonElement>) {
        onClick?.(event);
        if (event.defaultPrevented) return;
        const next = !pressed;
        if (pressedProp === undefined) setInternalPressed(next);
        setToggled(true);
        onPressedChange?.(next);
      }
    
      const swap: Variants = reduceMotion
        ? { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } }
        : {
            initial: (dir: number) => ({ opacity: 0, y: dir * 16, filter: "blur(4px)" }),
            animate: { opacity: 1, y: 0, filter: "blur(0px)" },
            exit: (dir: number) => ({ opacity: 0, y: dir * -16, filter: "blur(4px)" }),
          };
    
      const currentLabel = pressed ? pressedLabel : label;
      const looks: Look[] = variant === pressedVariant ? [variant] : [variant, pressedVariant];
    
      const renderContent = (on: boolean) => (
        <>
          {on ? pressedIcon : icon}
          {iconOnly ? null : on ? pressedLabel : label}
        </>
      );
    
      return (
        <>
          <motion.button
            type={type}
            onClick={toggle}
            aria-label={ariaLabel ?? (iconOnly && typeof currentLabel === "string" ? currentLabel : undefined)}
            whileTap={reduceMotion ? undefined : { scale: 0.96 }}
            transition={spring.snappy}
            className={cn(
              "group relative isolate inline-flex shrink-0 cursor-pointer items-center justify-center overflow-hidden font-medium whitespace-nowrap outline-none select-none",
              "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
              "disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0",
              iconOnly ? sizeClasses[size].icon : sizeClasses[size].base,
              size === "sm" && "after:absolute after:-inset-1 after:content-['']",
              className,
            )}
            {...props}
          >
            {/* Each look is its own layer; switching cross-fades opacity rather than animating colors. */}
            {looks.map((look, i) => (
              <motion.span
                key={look}
                aria-hidden="true"
                initial={false}
                animate={{ opacity: looks.length === 1 || (i === 1) === pressed ? 1 : 0 }}
                transition={{ duration: duration.base, ease: ease.out }}
                className={cn("absolute inset-0 -z-10 rounded-[inherit] transition-colors duration-150", layerClasses[look])}
              />
            ))}
    
            <span className="grid place-items-center *:[grid-area:1/1]">
              <span aria-hidden="true" className="invisible inline-flex items-center gap-2">
                {renderContent(false)}
              </span>
              <span aria-hidden="true" className="invisible inline-flex items-center gap-2">
                {renderContent(true)}
              </span>
              <AnimatePresence initial={false} custom={direction}>
                <motion.span
                  key={pressed ? "pressed" : "default"}
                  custom={direction}
                  variants={swap}
                  initial="initial"
                  animate="animate"
                  exit="exit"
                  transition={{ duration: duration.base, ease: ease.out }}
                  className={cn("inline-flex items-center gap-2", textClasses[pressed ? pressedVariant : variant])}
                >
                  {renderContent(pressed)}
                </motion.span>
              </AnimatePresence>
            </span>
          </motion.button>
          <span role="status" className="sr-only">
            {toggled ? currentLabel : null}
          </span>
        </>
      );
    }

Usage

import { UserCheck, UserPlus } from "lucide-react";
import { ActionSwapButton } from "@/components/ui/action-swap-button/action-swap-button";

export function FollowButton() {
  return (
    <ActionSwapButton
      label="Follow"
      pressedLabel="Following"
      icon={<UserPlus />}
      pressedIcon={<UserCheck />}
      onPressedChange={(following) => setFollowing(following)}
    />
  );
}

API reference

PropTypeDefaultDescription
pressedboolean–Controlled state.
defaultPressedbooleanfalseInitial state when uncontrolled.
onPressedChange(pressed: boolean) => void–Called when the button toggles.
label*ReactNode–Label in the default state. Used as the accessible name when iconOnly.
pressedLabel*ReactNode–Label once toggled.
iconReactNode–Icon in the default state.
pressedIconReactNode–Icon once toggled.
variantLook"solid"Look in the default state.
pressedVariantLook"outline"Look once toggled.
size"sm" | "md" | "lg""md"Button size.
iconOnlybooleanfalseShow icons only; labels become the accessible name.

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

  • Each look (solid, outline and so on) is a separate layer that cross-fades, so the color change stays on opacity.

Accessibility

  • The label itself changes, so the button does not also set aria-pressed (per the WAI-ARIA button pattern).
  • After each toggle, a polite status region announces the new label.
  • In iconOnly mode, `label` and `pressedLabel` become the accessible name. Pass strings there.
  • Both states are measured in one grid cell, so the button keeps a steady width and never shifts its neighbors.
  • With reduced motion enabled, the content cross-fades without sliding or blurring.