# Action button

Buttons that show their own work, so the page needs no toast: Save to Saving to Saved, Upload that fills its own glass, and Generate that becomes its own Stop with the elapsed time.

Tier: free. Type: component. Category: actions. Tags: motion.

## Install

```bash
npx shadcn@latest add @pixilui/action-button
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/action-button.tsx`.

## Preview

Live preview: https://pixilui.com/components/action-button

Knobs:

- `show`: `styles`, `more`, `sizes`, `states`

Signature: Save changes becomes Saving with a ring, then Saved with a check that draws itself, and the button never changes width.

Styles: `quiet` (default), `lively`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: quiet https://pixilui.com/r/standalone/action-button.tsx, lively https://pixilui.com/r/standalone/action-button.lively.tsx.

## Code

`components/pixilui/action-button.tsx`

```tsx
"use client";

import { forwardRef, useCallback, useEffect, useRef, useState, type ChangeEvent, type MouseEvent, type ReactNode } from "react";
import { Button, ButtonStopIcon, type ButtonProps, type ButtonSize, type ButtonVariant } from "./button";

/*
  Buttons that show their own work, so the page needs no toast. Three forms, one file, all on the
  locked button's own face swap, fill and drawn check (button.tsx, foundation.css section 7);
  each holds the widest of its labels with `reserve`, so the width never moves.

  ActionButton          Save changes, then Saving with the ring, then Saved with a drawn check.
  ActionButtonUpload    Upload, then Uploading as the button fills its own glass, then Uploaded.
  ActionButtonGenerate  Generate, then a glass Stop with the shimmering label and an m:ss timer.
*/

/* ------------------------------------------------------------ ActionButton: save, send, approve */

const SAVE_RESET_MS = 1500;

export type ActionButtonStatus = "idle" | "pending" | "done" | "error";

export type ActionButtonProps = Omit<ButtonProps, "children" | "loading" | "done" | "reserve" | "onError"> & {
  /** The work. Return a promise and the button shows Saving until it settles, then Saved. */
  onAction: () => void | Promise<void>;
  /** The label at rest. */
  label?: string;
  /** The label while the work runs, beside the ring. */
  pendingLabel?: string;
  /** The label once the work lands, beside the drawn check. */
  doneLabel?: string;
  /** Visual weight, as on Button. primary is the default: this is usually the surface's main action. */
  variant?: ButtonVariant;
  /** Height, as on Button: xs 24, sm 28, md 32 (default), lg 36, xl 44. */
  size?: ButtonSize;
  /** How long the done label shows before the button returns to rest, in ms. */
  resetAfter?: number;
  /** Runs when onAction rejects. The button returns to rest with data-status="error". */
  onError?: (error: Error) => void;
};

/** An action button that tells its own story: label, then the pending label with a ring, then the done label with a drawn check. */
export const ActionButton = forwardRef<HTMLButtonElement, ActionButtonProps>(function ActionButton(
  { onAction, label = "Save changes", pendingLabel = "Saving", doneLabel = "Saved", variant = "primary", resetAfter = SAVE_RESET_MS, onError, onClick, ...rest },
  ref,
) {
  const [status, setStatus] = useState<ActionButtonStatus>("idle");
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const live = useRef(true);
  useEffect(() => {
    live.current = true;
    return () => {
      live.current = false;
      clearTimeout(timer.current);
    };
  }, []);

  const run = async (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented || status === "pending" || status === "done") return;
    clearTimeout(timer.current);
    setStatus("pending");
    try {
      await onAction();
      if (!live.current) return;
      setStatus("done");
      timer.current = setTimeout(() => setStatus("idle"), resetAfter);
    } catch (error) {
      if (!live.current) return;
      setStatus("error");
      onError?.(error instanceof Error ? error : new Error(String(error)));
    }
  };

  return (
    <Button
      {...rest}
      ref={ref}
      variant={variant}
      loading={status === "pending"}
      done={status === "done"}
      reserve={[label, { label: pendingLabel, icon: "spinner" }, { label: doneLabel, icon: true }]}
      data-status={status}
      onClick={(event: MouseEvent<HTMLButtonElement>) => void run(event)}
    >
      {status === "pending" ? pendingLabel : status === "done" ? doneLabel : label}
    </Button>
  );
});

/* ------------------------------------------------------------ ActionButtonUpload: a fill as it goes */

const UPLOAD_RESET_MS = 1800;

export type ActionButtonUploadStatus = "idle" | "uploading" | "done" | "error";

export type ActionButtonUploadProps = Omit<ButtonProps, "children" | "icon" | "progress" | "done" | "reserve" | "onError"> & {
  /** The upload icon (Lucide Upload, say). The check that replaces it when done is the button's own. */
  icon: ReactNode;
  /** The label at rest. */
  label?: string;
  /** The label while the fill runs. */
  progressLabel?: string;
  /** The label once the upload lands. */
  doneLabel?: string;
  /**
   * The upload. Gets the chosen files (empty when chooseFiles is false) and report, which takes
   * progress from 0 to 1 and fills the button. Return a promise; when it settles the button says done.
   */
  onUpload: (files: File[], report: (progress: number) => void) => void | Promise<void>;
  /** File types the picker offers, as on input type="file" ("image/*,.pdf"). */
  accept?: string;
  /** Lets the picker choose more than one file. */
  multiple?: boolean;
  /** true (the default) opens the file picker on press; false runs onUpload at once, for a file the app already has. */
  chooseFiles?: boolean;
  /** Visual weight, as on Button. secondary (the glass) is the default. */
  variant?: ButtonVariant;
  /** Height, as on Button: xs 24, sm 28, md 32 (default), lg 36, xl 44. */
  size?: ButtonSize;
  /** How long the done label shows before the button returns to rest, in ms. */
  resetAfter?: number;
  /** Runs when onUpload rejects. The button returns to rest with data-status="error". */
  onError?: (error: Error) => void;
};

/** A button that uploads and fills its own glass as it goes, then says Uploaded, at a width that never moves. */
export const ActionButtonUpload = forwardRef<HTMLButtonElement, ActionButtonUploadProps>(function ActionButtonUpload(
  { icon, label = "Upload", progressLabel = "Uploading", doneLabel = "Uploaded", onUpload, accept, multiple, chooseFiles = true, resetAfter = UPLOAD_RESET_MS, onError, onClick, ...rest },
  ref,
) {
  const [status, setStatus] = useState<ActionButtonUploadStatus>("idle");
  const [progress, setProgress] = useState(0);
  const input = useRef<HTMLInputElement | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const live = useRef(true);
  useEffect(() => {
    live.current = true;
    return () => {
      live.current = false;
      clearTimeout(timer.current);
    };
  }, []);

  const report = useCallback((value: number) => {
    if (live.current) setProgress(Math.max(0, Math.min(1, value)));
  }, []);

  const upload = async (files: File[]) => {
    clearTimeout(timer.current);
    setProgress(0);
    setStatus("uploading");
    try {
      await onUpload(files, report);
      if (!live.current) return;
      setProgress(1);
      setStatus("done");
      timer.current = setTimeout(() => {
        setStatus("idle");
        setProgress(0);
      }, resetAfter);
    } catch (error) {
      if (!live.current) return;
      setStatus("error");
      setProgress(0);
      onError?.(error instanceof Error ? error : new Error(String(error)));
    }
  };

  const press = (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented || status === "uploading" || status === "done") return;
    if (chooseFiles) input.current?.click();
    else void upload([]);
  };

  const picked = (event: ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files ?? []);
    event.target.value = "";
    if (files.length) void upload(files);
  };

  const busy = status === "uploading" || status === "done";
  return (
    <>
      <Button
        {...rest}
        ref={ref}
        icon={icon}
        progress={busy ? progress : 0}
        done={status === "done"}
        reserve={[
          { label, icon: true },
          { label: progressLabel, icon: true },
          { label: doneLabel, icon: true },
        ]}
        data-status={status}
        onClick={press}
      >
        {status === "done" ? doneLabel : status === "uploading" ? progressLabel : label}
      </Button>
      {chooseFiles ? <input ref={input} type="file" accept={accept} multiple={multiple} hidden tabIndex={-1} aria-hidden="true" onChange={picked} /> : null}
    </>
  );
});

/* ------------------------------------------------------------ ActionButtonGenerate: start, then stop */

const TICK_MS = 1000;

const clock = (seconds: number) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;

export type ActionButtonGenerateProps = Omit<ButtonProps, "children" | "icon" | "variant" | "reserve" | "aria-label"> & {
  /** Controlled running state. Pair with onRunningChange. */
  running?: boolean;
  /** Starting running state when uncontrolled. */
  defaultRunning?: boolean;
  /** Runs whenever the button starts or stops. */
  onRunningChange?: (running: boolean) => void;
  /** Runs on the press that starts the work. */
  onStart?: () => void | Promise<void>;
  /** Runs on the press that stops it. */
  onStop?: () => void | Promise<void>;
  /** The label at rest. */
  label?: string;
  /** The shimmering label while running, before the timer. */
  runningLabel?: string;
  /** The accessible name while running: the press stops the work. */
  stopLabel?: string;
  /** Height, as on Button: xs 24, sm 28, md 32 (default), lg 36, xl 44. */
  size?: ButtonSize;
};

/** A start button that morphs into its own stop: the primary becomes a secondary with a stop square, a shimmering label and the elapsed time. */
export const ActionButtonGenerate = forwardRef<HTMLButtonElement, ActionButtonGenerateProps>(function ActionButtonGenerate(
  { running: runningProp, defaultRunning = false, onRunningChange, onStart, onStop, label = "Generate", runningLabel = "Generating", stopLabel = "Stop generating", onClick, ...rest },
  ref,
) {
  const [own, setOwn] = useState(defaultRunning);
  const running = runningProp ?? own;
  const [seconds, setSeconds] = useState(0);
  // Each run starts again from 0:00.
  const [wasRunning, setWasRunning] = useState(running);
  if (wasRunning !== running) {
    setWasRunning(running);
    if (running) setSeconds(0);
  }

  // The timer counts while running.
  useEffect(() => {
    if (!running) return;
    const id = setInterval(() => setSeconds((s) => s + 1), TICK_MS);
    return () => clearInterval(id);
  }, [running]);

  const toggle = (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented) return;
    const next = !running;
    if (runningProp === undefined) setOwn(next);
    onRunningChange?.(next);
    void (next ? onStart?.() : onStop?.());
  };

  return (
    <Button
      {...rest}
      ref={ref}
      variant={running ? "secondary" : "primary"}
      icon={running ? <ButtonStopIcon /> : undefined}
      aria-label={running ? stopLabel : undefined}
      reserve={[label, { label: `${runningLabel} 0:12`, icon: true }]}
      data-status={running ? "running" : "idle"}
      onClick={toggle}
    >
      {running ? (
        <span>
          <span className="pixilui-btn-shimmer">{runningLabel}</span> <span className="pixilui-btn-timer">{clock(seconds)}</span>
        </span>
      ) : (
        label
      )}
    </Button>
  );
});
```

