# AI send with undo

> In-chat editable email draft with 5-second countdown progress bar, Undo cancellation, and collapsible sent confirmation row.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-send`
- File: `src/components/haze/blocks/ai-send.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-send

## Use when
- Letting users review and edit an AI-drafted email inside a conversation before it goes out
- Providing a visible grace period with an Undo button to prevent accidental outbound messages
- Collapsing a completed email draft into a clean single-row delivery confirmation

## Avoid when
- Offering an undo action for a generic page-level mutation outside chat; use undo-toast
- Composing rich multi-attachment threads or inbox replies; build a dedicated mail composer

## Alternatives
- [undo-toast](https://hazeui.com/ui/undo-toast.md)
- [ai-checkout](https://hazeui.com/blocks/ai-checkout.md)
- [ai-schedule](https://hazeui.com/blocks/ai-schedule.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-send" | no | Unique prefix for field label associations and heading IDs. |
| heading | `string` | "Email draft with undo" | no | Screen-reader section heading for landmark navigation. |
| userPrompt | `string` | "Let Devon know the launch review moved to Thursday at 2" | no | User message requesting the email draft. |
| assistantReply | `string` | "Here's a draft. Change anything you like before it goes." | no | Assistant reply introducing the editable email card. |
| recipient | `string` | "Devon Park <devon@kiteworks.io>" | no | Initial value for the editable To input. |
| subject | `string` | "Launch review moved to Thursday" | no | Initial value for the editable Subject input. |
| body | `string` | "Hi Devon, ..." | no | Initial message content for the editable textarea. |
| sender | `string` | "nora@kiteworks.io" | no | Sender email address displayed in the draft footer. |
| undoSeconds | `number` | 5 | no | Duration in seconds for the undo countdown window. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- The To, Subject, and Message inputs carry explicit label elements, and pressing Send moves keyboard focus directly to the Undo button during the countdown.
- Countdown progress exposes role="progressbar" with live aria-valuenow updates and switches to discrete one-second steps when prefers-reduced-motion is active.
- Key Tab: Move through To, Subject, Message fields, Send, Undo during countdown, and Draft again after delivery
- Key Enter / Space: Start the send countdown, cancel delivery with Undo, or reopen the draft

## Agent prompts

### Install and use

Install the Haze UI block "AI send with undo" with `npx shadcn@latest add @haze/ai-send`. 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 AiSend from "@/components/haze/blocks/ai-send.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/blocks/ai-send.md

### Customize with real content

Adapt the Haze ai-send block for our product. Replace the demo values of these props with our real content: id, heading, userPrompt, assistantReply, recipient, subject, body, sender, undoSeconds, class. Keep the layout, the heading level rules and these accessibility details: The To, Subject, and Message inputs carry explicit label elements, and pressing Send moves keyboard focus directly to the Undo button during the countdown. Countdown progress exposes role="progressbar" with live aria-valuenow updates and switches to discrete one-second steps when prefers-reduced-motion is active. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-send, check it fits: use it when letting users review and edit an ai-drafted email inside a conversation before it goes out; providing a visible grace period with an undo button to prevent accidental outbound messages; collapsing a completed email draft into a clean single-row delivery confirmation. Avoid it when offering an undo action for a generic page-level mutation outside chat; use undo-toast; composing rich multi-attachment threads or inbox replies; build a dedicated mail composer. Alternatives: @haze/undo-toast, @haze/ai-checkout, @haze/ai-schedule.

## Example requests that should lead here
- Create an AI in-chat email draft card with editable To, Subject, and body fields plus a 5-second Undo countdown before sending
- Build an assistant outbound message approval block that folds into a Sent confirmation row with a Draft again button

## Source

```astro
---
import { Check, Mail, RotateCcw, Send, Undo2 } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id?: string;
  heading?: string;
  userPrompt?: string;
  assistantReply?: string;
  recipient?: string;
  subject?: string;
  body?: string;
  sender?: string;
  undoSeconds?: number;
  class?: string;
}

const {
  id = "haze-ai-send",
  heading = "Email draft with undo",
  userPrompt = "Let Devon know the launch review moved to Thursday at 2",
  assistantReply = "Here's a draft. Change anything you like before it goes.",
  recipient = "Devon Park <devon@kiteworks.io>",
  subject = "Launch review moved to Thursday",
  body = "Hi Devon,\n\nQuick heads up: the launch review is now Thursday at 2pm, same room. QA needs the extra day to finish the final sweep.\n\nThanks,\nNora",
  sender = "nora@kiteworks.io",
  undoSeconds = 5,
  class: className,
} = Astro.props;

const safeSeconds = Math.max(2, Math.min(15, Math.round(undoSeconds)));
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-send
  data-undo-seconds={String(safeSeconds)}
  class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
  <h2 id={`${id}-title`} class="sr-only">{heading}</h2>

  <div class="mx-auto max-w-md space-y-3.5">
    <div class="flex justify-end">
      <p class="max-w-[85%] rounded-2xl bg-muted px-4 py-2.5 text-sm/5 text-foreground">
        {userPrompt}
      </p>
    </div>

    <p class="text-[0.9375rem]/6 text-pretty text-foreground">
      {assistantReply}
    </p>

    <form data-snd-card class="overflow-hidden rounded-2xl border border-border bg-card">
      <div class="divide-y divide-border px-5">
        <div class="flex flex-wrap items-center gap-x-3 gap-y-1 py-3 sm:flex-nowrap">
          <label for={`${id}-to`} class="w-14 shrink-0 text-sm/5 text-muted-foreground">To</label>
          <input
            id={`${id}-to`}
            type="text"
            data-snd-to
            value={recipient}
            autocomplete="off"
            class="-m-px border border-frame-input min-w-0 flex-1 rounded-md bg-transparent py-0.5 text-sm/5 text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden disabled:opacity-60"
          />
        </div>

        <div class="flex flex-wrap items-center gap-x-3 gap-y-1 py-3 sm:flex-nowrap">
          <label for={`${id}-subject`} class="w-14 shrink-0 text-sm/5 text-muted-foreground">Subject</label>
          <input
            id={`${id}-subject`}
            type="text"
            data-snd-subject
            value={subject}
            autocomplete="off"
            class="-m-px border border-frame-input min-w-0 flex-1 rounded-md bg-transparent py-0.5 text-sm/5 font-medium text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden disabled:opacity-60"
          />
        </div>
      </div>

      <div class="border-t border-border px-5 py-4">
        <label for={`${id}-body`} class="sr-only">Email message</label>
        <textarea
          id={`${id}-body`}
          data-snd-body
          rows="6"
          class="-m-px border border-frame-input block w-full resize-none rounded-md bg-transparent text-sm/6 text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden disabled:opacity-60"
        >{body}</textarea>
      </div>

      <div data-snd-actions class="flex flex-wrap items-center justify-between gap-3 border-t border-border px-5 py-3">
        <span class="inline-flex min-w-0 items-center gap-2 text-xs/5 text-muted-foreground">
          <Mail class="size-3.5 shrink-0" aria-hidden="true" />
          <span class="truncate">{sender}</span>
        </span>
        <button
          type="submit"
          data-snd-submit
          class="inline-flex h-9 shrink-0 cursor-pointer items-center gap-1.5 rounded-full bg-primary px-4 text-sm/5 font-medium text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-92 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97]"
        >
          Send
          <Send class="size-3.5" aria-hidden="true" />
        </button>
      </div>

      <div data-snd-countdown hidden class="space-y-2.5 border-t border-warning-border bg-warning/8 px-5 py-3">
        <div class="flex flex-wrap items-center justify-between gap-3">
          <p class="text-sm/5 text-foreground tabular-nums">
            Sending in <span data-snd-sec class="font-semibold text-warning">{safeSeconds}s</span>…
          </p>
          <button
            type="button"
            data-snd-undo
            class="inline-flex h-9 cursor-pointer items-center gap-1.5 rounded-full border border-frame-warning bg-field px-4 text-sm/5 font-medium text-warning transition-colors duration-150 ease-snappy hover:bg-warning/14 focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97]"
          >
            <Undo2 class="size-3.5" aria-hidden="true" />
            Undo
          </button>
        </div>
        <div
          role="progressbar"
          aria-label="Undo countdown remaining"
          aria-valuemin="0"
          aria-valuemax="100"
          aria-valuenow="100"
          data-snd-bar-wrap
          class="h-1.5 w-full overflow-hidden rounded-full bg-muted"
        >
          <div data-snd-bar class="h-full w-full rounded-full bg-warning"></div>
        </div>
      </div>
    </form>

    <div
      data-snd-sent
      hidden
      class="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-frame-success bg-success/8 px-4 py-3 animate-rise"
    >
      <div class="flex min-w-0 items-center gap-2.5">
        <span class="inline-flex size-6 shrink-0 items-center justify-center rounded-full bg-success/14 text-success" aria-hidden="true">
          <Check class="size-3.5" />
        </span>
        <div class="min-w-0">
          <p data-snd-sent-title class="truncate text-sm/5 font-medium text-foreground">Sent to Devon Park</p>
          <p data-snd-sent-sub class="truncate text-xs/4 text-muted-foreground">{subject} · Just now</p>
        </div>
      </div>
      <button
        type="button"
        data-snd-reset
        class="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full border border-frame bg-field px-3 text-xs/5 font-medium text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97]"
      >
        <RotateCcw class="size-3" aria-hidden="true" />
        Draft again
      </button>
    </div>

    <p data-snd-status role="status" class="sr-only"></p>
  </div>
</section>

<script>
  function initAiSends() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-send]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const totalSeconds = Math.max(2, Number(root.dataset.undoSeconds ?? 5));
      const form = root.querySelector<HTMLFormElement>("[data-snd-card]");
      const toInput = root.querySelector<HTMLInputElement>("[data-snd-to]");
      const subjectInput = root.querySelector<HTMLInputElement>("[data-snd-subject]");
      const bodyInput = root.querySelector<HTMLTextAreaElement>("[data-snd-body]");
      const actionsRow = root.querySelector<HTMLElement>("[data-snd-actions]");
      const countdownRow = root.querySelector<HTMLElement>("[data-snd-countdown]");
      const secEl = root.querySelector<HTMLElement>("[data-snd-sec]");
      const barWrap = root.querySelector<HTMLElement>("[data-snd-bar-wrap]");
      const barEl = root.querySelector<HTMLElement>("[data-snd-bar]");
      const undoBtn = root.querySelector<HTMLButtonElement>("[data-snd-undo]");
      const sentRow = root.querySelector<HTMLElement>("[data-snd-sent]");
      const sentTitle = root.querySelector<HTMLElement>("[data-snd-sent-title]");
      const sentSub = root.querySelector<HTMLElement>("[data-snd-sent-sub]");
      const resetBtn = root.querySelector<HTMLButtonElement>("[data-snd-reset]");
      const status = root.querySelector<HTMLElement>("[data-snd-status]");

      let rafId: number | undefined;
      let intervalId: number | undefined;

      const clearTimers = () => {
        if (rafId !== undefined) {
          window.cancelAnimationFrame(rafId);
          rafId = undefined;
        }
        if (intervalId !== undefined) {
          window.clearInterval(intervalId);
          intervalId = undefined;
        }
      };

      const setFieldsDisabled = (disabled: boolean) => {
        if (toInput) toInput.disabled = disabled;
        if (subjectInput) subjectInput.disabled = disabled;
        if (bodyInput) bodyInput.disabled = disabled;
      };

      const extractName = (raw: string) => {
        const trimmed = raw.trim();
        const bracketIdx = trimmed.indexOf("<");
        if (bracketIdx > 0) return trimmed.slice(0, bracketIdx).trim();
        return trimmed || "recipient";
      };

      const finishSend = () => {
        clearTimers();
        setFieldsDisabled(false);
        const recipientName = extractName(toInput?.value ?? "");
        const subjectText = subjectInput?.value.trim() || "No subject";
        if (form) form.hidden = true;
        if (actionsRow) actionsRow.hidden = false;
        if (countdownRow) countdownRow.hidden = true;
        if (sentTitle) sentTitle.textContent = `Sent to ${recipientName}`;
        if (sentSub) sentSub.textContent = `${subjectText} · Just now`;
        if (sentRow) sentRow.hidden = false;
        if (status) status.textContent = `Email sent to ${recipientName}.`;
        resetBtn?.focus();
      };

      form?.addEventListener("submit", (ev) => {
        ev.preventDefault();
        const toVal = toInput?.value.trim() ?? "";
        const subVal = subjectInput?.value.trim() ?? "";
        if (!toVal) {
          if (status) status.textContent = "Add a recipient before sending.";
          toInput?.focus();
          return;
        }
        if (!subVal) {
          if (status) status.textContent = "Add a subject line before sending.";
          subjectInput?.focus();
          return;
        }

        clearTimers();
        setFieldsDisabled(true);
        if (actionsRow) actionsRow.hidden = true;
        if (countdownRow) countdownRow.hidden = false;
        if (barEl) barEl.style.width = "100%";
        if (barWrap) barWrap.setAttribute("aria-valuenow", "100");
        if (secEl) secEl.textContent = `${totalSeconds}s`;
        if (status) status.textContent = `Sending email in ${totalSeconds} seconds. Press Undo to cancel.`;
        undoBtn?.focus();

        const durationMs = totalSeconds * 1000;
        const start = performance.now();
        const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

        if (reduced) {
          let remaining = totalSeconds;
          intervalId = window.setInterval(() => {
            remaining -= 1;
            const pct = Math.max(0, Math.round((remaining / totalSeconds) * 100));
            if (barEl) barEl.style.width = `${pct}%`;
            if (barWrap) barWrap.setAttribute("aria-valuenow", String(pct));
            if (secEl) secEl.textContent = `${Math.max(1, remaining)}s`;
            if (remaining <= 0) finishSend();
          }, 1000);
          return;
        }

        const tick = (now: number) => {
          const elapsed = now - start;
          const leftMs = Math.max(0, durationMs - elapsed);
          const pct = (leftMs / durationMs) * 100;
          const secsLeft = Math.ceil(leftMs / 1000);
          if (barEl) barEl.style.width = `${pct.toFixed(1)}%`;
          if (barWrap) barWrap.setAttribute("aria-valuenow", String(Math.round(pct)));
          if (secEl) secEl.textContent = `${Math.max(1, secsLeft)}s`;

          if (leftMs <= 0) {
            finishSend();
          } else {
            rafId = window.requestAnimationFrame(tick);
          }
        };
        rafId = window.requestAnimationFrame(tick);
      });

      undoBtn?.addEventListener("click", () => {
        clearTimers();
        setFieldsDisabled(false);
        if (countdownRow) countdownRow.hidden = true;
        if (actionsRow) actionsRow.hidden = false;
        if (barEl) barEl.style.width = "100%";
        if (status) status.textContent = "Send cancelled. Draft restored for editing.";
        bodyInput?.focus();
      });

      resetBtn?.addEventListener("click", () => {
        clearTimers();
        setFieldsDisabled(false);
        if (sentRow) sentRow.hidden = true;
        if (form) form.hidden = false;
        if (actionsRow) actionsRow.hidden = false;
        if (countdownRow) countdownRow.hidden = true;
        if (status) status.textContent = "Draft reopened for editing.";
        toInput?.focus();
      });
    });
  }

  initAiSends();
  document.addEventListener("astro:page-load", initAiSends);
</script>
```
