Async action button

A button that runs a whole async action in place: idle, pending, success and error, without ever changing width, because every label is stacked invisibly in one grid cell. Labels crossfade upward between states and icons change with them: a ring spinner (or a determinate arc when progress is given), a check that draws itself and an X with a small shake. While pending a hairline bar runs along the bottom edge, and success briefly floods the button green before it eases back. It keeps focus throughout, is busy rather than disabled while pending, announces each state politely, and simply swaps icons when reduced motion is requested. A status prop can force any state.

ButtonsComponentTailwind v4

Source

"use client";

import { useEffect, useRef, useState, type ButtonHTMLAttributes, type MouseEvent, type ReactNode } from "react";
import { cn } from "@/lib/utils";

export type AsyncStatus = "idle" | "pending" | "success" | "error";
const STATUSES: AsyncStatus[] = ["idle", "pending", "success", "error"];

export type AsyncActionButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "children" | "onError"> & {
  action: () => Promise<unknown>;
  labels: Record<AsyncStatus, ReactNode>;
  /** Shown while idle, e.g. a download or cart icon. */
  icon?: ReactNode;
  /** 0 to 1 while pending draws a determinate arc and bar; leave undefined for an indeterminate spinner. */
  progress?: number;
  /** How long success and error stay before returning to idle. */
  resetMs?: number;
  variant?: "solid" | "outline";
  /** Forces a state, for documentation or when the work is driven from elsewhere. */
  status?: AsyncStatus;
  onSuccess?: (result: unknown) => void;
  onError?: (error: unknown) => void;
};

const CSS = `@keyframes chm-aab-spin{to{transform:rotate(360deg)}}
@keyframes chm-aab-draw{from{stroke-dashoffset:1}to{stroke-dashoffset:0}}
@keyframes chm-aab-shake{0%,100%{transform:translateX(0)}20%{transform:translateX(-4px)}40%{transform:translateX(4px)}60%{transform:translateX(-3px)}80%{transform:translateX(2px)}}
@keyframes chm-aab-slide{from{transform:translateX(-100%)}to{transform:translateX(250%)}}
@media (prefers-reduced-motion:no-preference){
.chm-aab-spin{animation:chm-aab-spin .8s linear infinite;transform-origin:center}
.chm-aab-draw{animation:chm-aab-draw .4s cubic-bezier(.65,0,.35,1) .1s both}
.chm-aab[data-status=error]{animation:chm-aab-shake .4s ease-in-out}
.chm-aab-bar{animation:chm-aab-slide 1.1s ease-in-out infinite}
.chm-aab-layer{transition:opacity .22s ease,transform .3s cubic-bezier(.3,1.2,.5,1)}
.chm-aab-flood{transition:opacity .6s ease}
.chm-aab-arc{transition:stroke-dashoffset .25s ease}
}`;

function Spinner({ progress }: { progress?: number }) {
  const determinate = progress !== undefined;
  return (
    <svg viewBox="0 0 20 20" className="size-4" aria-hidden="true">
      <circle cx="10" cy="10" r="7.5" fill="none" stroke="currentColor" strokeOpacity=".25" strokeWidth="2.25" />
      {determinate ? (
        <circle
          className="chm-aab-arc"
          cx="10" cy="10" r="7.5" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round"
          pathLength={1} strokeDasharray="1" strokeDashoffset={1 - Math.min(1, Math.max(0, progress))}
          transform="rotate(-90 10 10)"
        />
      ) : (
        <circle
          className="chm-aab-spin"
          cx="10" cy="10" r="7.5" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round"
          pathLength={1} strokeDasharray="0.28 0.72"
        />
      )}
    </svg>
  );
}

function DrawnCheck() {
  return (
    <svg viewBox="0 0 20 20" className="size-4" aria-hidden="true">
      <path className="chm-aab-draw" d="M4.5 10.5l3.5 3.5 7.5-8" fill="none" stroke="currentColor" strokeWidth="2.5"
        strokeLinecap="round" strokeLinejoin="round" pathLength={1} strokeDasharray="1" />
    </svg>
  );
}

function Cross() {
  return (
    <svg viewBox="0 0 20 20" className="size-4" aria-hidden="true">
      <path d="M6 6l8 8M14 6l-8 8" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" />
    </svg>
  );
}

