particle button.json

"use client";

/**
 * @author: @dorianbaffier
 * @description: Particle Button
 * @version: 2.0.0
 * @date: 2026-10-16
 * @license: MIT
 * @website: https://kokonutui.com
 * @github: https://github.com/kokonut-labs/kokonutui
 *
 * A status button for async actions. Return a promise from `onClick` and the
 * label crossfades to a spinner, then to a drawn check with a burst of
 * particles, or to an error with a shake. The width follows every label.
 */

import type { VariantProps } from "class-variance-authority";
import { AlertCircle } from "lucide-react";
import {
  AnimatePresence,
  MotionConfig,
  motion,
  useAnimationControls,
  useReducedMotion,
} from "motion/react";
import {
  type ComponentProps,
  type MouseEvent,
  type ReactNode,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";

export type ParticleButtonStatus = "idle" | "pending" | "success" | "error";

export interface ParticleButtonProps
  extends Omit<
      ComponentProps<"button">,
      // Motion owns the drag and animation handlers on a motion.button.
      | "onClick"
      | "children"
      | "onDrag"
      | "onDragStart"
      | "onDragEnd"
      | "onAnimationStart"
    >,
    VariantProps {
  children?: ReactNode;
  /**
   * Return a promise to show the pending state until it settles. A rejected
   * promise shows the error state. A plain click goes straight to success.
   */
  onClick?: (event: MouseEvent) => unknown;
  /** Called when the action succeeds, alongside the burst. */
  onSuccess?: () => void;
  /** Called with the rejection reason when the action fails. */
  onError?: (error: unknown) => void;
  /** Controlled status. Without it the button tracks `onClick` itself. */
  status?: ParticleButtonStatus;
  /** How long (ms) the success state shows before going back to idle. */
  successDuration?: number;
  /** How long (ms) the error state shows. Longer than success, so it can be read. */
  errorDuration?: number;
  pendingLabel?: ReactNode;
  successLabel?: ReactNode;
  errorLabel?: ReactNode;
  /** Icon rendered after the idle label. */
  icon?: ReactNode;
  /** Fire the particle burst on success. */
  particles?: boolean;
}

const EASE_OUT = [0.23, 1, 0.32, 1] as const;
const LABEL_TRANSITION = { duration: 0.2, ease: EASE_OUT };
const WIDTH_TRANSITION = { type: "spring", duration: 0.35, bounce: 0 } as const;
const SHAKE = { x: [0, -5, 5, -3, 3, 0] };
const ZERO_ALPHA = /(,|\/)\s*0\)$/;

interface Particle {
  x: number;
  y: number;
  vx: number;
  vy: number;
  angle: number;
  spin: number;
  w: number;
  h: number;
}

const PARTICLE_COUNT = 18;
const GRAVITY = 0.0016; // px per ms²
const DRAG = 0.0022; // fraction of velocity lost per ms
const LIFETIME = 650;
const BLEED = 64; // room around the button the canvas can draw into

function createParticles(originX: number, width: number): Particle[] {
  return Array.from({ length: PARTICLE_COUNT }, (_, i) => {
    const spread = (Math.random() - 0.5) * Math.min(width, 120);
    const x = Math.min(Math.max(originX + spread, 4), width - 4);
    const side = x < width / 2 ? -1 : 1;
    const speed = 0.18 + Math.random() * 0.22;
    const angle = -Math.PI / 2 + side * Math.random() * 0.9;
    const isChip = i % 3 === 0;
    return {
      x,
      y: 0,
      vx: Math.cos(angle) * speed,
      vy: Math.sin(angle) * speed,
      angle: Math.random() * Math.PI,
      spin: (Math.random() - 0.5) * 0.02,
      w: isChip ? 5 : 3,
      h: isChip ? 2 : 3,
    };
  });
}

function Burst({
  originX,
  color,
  onDone,
}: {
  originX: number;
  color: string;
  onDone: () => void;
}) {
  const canvasRef = useRef(null);
  const onDoneRef = useRef(onDone);
  onDoneRef.current = onDone;

useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas?.getContext("2d");
    const parent = canvas?.parentElement?.parentElement;
    if (!(canvas && ctx && parent)) {
      return;
    }
    const dpr = window.devicePixelRatio || 1;
    const width = parent.offsetWidth;
    const cssW = width + BLEED * 2;
    const cssH = parent.offsetHeight + BLEED * 2;
    canvas.width = cssW * dpr;
    canvas.height = cssH * dpr;
    ctx.scale(dpr, dpr);

const particles = createParticles(originX, width);
    const start = performance.now();
    let last = start;
    let frame = 0;

const tick = (now: number) => {
      const dt = Math.min(now - last, 32);
      last = now;
      const t = (now - start) / LIFETIME;
      ctx.clearRect(0, 0, cssW, cssH);
      if (t >= 1) {
        onDoneRef.current();
        return;
      }
      ctx.fillStyle = color;
      ctx.globalAlpha = 1 - t * t;
      for (const p of particles) {
        p.vx *= 1 - DRAG * dt;
        p.vy = p.vy * (1 - DRAG * dt) + GRAVITY * dt;
        p.x += p.vx * dt;
        p.y += p.vy * dt;
        p.angle += p.spin * dt;
        ctx.save();
        ctx.translate(p.x + BLEED, p.y + BLEED);
        ctx.rotate(p.angle);
        ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
        ctx.restore();
      }
      frame = requestAnimationFrame(tick);
    };
    frame = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(frame);
  }, [originX, color]);

