# Inline confirmation morph

> An action unfolds into an inline question, then reports a local or host-managed result with an undo event.

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

## Use when
- Archiving or removing a local item needs a clear second step
- A host action can report pending, completion and failure through callbacks

## Avoid when
- Use dialog when consequences need a longer explanation
- Use hold-to-confirm when the intended confirmation is a deliberate hold

## Alternatives
- [hold-to-confirm](https://hazeui.com/ui/hold-to-confirm.md)
- [dialog](https://hazeui.com/ui/dialog.md)
- [stateful-button](https://hazeui.com/ui/stateful-button.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller-supplied prefix for this component and its related elements. |
| label | `string` | "Archive draft" | no | Resting action label. |
| prompt | `string` | "Archive this draft?" | no | Inline confirmation question. |
| confirmLabel | `string` | "Archive" | no | Text on the explicit confirmation button. |
| successLabel | `string` | "Draft archived" | no | Local result text after confirmation. |
| pendingLabel | `string` | "Archiving…" | no | Busy text shown when the host calls pending. |
| undoLabel | `string` | "Undo" | no | Result action that dispatches haze:undo. |
| form | `string` |  | no | Optional external form ID; confirm uses native submission instead of the local result. |
| name | `string` | id | no | Name submitted by the confirm button. |
| value | `string` | "confirmed" | no | Value submitted by the confirm button. |
| class | `string` |  | no | Additional classes for the component root. |

## Accessibility
- Native details exposes the second confirmation step with no script; a form prop enables ordinary submission.
- Enhanced opening focuses Confirm and rejects activation during the first 300 ms to guard against accidental double presses.
- haze:confirm provides pending, complete and fail callbacks; the host implements the real operation and haze:undo reversal.
- Key Enter, Space: Open the question or activate its focused answer.
- Key Escape: Cancel the open question and restore focus to the action.

## Agent prompts

### Install and use

Install the Haze UI component "Inline confirmation morph" with `npx shadcn@latest add @haze/confirm-morph`. 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 ConfirmMorph from "@/components/haze/ui/confirm-morph.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/confirm-morph.md

### Customize with real content

Adapt the Haze confirm-morph ui for our product. Replace the demo values of these props with our real content: id, label, prompt, confirmLabel, successLabel, pendingLabel, undoLabel, form, name, value, class. Keep the layout, the heading level rules and these accessibility details: Native details exposes the second confirmation step with no script; a form prop enables ordinary submission. Enhanced opening focuses Confirm and rejects activation during the first 300 ms to guard against accidental double presses. haze:confirm provides pending, complete and fail callbacks; the host implements the real operation and haze:undo reversal. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using confirm-morph, check it fits: use it when archiving or removing a local item needs a clear second step; a host action can report pending, completion and failure through callbacks. Avoid it when use dialog when consequences need a longer explanation; use hold-to-confirm when the intended confirmation is a deliberate hold. Alternatives: @haze/hold-to-confirm, @haze/dialog, @haze/stateful-button.

## Example requests that should lead here
- Add an inline archive confirmation with a pending callback and an Undo event.

## Source

```astro
---
import { Check, LoaderCircle } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id: string;
  label?: string;
  prompt?: string;
  confirmLabel?: string;
  successLabel?: string;
  pendingLabel?: string;
  undoLabel?: string;
  form?: string;
  name?: string;
  value?: string;
  class?: string;
}

const { id, label = "Archive draft", prompt = "Archive this draft?", confirmLabel = "Archive", successLabel = "Draft archived", pendingLabel = "Archiving…", undoLabel = "Undo", form, name = id, value = "confirmed", class: className } = Astro.props;
const key = "inline-flex h-6 shrink-0 cursor-pointer items-center justify-center rounded-md px-2.5 text-[0.8125rem]/5 font-medium whitespace-nowrap transition-[background-color,color,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
const face = "[[data-haze-confirm-morph][data-enhanced]_&]:absolute [[data-haze-confirm-morph][data-enhanced]_&]:top-0 [[data-haze-confirm-morph][data-enhanced]_&]:left-0 [[data-haze-confirm-morph][data-enhanced]_&]:w-max motion-safe:[[data-haze-confirm-morph][data-enhanced]_&]:transition-[opacity,translate] motion-safe:[[data-haze-confirm-morph][data-enhanced]_&]:duration-200 motion-safe:[[data-haze-confirm-morph][data-enhanced]_&]:ease-snappy";
---

<div id={id} data-haze-confirm-morph data-state="idle" data-pending-label={pendingLabel} data-success-label={successLabel} data-undo-label={undoLabel} data-form-action={Boolean(form)} class={cn("grid min-w-0 justify-items-start gap-2", className)}>
  <details data-confirm-disclosure class="group relative max-w-full overflow-clip rounded-lg border border-border bg-field text-foreground hover:border-border-strong motion-safe:transition-[width,height,border-color] motion-safe:duration-200 motion-safe:ease-snappy [&[hidden]]:hidden [[data-enhanced]_&]:h-8">
    <summary data-confirm-face="idle" class={cn(key, "h-8 list-none rounded-lg px-3 hover:bg-accent [&::-webkit-details-marker]:hidden", face, "[[data-state=confirming]_&]:pointer-events-none [[data-state=confirming]_&]:-translate-x-1.5 [[data-state=confirming]_&]:opacity-0")}>{label}</summary>
    <div data-confirm-face="confirm" role="group" aria-labelledby={`${id}-question`} class={cn("group/face flex items-center gap-1 p-1 data-[wrap]:flex-wrap", face, "[[data-haze-confirm-morph][data-enhanced]:not([data-state=confirming])_&]:pointer-events-none [[data-haze-confirm-morph][data-enhanced]:not([data-state=confirming])_&]:translate-x-1.5 [[data-haze-confirm-morph][data-enhanced]:not([data-state=confirming])_&]:opacity-0")}>
      <span id={`${id}-question`} class="min-w-0 truncate ps-2 pe-1 text-[0.8125rem]/5 font-medium group-data-[wrap]/face:basis-full group-data-[wrap]/face:py-0.5">{prompt}</span>
      <button data-confirm-yes type={form ? "submit" : "button"} form={form} name={name} value={value} class={cn(key, "text-foreground hover:bg-accent")}>{confirmLabel}</button>
      <button data-confirm-cancel type="button" hidden class={cn(key, "text-muted-foreground hover:bg-accent hover:text-foreground [&[hidden]]:hidden")}>Cancel</button>
    </div>
  </details>
  <div data-confirm-result hidden class="flex h-8 max-w-full items-center gap-2 rounded-lg border border-border bg-field ps-3 pe-1 text-[0.8125rem]/5 font-medium [&[hidden]]:hidden">
    <LoaderCircle data-confirm-spinner aria-hidden="true" class="hidden size-4 shrink-0 motion-safe:animate-spin" />
    <Check data-confirm-check aria-hidden="true" class="size-4 shrink-0 text-muted-foreground motion-safe:animate-pop" />
    <span data-confirm-message class="min-w-0 truncate"></span>
    <button data-confirm-undo type="button" class={cn(key, "text-muted-foreground hover:bg-accent hover:text-foreground")}>{undoLabel}</button>
  </div>
  <span data-confirm-status role="status" class="sr-only"></span>
</div>

<script>
  function initConfirmMorphs() {
    document.querySelectorAll<HTMLElement>("[data-haze-confirm-morph]").forEach(root => {
      if (root.hasAttribute("data-enhanced")) return;
      const disclosure = root.querySelector<HTMLDetailsElement>("[data-confirm-disclosure]");
      const trigger = disclosure?.querySelector("summary");
      const yes = root.querySelector<HTMLButtonElement>("[data-confirm-yes]");
      const cancel = root.querySelector<HTMLButtonElement>("[data-confirm-cancel]");
      const result = root.querySelector<HTMLElement>("[data-confirm-result]");
      const undo = root.querySelector<HTMLButtonElement>("[data-confirm-undo]");
      const message = root.querySelector<HTMLElement>("[data-confirm-message]");
      const status = root.querySelector<HTMLElement>("[data-confirm-status]");
      if (!disclosure || !trigger || !yes || !cancel || !result || !undo || !message || !status) return;
      root.setAttribute("data-enhanced", "");
      let openedAt = 0;
      let revision = 0;
      let busy = false;
      let lastState = "";
      const faces = { idle: trigger as HTMLElement, confirm: root.querySelector<HTMLElement>("[data-confirm-face='confirm']")! };
      const fit = () => {
        const next = root.dataset.state === "confirming" ? faces.confirm : faces.idle;
        const cap = Math.max(root.clientWidth - 2, 0);
        next.style.maxWidth = "";
        next.toggleAttribute("data-wrap", false);
        const wrap = next === faces.confirm && cap > 0 && next.offsetWidth > cap;
        next.toggleAttribute("data-wrap", wrap);
        next.style.maxWidth = cap ? `${cap}px` : "";
        disclosure.style.width = `${Math.min(next.offsetWidth + 2, cap + 2)}px`;
        disclosure.style.height = wrap ? `${next.offsetHeight + 2}px` : "";
        faces.idle.inert = next !== faces.idle;
        faces.confirm.inert = next !== faces.confirm;
      };
      const setConfirming = (on: boolean) => { root.dataset.state = on ? "confirming" : "idle"; fit(); };
      const reset = () => { revision++; busy = false; result.hidden = true; disclosure.hidden = false; setConfirming(false); trigger.focus(); };
      const show = (state: "pending" | "success" | "error", text: string) => {
        disclosure.hidden = true;
        result.hidden = false;
        busy = state === "pending";
        lastState = state;
        result.setAttribute("aria-busy", String(busy));
        const spinner = root.querySelector<HTMLElement>("[data-confirm-spinner]");
        const check = root.querySelector<HTMLElement>("[data-confirm-check]");
        spinner?.classList.toggle("hidden", !busy);
        check?.classList.toggle("hidden", state !== "success");
        undo.hidden = busy;
        undo.textContent = state === "error" ? "Try again" : root.dataset.undoLabel ?? "Undo";
        message.textContent = text;
        status.textContent = text;
        result.tabIndex = -1;
        if (busy) result.focus(); else undo.focus();
        if (!matchMedia("(prefers-reduced-motion: reduce)").matches) result.animate([{ opacity: .5, translate: "0 3px" }, { opacity: 1, translate: "0 0" }], { duration: 200 });
      };
      // Enhanced: the disclosure stays open and the morph is driven by data-state, so the width can animate.
      disclosure.open = true;
      trigger.addEventListener("click", event => {
        event.preventDefault();
        setConfirming(true);
        openedAt = performance.now();
        status.textContent = root.querySelector("[id$='-question']")?.textContent ?? "";
        yes.focus();
      });
      disclosure.style.transitionDuration = "0ms";
      fit();
      requestAnimationFrame(() => { disclosure.style.transitionDuration = ""; });
      document.fonts?.ready.then(fit);
      addEventListener("resize", fit);
      cancel.hidden = false;
      cancel.addEventListener("click", reset);
      disclosure.addEventListener("keydown", event => {
        if (event.repeat && event.key === "Enter") event.preventDefault();
      });
      // Escape works wherever focus is (the document listener below forwards it here).
      root.addEventListener("haze:confirm-escape", () => { if (root.dataset.state === "confirming" && !busy) reset(); });
      yes.addEventListener("click", event => {
        if (busy || performance.now() - openedAt < 300) { event.preventDefault(); return; }
        if (root.dataset.formAction === "true") return;
        const current = ++revision;
        let managed = false;
        let settled = false;
        const settle = (state: "success" | "error", text?: string) => {
          if (current !== revision || settled) return;
          settled = true;
          show(state, text ?? (state === "success" ? root.dataset.successLabel ?? "Done" : "Could not complete the action."));
        };
        root.dispatchEvent(new CustomEvent("haze:confirm", { bubbles: true, detail: { pending: () => { if (settled) return; managed = true; show("pending", root.dataset.pendingLabel ?? "Working…"); }, complete: (text?: string) => settle("success", text), fail: (text?: string) => settle("error", text) } }));
        if (!managed && !settled) settle("success");
      });
      undo.addEventListener("click", () => {
        if (lastState === "success") root.dispatchEvent(new CustomEvent("haze:undo", { bubbles: true }));
        status.textContent = lastState === "success" ? "Action undone." : "Ready to try again.";
        reset();
      });
    });
  }
  initConfirmMorphs();
  if (!document.documentElement.hasAttribute("data-haze-confirm-morph-listener")) {
    document.documentElement.setAttribute("data-haze-confirm-morph-listener", "");
    document.addEventListener("astro:page-load", initConfirmMorphs);
    document.addEventListener("keydown", event => {
      if (event.key !== "Escape" || event.defaultPrevented) return;
      const open = document.querySelectorAll<HTMLElement>("[data-haze-confirm-morph][data-state=confirming]");
      if (!open.length) return;
      event.preventDefault();
      open.forEach(root => root.dispatchEvent(new CustomEvent("haze:confirm-escape")));
    });
  }
</script>
```
