Stateful Button
Keeps an action button in place as its icon and status message show pending, success, or error.
pnpm dlx shadcn@latest add @haze/stateful-button---
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>When to use
- A save or publish action takes time and has a result to report.
- The button should retain focus during an async request.
When not to use
- A click simply navigates to a page.
Installation
Add the Haze registry to components.json once, then install Stateful Button with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/stateful-buttonnpx shadcn@latest add @haze/stateful-buttonyarn dlx shadcn@latest add @haze/stateful-buttonbunx --bun shadcn@latest add @haze/stateful-buttonFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique ID for the root element whose data-state is updated by the caller. |
| label | string | Save changes | Stable visible and accessible label for the action. |
| type | "button" | "submit" | button | Native button behavior. |
| variant | "primary" | "secondary" | "outline" | "soft" | primary | Button variant. |
| pendingMessage | string | – | Live message while the action is pending. |
| successMessage | string | – | Live message after success. |
| errorMessage | string | – | Live message after failure. |
| class | string | – | Classes for the button and status wrapper. |
Keyboard interactions
- EnterSpace
- Activate the focused button when the action is available.
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.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
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": "http://localhost:4329/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: http://localhost:4329/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.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.