## Usage

When to use:

- An action that takes a moment and lands: save, send, publish, approve. Use ActionButton.
- Sending a file, where the progress belongs on the button that started it. Use ActionButtonUpload.
- Starting work a person may want to stop: generating, summarizing, running an eval. Use ActionButtonGenerate.

When not to use:

- Work that runs longer than a minute or in the background: show it in a run timeline, not on a button.
- A destructive action: use Confirm button.
- Copying text: use Copy button, which has its own drawn check.

```tsx
import type { ReactNode } from "react";
import { IconExport } from "@/components/pixilui/icons/export";
import { IconUpload } from "@/components/pixilui/icons/upload";
import { ActionButton, ActionButtonGenerate, ActionButtonUpload } from "@/components/pixilui/action-button";

// The item page's one row, Show: Styles, More styles, Icons and sizes, States (the button pages' layout).
export const knobs = {
  show: ["styles", "more", "sizes", "states"],
} as const;

const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
const fail = (ms: number) => new Promise<void>((_, reject) => setTimeout(() => reject(new Error("The CRM refused the update")), ms));

/** Ten steps of 140ms, like a small file on a good connection. */
const simulate = (_files: File[], report: (progress: number) => void) =>
  new Promise<void>((resolve) => {
    let step = 0;
    const id = setInterval(() => {
      step += 1;
      report(step / 10);
      if (step >= 10) {
        clearInterval(id);
        resolve();
      }
    }, 140);
  });

const Row = ({ children }: { children: ReactNode }) => <div className="flex flex-wrap items-center justify-center gap-2.5">{children}</div>;
const Cap = ({ children }: { children: ReactNode }) => <p className="-mt-2 text-center text-caption text-muted">{children}</p>;

function Shown({ show }: { show: string }) {
  if (show === "more")
    return (
      <>
        <Row>
          <ActionButtonGenerate />
          <ActionButtonGenerate label="Summarize thread" runningLabel="Summarizing" stopLabel="Stop summarizing" />
        </Row>
        <Cap>Generate becomes its own Stop, with the time it has run</Cap>
      </>
    );
  if (show === "sizes")
    return (
      <>
        <Row>
          <ActionButtonUpload size="sm" icon={<IconUpload />} chooseFiles={false} onUpload={simulate} />
          <ActionButtonUpload icon={<IconUpload />} chooseFiles={false} onUpload={simulate} />
          <ActionButtonUpload size="lg" variant="secondary-2" icon={<IconExport />} label="Upload report" progressLabel="Uploading report" doneLabel="Report uploaded" chooseFiles={false} onUpload={simulate} />
        </Row>
        <Cap>Upload fills its own glass as the file goes up: 28, 32, 36</Cap>
      </>
    );
  if (show === "states")
    return (
      <>
        <Row>
          <ActionButton label="Sync contacts" pendingLabel="Syncing" doneLabel="Synced" onAction={() => fail(1200)} />
          <ActionButton variant="secondary" label="Publish" pendingLabel="Publishing" doneLabel="Published" aria-disabled="true" onAction={() => wait(900)} />
        </Row>
        <Cap>When the work fails, the button returns to rest with data-status error; disabled stays focusable</Cap>
      </>
    );
  return (
    <>
      <Row>
        <ActionButton size="lg" onAction={() => wait(1100)} />
        <ActionButton variant="secondary" size="lg" label="Send invoice" pendingLabel="Sending" doneLabel="Sent" onAction={() => wait(1400)} />
        <ActionButton variant="secondary-2" size="lg" label="Approve" pendingLabel="Approving" doneLabel="Approved" onAction={() => wait(900)} />
      </Row>
      <Cap>Press one: the ring, then a check that draws itself, at a width that never moves</Cap>
    </>
  );
}

export default function ActionButtonDemo({ show = "styles" }: KnobValues<typeof knobs>) {
  return (
    <div key={show} className="grid justify-items-center gap-4.5" aria-live="polite">
      <Shown show={show} />
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `variant` | `ButtonVariant` | `"primary"` | Visual weight, as on Button. primary is the default: this is usually the surface's main action. |
| `size` | `ButtonSize` |  | Height, as on Button: xs 24, sm 28, md 32 (default), lg 36, xl 44. |
| `onAction` (required) | `() => void \| Promise<void>` |  | The work. Return a promise and the button shows Saving until it settles, then Saved. |
| `label` | `string` | `"Save changes"` | The label at rest. |
| `pendingLabel` | `string` | `"Saving"` | The label while the work runs, beside the ring. |
| `doneLabel` | `string` | `"Saved"` | The label once the work lands, beside the drawn check. |
| `resetAfter` | `number` | `SAVE_RESET_MS` | How long the done label shows before the button returns to rest, in ms. |
| `onError` | `(error: Error) => void` |  | Runs when onAction rejects. The button returns to rest with data-status="error". |

## Keyboard

- `Tab`: Moves focus to the button; focus stays on it while the work runs and when it lands.
- `Enter`: Runs the action (or opens the file picker, or starts and stops the generation).
- `Space`: Same as Enter, on release.

## Accessibility

- A native button. While the work runs it sets aria-busy and aria-disabled, never disabled, so focus survives.
- The label itself changes (Saving, Uploaded, Stop generating), so a screen reader hears the state when it reads the button again.
- The upload's file input is hidden and out of the tab order; the button opens it.
- data-status is idle, pending, uploading, running, done or error, for styling and tests.

## Motion

- Each label cross-fades: the old leaves 5px up in 110ms, the new arrives from 5px below out of a 2px blur in 200ms, 70ms later.
- Saved and Uploaded draw their check in 260ms; the button returns to rest after resetAfter.
- The upload fill grows across the glass as report is called and fades when done.
- Generate swaps the accent for the glass in 150ms; the running label shimmers, linear, and the timer counts each second.
- reserve holds the widest label of each form, so the width never animates. Reduced motion: labels change at once, no draw, shimmer or eased fill.

## Responsive

- Never wider than its container. Pass block to fill a narrow form. The timer uses tabular figures, so it never jitters.

## Performance

- One timer per button, cleared on unmount. Progress is one CSS variable; report can run on every progress event.

## Notes for AI

- ActionButton: pass the work as onAction and return its promise; it shows pending and done on its own. A rejection returns it to rest with data-status="error" and calls onError.
- Change label, pendingLabel and doneLabel together and keep them short verbs: Publish, Publishing, Published.
- ActionButtonUpload: pass onUpload(files, report), call report with 0 to 1 as bytes go out, and return the promise. chooseFiles={false} when the app already has the file.
- ActionButtonGenerate: uncontrolled with onStart and onStop; when the work ends on its own, control it with running and onRunningChange.
- Pass icons as props (icon); never import an icon library inside the component. Keep one primary per surface.

## Related

- [Button](https://pixilui.com/components/button/markdown): The PixilUI button in four main styles and four more, five sizes from 24 to 44, with icons, loading, disabled, a count and a shortcut.
- [Confirm button](https://pixilui.com/components/confirm-button/markdown): Destructive actions that a slip cannot trigger: hold until the fill crosses, or press twice while the button is armed. The plain Destructive and quiet Revoke styles sit beside them.
- [Copy button](https://pixilui.com/components/copy-button/markdown): A button that copies a link, an ID or a snippet and says so: the icon swaps to a check that draws itself and the label to Copied, at a width that never moves.