return (
    <canvas ref={canvasRef} />
  );
}

function Spinner() {
  return (
    <AlertCircle />
  );
}

function Check() {
  return (
    <span>✓</span>
  );
}

function burstColor(button: HTMLElement) {
  const style = getComputedStyle(button);
  const fill = style.backgroundColor;
  const clear = fill === "transparent" || ZERO_ALPHA.test(fill);
  return clear ? style.color : fill;
}

function isPromiseLike(value: unknown): value is PromiseLike {
  return (
    typeof value === "object" &&
    value !== null &&
    typeof (value as PromiseLike).then === "function"
  );
}

export default function ParticleButton({
  children = "Save changes",
  onClick,
  onSuccess,
  onError,
  status: controlledStatus,
  successDuration = 1600,
  errorDuration = 3200,
  pendingLabel = "Saving",
  successLabel = "Saved",
  errorLabel = "Try again",
  icon,
  particles = true,
  variant,
  size,
  className,
  disabled,
  ...props
}: ParticleButtonProps) {
  const [internalStatus, setInternalStatus] = useState("idle");
  const status = controlledStatus ?? internalStatus;
  const [burst, setBurst] = useState<{
    id: number;
    originX: number;
    color: string;
  } | null>(null);
  const [width, setWidth] = useState();

const buttonRef = useRef(null);
  const contentRef = useRef(null);
  const pressXRef = useRef(null);
  const resetRef = useRef(null);
  const runRef = useRef(0);
  const previousStatusRef = useRef(status);
  const shake = useAnimationControls();
  const shouldReduceMotion = useReducedMotion();

useEffect(
    () => () => {
      if (resetRef.current) {
        clearTimeout(resetRef.current);
      }
    },
    []
  );

useLayoutEffect(() => {
    const button = buttonRef.current;
    const content = contentRef.current;
    if (!(button && content)) {
      return;
    }
    const measure = () => {
      const labels = content.querySelectorAll(
        `[data-label="${status}"]`
      );
      const label = labels.item(labels.length - 1);
      if (!label) {
        return;
      }
      const style = getComputedStyle(button);
      const chrome =
        Number.parseFloat(style.paddingLeft) +
        Number.parseFloat(style.paddingRight) +
        Number.parseFloat(style.borderLeftWidth) +
        Number.parseFloat(style.borderRightWidth);
      setWidth(Math.ceil(label.scrollWidth + chrome));
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(content);
    return () => observer.disconnect();
  }, [status]);

useEffect(() => {
    const previous = previousStatusRef.current;
    previousStatusRef.current = status;
    if (previous === status) {
      return;
    }
    const button = buttonRef.current;
    if (status === "success" && particles && !shouldReduceMotion && button) {
      const originX = pressXRef.current ?? button.offsetWidth / 2;
      setBurst({
        id: Date.now(),
        originX,
        color: burstColor(button),
      });
    }
    if (status === "error" && !shouldReduceMotion) {
      shake.start(SHAKE, { duration: 0.32, ease: "easeOut" });
    }
  }, [status, particles, shouldReduceMotion, shake]);

const settle = (next: "success" | "error") => {
    setInternalStatus(next);
    resetRef.current = setTimeout(
      () => {
        setInternalStatus("idle");
        resetRef.current = null;
      },
      next === "success" ? successDuration : errorDuration
    );
  };

const handleClick = (event: MouseEvent) => {
    if (status === "pending") {
      return;
    }
    const rect = event.currentTarget.getBoundingClientRect();
    pressXRef.current =
      event.clientX === 0 && event.clientY === 0
        ? null
        : event.clientX - rect.left;

if (resetRef.current) {
      clearTimeout(resetRef.current);
      resetRef.current = null;
    }

const result = onClick?.(event);
    if (event.defaultPrevented || controlledStatus !== undefined) {
      return;
    }

if (!isPromiseLike(result)) {
      settle("success");
      onSuccess?.();
      return;
    }

runRef.current += 1;
    const run = runRef.current;
    setInternalStatus("pending");
    Promise.resolve(result).then(
      () => {
        if (run === runRef.current) {
          settle("success");
          onSuccess?.();
        }
      },
      (error: unknown) => {
        if (run === runRef.current) {
          settle("error");
          onError?.(error);
        }
      }
    );
  };

const label = (() => {
    switch (status) {
      case "pending":
        return (
          <>
            <Spinner />
            {pendingLabel}
          </>
        );
      case "success":
        return (
          <>
            <Check />
            {successLabel}
          </>
        );
      case "error":
        return (
          <>
            <AlertCircle />
            {errorLabel}
          </>
        );
      default:
        return (
          <>
            {children}
            {icon}
          </>
        );
    }
  })();

return (
    <button
      ref={buttonRef}
      onClick={handleClick}
      {...props}
      className={cn(buttonVariants({ variant, size, className }), { "opacity-50 cursor-not-allowed": disabled })}
      disabled={disabled}
    >
      {burst && (
        <Burst
          originX={burst.originX}
          color={burst.color}
          onDone={() => setBurst(null)}
        />
      )}
      {label}
    </button>
  );
}