# Stateful Button

> Keeps an action button in place as its icon and status message show pending, success, or error.

- Kind: ui · Category: Actions · Interactivity: script
- Install: `npx shadcn@latest add @haze/stateful-button`
- File: `src/components/haze/ui/stateful-button.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/utils
- Docs page: https://hazeui.com/ui/stateful-button

## Use when
- A save or publish action takes time and has a result to report.
- The button should retain focus during an async request.

## Avoid when
- A click simply navigates to a page.

## Alternatives
- [button](https://hazeui.com/ui/button.md)
- [spinner](https://hazeui.com/ui/spinner.md)
- [alert](https://hazeui.com/ui/alert.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique ID for the root element whose data-state is updated by the caller. |
| label | `string` | Save changes | no | Stable visible and accessible label for the action. |
| type | `"button" \| "submit"` | button | no | Native button behavior. |
| variant | `"primary" \| "secondary" \| "outline" \| "soft"` | primary | no | Button variant. |
| pendingMessage | `string` |  | no | Live message while the action is pending. |
| successMessage | `string` |  | no | Live message after success. |
| errorMessage | `string` |  | no | Live message after failure. |
| class | `string` |  | no | Classes for the button and status wrapper. |

## Accessibility
- Set data-state on the root to idle, pending, success, or error from the action handler.
- Pending blocks further activation while the status is announced separately.
- Key Enter / Space: Activate the focused button when the action is available.

## Agent prompts

### Install and use

Install the Haze UI component "Stateful Button" with `npx shadcn@latest add @haze/stateful-button`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import StatefulButton from "@/components/haze/ui/stateful-button.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/stateful-button.md

### Customize with real content

Adapt the Haze stateful-button ui for our product. Replace the demo values of these props with our real content: id, label, type, variant, pendingMessage, successMessage, errorMessage, class. Keep the layout, the heading level rules and these accessibility details: Set data-state on the root to idle, pending, success, or error from the action handler. Pending blocks further activation while the status is announced separately. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using stateful-button, check it fits: use it when a save or publish action takes time and has a result to report.; the button should retain focus during an async request.. Avoid it when a click simply navigates to a page.. Alternatives: @haze/button, @haze/spinner, @haze/alert.

## Example requests that should lead here
- Give the save button a spinner, a confirmation check, and an error state.
- Keep focus on a profile action while the request runs.

## Source

```astro
---
import { Check, CircleAlert, LoaderCircle } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";

interface Props {
  id: string;
  label?: string;
  type?: "button" | "submit";
  variant?: "primary" | "secondary" | "outline" | "soft";
  pendingMessage?: string;
  successMessage?: string;
  errorMessage?: string;
  class?: string;
  [key: string]: unknown;
}

const {
  id, label = "Save changes", type = "button", variant = "primary", pendingMessage = "Saving…",
  successMessage = "Changes saved.", errorMessage = "Save failed. Try again.", class: className, ...rest
} = Astro.props;
---

<div id={id} data-haze-stateful-button data-state="idle" data-pending={pendingMessage}
  data-success={successMessage} data-error={errorMessage} class={cn("group inline-grid min-w-0 justify-items-start gap-2", className)}>
  <Button {...rest} type={type} variant={variant} class="max-w-full whitespace-normal text-start aria-disabled:opacity-100">
    <span class="wrap-anywhere">{label}</span>
    <span aria-hidden="true" class="relative grid size-4 shrink-0 place-items-center">
      <span class="hidden size-1.5 rounded-full bg-current opacity-90 group-data-[state=idle]:block"></span>
      <LoaderCircle class="hidden animate-spin group-data-[state=pending]:block" />
      <Check class="hidden animate-pop group-data-[state=success]:block" />
      <CircleAlert class="hidden animate-pop group-data-[state=error]:block" />
    </span>
  </Button>
  <span aria-live="polite" aria-atomic="true" data-stateful-status class="min-h-5 text-[0.8125rem]/5 text-muted-foreground group-data-[state=error]:text-destructive group-data-[state=success]:text-success"></span>
</div>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const button = root.querySelector<HTMLButtonElement>("button");
    const status = root.querySelector<HTMLElement>("[data-stateful-status]");
    if (!button || !status) return;
    const initialDisabled = button.getAttribute("aria-disabled");
    let lastState = "";
    const sync = () => {
      const state = root.dataset.state ?? "idle";
      if (state === lastState) return;
      lastState = state;
      const busy = state === "pending";
      if (busy) button.setAttribute("aria-disabled", "true");
      else if (initialDisabled !== null) button.setAttribute("aria-disabled", initialDisabled);
      else button.removeAttribute("aria-disabled");
      button.setAttribute("aria-busy", String(busy));
      const messages: Record<string, string | undefined> = {
        pending: root.dataset.pending, success: root.dataset.success, error: root.dataset.error,
      };
      status.textContent = messages[state] ?? "";
    };
    button.addEventListener("click", (event) => {
      if (root.dataset.state !== "pending" && button.getAttribute("aria-disabled") !== "true") return;
      event.preventDefault();
      event.stopImmediatePropagation();
    }, { capture: true });
    const observer = new MutationObserver(sync);
    observer.observe(root, { attributes: true, attributeFilter: ["data-state"] });
    sync();
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-stateful-button]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-stateful-button-listener")) {
    document.documentElement.setAttribute("data-haze-stateful-button-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
