Buttons

Async states

idle → loading → success | error → idle, driven by one promise. Every face is stacked in the same grid cell, so the button never resizes mid-swap.

  • loading
  • promise
  • state machine
  • hook

Preview

state: idle

all states, side by side

Usage

const { state, run } = useAsyncAction(() => api.save(draft));

<StateButton state={state} onClick={run} successLabel="Saved">
  Save changes
</StateButton>
"use client";

import { Button, type ButtonProps } from "./Button";
import { Spinner } from "./Spinner";
import { cn } from "@/lib/cn";
import type { ActionState } from "./useAsyncAction";

export interface StateButtonProps extends Omit<ButtonProps, "children"> {
  state?: ActionState;
  children: React.ReactNode;
  loadingLabel?: React.ReactNode;
  successLabel?: React.ReactNode;
  errorLabel?: React.ReactNode;
  /** Collapse to an icon-only pill while loading. */
  collapse?: boolean;
  icon?: React.ReactNode;
}

/**
 * A button whose label swaps with its async state. Every state is rendered in
 * the same grid cell so the button never resizes mid-transition — the usual
 * cause of layout jitter in loading buttons.
 */
export function StateButton({
  state = "idle",
  children,
  loadingLabel,
  successLabel = "Done",
  errorLabel = "Try again",
  collapse = false,
  icon,
  variant = "solid",
  className,
  disabled,
  ...rest
}: StateButtonProps) {
  const busy = state === "loading";

  const faces: Record<ActionState, React.ReactNode> = {
    idle: (
      <>
        {icon}
        {children}
      </>
    ),
    loading: (
      <>
        <Spinner size={15} />
        {!collapse && (loadingLabel ?? children)}
      </>
    ),
    success: (
      <>
        <CheckIcon />
        {!collapse && successLabel}
      </>
    ),
    error: (
      <>
        <AlertIcon />
        {!collapse && errorLabel}
      </>
    ),
  };

  return (
    <Button
      variant={state === "error" ? "danger" : variant}
      aria-busy={busy}
      aria-live="polite"
      disabled={disabled || busy}
      className={cn(
        "inline-grid transition-[width,background-color] duration-300",
        collapse && busy && "w-11 px-0",
        state === "success" && "bg-positive! text-white!",
        className,
      )}
      {...rest}
    >
      {(Object.keys(faces) as ActionState[]).map((face) => (
        <span
          key={face}
          aria-hidden={face !== state}
          className={cn(
            "col-start-1 row-start-1 flex items-center justify-center gap-2 whitespace-nowrap",
            "transition-all duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]",
            face === state
              ? "translate-y-0 opacity-100 blur-0"
              : "pointer-events-none -translate-y-1.5 opacity-0 blur-[2px]",
          )}
        >
          {faces[face]}
        </span>
      ))}
    </Button>
  );
}

function CheckIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden className="animate-pop">
      <path
        d="M3.5 8.5l3 3 6-7"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function AlertIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden className="animate-pop">
      <path d="M8 4.5v4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
      <circle cx="8" cy="11.2" r="1" fill="currentColor" />
    </svg>
  );
}

export default StateButton;