export function AsyncActionButton({
  action, labels, icon, progress, resetMs = 1800, variant = "solid", status: forced, onSuccess, onError,
  className, onClick, type = "button", ...props
}: AsyncActionButtonProps) {
  const [own, setOwn] = useState<AsyncStatus>("idle");
  const status = forced ?? own;
  const [previous, setPrevious] = useState<AsyncStatus | null>(null);
  const lastStatus = useRef(status);
  const timer = useRef<number | undefined>(undefined);
  const mounted = useRef(true);

  useEffect(() => {
    mounted.current = true;
    return () => { mounted.current = false; window.clearTimeout(timer.current); };
  }, []);
  // Remember which label to send upward when the state changes.
  useEffect(() => {
    if (lastStatus.current !== status) { setPrevious(lastStatus.current); lastStatus.current = status; }
  }, [status]);

  async function run(event: MouseEvent<HTMLButtonElement>) {
    onClick?.(event);
    if (event.defaultPrevented || status === "pending" || forced) return;
    window.clearTimeout(timer.current);
    setOwn("pending");
    let next: AsyncStatus = "success";
    try {
      const result = await action();
      if (!mounted.current) return;
      onSuccess?.(result);
    } catch (error) {
      if (!mounted.current) return;
      next = "error";
      onError?.(error);
    }
    setOwn(next);
    timer.current = window.setTimeout(() => mounted.current && setOwn("idle"), resetMs);
  }

  const icons: Record<AsyncStatus, ReactNode> = {
    idle: icon,
    pending: <Spinner progress={progress} />,
    success: <DrawnCheck key={status === "success" ? "on" : "off"} />,
    error: <Cross />,
  };
  const pending = status === "pending";
  const announce = status === "idle" ? "" : labels[status];

  return (
    <>
    <button
      type={type}
      {...props}
      data-status={status}
      aria-busy={pending || undefined}
      aria-disabled={pending || props.disabled || undefined}
      onClick={run}
      className={cn(
        "chm-aab relative isolate inline-grid h-10 select-none items-center overflow-hidden rounded-lg px-4 text-sm font-medium",
        "outline-none 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 aria-busy:cursor-progress",
        variant === "solid"
          ? "bg-primary text-primary-foreground shadow-sm hover:bg-primary/90"
          : "border bg-background text-foreground shadow-xs hover:bg-accent",
        status === "success" && "text-white",
        status === "error" && (variant === "solid" ? "text-white" : "text-destructive"),
        className,
      )}
    >
      <style href="chm-async-action-button" precedence="default">{CSS}</style>
      <span
        aria-hidden="true"
        className={cn(
          "chm-aab-flood absolute inset-0 -z-10",
          status === "error" ? (variant === "solid" ? "bg-destructive" : "bg-destructive/10") : "bg-emerald-600",
          status === "success" || status === "error" ? "opacity-100" : "opacity-0",
        )}
      />
      {STATUSES.map((key) => (
        <span
          key={key}
          aria-hidden="true"
          className={cn(
            "chm-aab-layer col-start-1 row-start-1 flex items-center justify-center gap-2 whitespace-nowrap",
            key === status ? "translate-y-0 opacity-100" : key === previous ? "-translate-y-3 opacity-0" : "translate-y-3 opacity-0",
          )}
        >
          {icons[key] && <span className="grid size-4 place-items-center [&_svg]:size-4">{icons[key]}</span>}
          {labels[key]}
        </span>
      ))}
      {/* The visible label for assistive tech; the stacked layers above only lock the width. */}
      <span className="sr-only">{labels[status]}</span>
      {pending && (
        <span aria-hidden="true" className="absolute inset-x-0 bottom-0 h-0.5 overflow-hidden bg-current/15">
          {progress !== undefined ? (
            <span className="chm-aab-arc block h-full bg-current" style={{ width: `${Math.round(progress * 100)}%` }} />
          ) : (
            <span className="chm-aab-bar block h-full w-2/5 bg-current" />
          )}
        </span>
      )}
    </button>
    <span role="status" aria-live="polite" className="sr-only">{announce}</span>
    </>
  );
}