# AI ghost autocomplete

> Email reply composer with live ghost completion, Tab full-accept, ArrowRight word-accept, prefix matching and accessible toolbar buttons.

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

## Use when
- Offering inline AI sentence completions while composing an email, reply or support note
- Letting keyboard users accept full or word-level suggestions without leaving the textarea
- Pairing ghost completions with visible buttons and kbd hints for touch and pointer users

## Avoid when
- Users need to highlight and rewrite existing paragraphs in place; use ai-inline-rewrite instead
- You need a dropdown list of matching option items; use autocomplete instead

## Alternatives
- [ai-inline-rewrite](https://hazeui.com/blocks/ai-inline-rewrite.md)
- [ai-inline-edit](https://hazeui.com/blocks/ai-inline-edit.md)
- [autocomplete](https://hazeui.com/ui/autocomplete.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-autocomplete" | no | Unique prefix for textarea label and hint references. |
| heading | `string` | "AI ghost autocomplete" | no | Screen-reader section heading for the reply compose card. |
| recipient | `string` | "Hana Sato" | no | Recipient name shown in the compose header. |
| subject | `string` | "Re: Launch review" | no | Subject line displayed in the compose header. |
| initialText | `string` | "Thanks for the update on the " | no | Pre-filled starting draft text before the ghost suggestion. |
| suggestions | `string[]` | 3 contextual continuations | no | Ghost completion candidates users can accept or cycle through. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- Tab only intercepts focus when an active ghost suggestion is visible, preventing keyboard traps once accepted or dismissed.
- Every keyboard shortcut has a matching accessible toolbar button with kbd hints and polite role="status" feedback.
- Key Tab: Accept the entire active ghost completion
- Key ArrowRight: Accept one word at a time when the caret is at the end of the draft
- Key Escape: Dismiss the current ghost completion

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze ai-autocomplete block for our product. Replace the demo values of these props with our real content: id, heading, recipient, subject, initialText, suggestions, class. Keep the layout, the heading level rules and these accessibility details: Tab only intercepts focus when an active ghost suggestion is visible, preventing keyboard traps once accepted or dismissed. Every keyboard shortcut has a matching accessible toolbar button with kbd hints and polite role="status" feedback. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-autocomplete, check it fits: use it when offering inline ai sentence completions while composing an email, reply or support note; letting keyboard users accept full or word-level suggestions without leaving the textarea; pairing ghost completions with visible buttons and kbd hints for touch and pointer users. Avoid it when users need to highlight and rewrite existing paragraphs in place; use ai-inline-rewrite instead; you need a dropdown list of matching option items; use autocomplete instead. Alternatives: @haze/ai-inline-rewrite, @haze/ai-inline-edit, @haze/autocomplete.

## Example requests that should lead here
- Build an email reply frame with inline AI ghost autocomplete supporting Tab full-accept and ArrowRight word-by-word accept
- Create an accessible ghost completion textarea with Accept all, Next word and Cycle suggestion toolbar controls

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface Props {
  id?: string;
  heading?: string;
  recipient?: string;
  subject?: string;
  initialText?: string;
  suggestions?: string[];
  class?: string;
}

const {
  id = "haze-ai-autocomplete",
  heading = "AI ghost autocomplete",
  recipient = "Hana Sato",
  subject = "Re: Launch review",
  initialText = "Thanks for the update on the ",
  suggestions = [
    "launch timeline.",
    "rollout checklist before Thursday's release.",
    "staging latency numbers we reviewed earlier.",
  ],
  class: className,
} = Astro.props;

const firstName = recipient.split(/\s+/)[0] || "there";
const firstGhost = suggestions[0] ?? "";
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-autocomplete
  data-initial-text={initialText}
  data-suggestions={JSON.stringify(suggestions)}
  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-lg overflow-hidden rounded-2xl border border-border bg-card shadow-key transition-[color,background-color,border-color,box-shadow] duration-150 ease-snappy has-[:is(input,textarea):focus-visible]:border-ring has-[:is(input,textarea):focus-visible]:ring-3 has-[:is(input,textarea):focus-visible]:ring-ring/24">
    <div class="flex items-center gap-4 border-b border-border px-5 py-3 text-sm/5">
      <span class="w-14 shrink-0 text-muted-foreground">To</span>
      <span class="min-w-0 truncate text-foreground">{recipient}</span>
    </div>

    <div class="flex items-center gap-4 border-b border-border px-5 py-3 text-sm/5">
      <span class="w-14 shrink-0 text-muted-foreground">Subject</span>
      <span class="min-w-0 truncate text-foreground">{subject}</span>
    </div>

    <div class="px-5 pt-5 pb-4">
      <p class="mb-4 text-[0.9375rem]/7 text-foreground">Hi {firstName},</p>

      <div class="relative grid min-h-20">
        <div
          aria-hidden="true"
          class="pointer-events-none col-start-1 row-start-1 text-[0.9375rem]/7 whitespace-pre-wrap wrap-anywhere"
        >
          <span data-aa-mirror-typed class="text-transparent">{initialText}</span><span data-aa-mirror-ghost class="text-muted-foreground">{firstGhost}</span><kbd
            data-aa-inline-kbd
            class="ml-1.5 inline-block rounded-sm border border-frame bg-muted/40 px-1.5 py-0.5 align-baseline font-sans text-[0.6875rem]/4 text-muted-foreground"
          >Tab</kbd>
        </div>

        <label for={`${id}-compose`} class="sr-only">Reply message</label>
        <textarea
          id={`${id}-compose`}
          data-aa-input
          aria-describedby={`${id}-hint`}
          spellcheck="false"
          rows="3"
          class="col-start-1 row-start-1 min-h-20 w-full resize-none overflow-hidden bg-transparent text-[0.9375rem]/7 text-foreground caret-foreground outline-hidden"
        >{initialText}</textarea>
      </div>

      <p id={`${id}-hint`} class="sr-only">
        Press Tab to accept the full ghost suggestion, ArrowRight at the end of the text to accept one word, or Escape to dismiss.
      </p>

      <div class="mt-3 flex flex-wrap items-center justify-between gap-3">
        <div class="flex flex-wrap items-center gap-4">
          <button
            type="button"
            data-aa-accept-all
            class="inline-flex min-h-7 cursor-pointer items-center gap-1.5 rounded-md text-xs text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring disabled:cursor-default disabled:opacity-45"
          >
            <kbd class="rounded-sm border border-frame bg-muted/40 px-1.5 py-0.5 font-mono text-[0.6875rem]/4 text-muted-foreground">Tab</kbd>
            <span>Accept</span>
          </button>

          <button
            type="button"
            data-aa-accept-word
            class="inline-flex min-h-7 cursor-pointer items-center gap-1.5 rounded-md text-xs text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring disabled:cursor-default disabled:opacity-45"
          >
            <kbd class="rounded-sm border border-frame bg-muted/40 px-1.5 py-0.5 font-mono text-[0.6875rem]/4 text-muted-foreground">→</kbd>
            <span>Word</span>
          </button>

          <button
            type="button"
            data-aa-dismiss
            class="inline-flex min-h-7 cursor-pointer items-center gap-1.5 rounded-md text-xs text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring disabled:cursor-default disabled:opacity-45"
          >
            <kbd class="rounded-sm border border-frame bg-muted/40 px-1.5 py-0.5 font-mono text-[0.6875rem]/4 text-muted-foreground">Esc</kbd>
            <span>Dismiss</span>
          </button>
        </div>

        <button
          type="button"
          data-aa-reset
          hidden
          class="inline-flex min-h-7 cursor-pointer items-center rounded-md px-1.5 text-xs text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
        >
          Reset
        </button>
      </div>
    </div>
  </div>

  <p data-aa-status role="status" class="sr-only"></p>
</section>

<script>
  function initAiAutocomplete() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-autocomplete]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const input = root.querySelector<HTMLTextAreaElement>("[data-aa-input]");
      const mirrorTyped = root.querySelector<HTMLElement>("[data-aa-mirror-typed]");
      const mirrorGhost = root.querySelector<HTMLElement>("[data-aa-mirror-ghost]");
      const inlineKbd = root.querySelector<HTMLElement>("[data-aa-inline-kbd]");
      const acceptAllBtn = root.querySelector<HTMLButtonElement>("[data-aa-accept-all]");
      const acceptWordBtn = root.querySelector<HTMLButtonElement>("[data-aa-accept-word]");
      const dismissBtn = root.querySelector<HTMLButtonElement>("[data-aa-dismiss]");
      const resetBtn = root.querySelector<HTMLButtonElement>("[data-aa-reset]");
      const status = root.querySelector<HTMLElement>("[data-aa-status]");

      const initialText = root.dataset.initialText ?? "";
      let suggestions: string[] = [];
      try {
        suggestions = JSON.parse(root.dataset.suggestions ?? "[]") as string[];
      } catch {
        suggestions = [];
      }
      if (!suggestions.length) return;

      let anchorText = initialText;
      let suggestionIdx = 0;
      let dismissed = false;
      let activeGhost = suggestions[0] ?? "";

      const announce = (msg: string) => {
        if (status) status.textContent = msg;
      };

      const computeGhost = (typed: string): string => {
        if (dismissed) return "";
        if (!typed.startsWith(anchorText)) {
          return "";
        }
        const suffix = typed.slice(anchorText.length);
        const current = suggestions[suggestionIdx] ?? "";
        if (current.toLowerCase().startsWith(suffix.toLowerCase())) {
          return current.slice(suffix.length);
        }
        const matchedIdx = suggestions.findIndex((s) => s.toLowerCase().startsWith(suffix.toLowerCase()));
        if (matchedIdx !== -1) {
          suggestionIdx = matchedIdx;
          return suggestions[matchedIdx].slice(suffix.length);
        }
        return "";
      };

      const render = () => {
        if (!input) return;
        const val = input.value;
        activeGhost = computeGhost(val);

        if (mirrorTyped) mirrorTyped.textContent = val;
        if (mirrorGhost) mirrorGhost.textContent = activeGhost;

        const hasGhost = activeGhost.length > 0;
        if (inlineKbd) inlineKbd.hidden = !hasGhost;
        if (acceptAllBtn) acceptAllBtn.disabled = !hasGhost;
        if (acceptWordBtn) acceptWordBtn.disabled = !hasGhost;
        if (dismissBtn) dismissBtn.disabled = !hasGhost;
        if (resetBtn) resetBtn.hidden = val === initialText && !dismissed && suggestionIdx === 0;
      };

      const acceptAll = () => {
        if (!input || !activeGhost) return;
        input.value = `${input.value}${activeGhost}`;
        input.focus();
        input.setSelectionRange(input.value.length, input.value.length);
        render();
        announce("Accepted full ghost suggestion.");
      };

      const acceptNextWord = () => {
        if (!input || !activeGhost) return;
        const match = activeGhost.match(/^\s*\S+\s?/);
        const chunk = match ? match[0] : activeGhost;
        input.value = `${input.value}${chunk}`;
        input.focus();
        input.setSelectionRange(input.value.length, input.value.length);
        render();
        announce(`Accepted "${chunk.trim()}".`);
      };

      const dismissGhost = () => {
        if (!activeGhost) return;
        dismissed = true;
        render();
        announce("Dismissed inline suggestion.");
      };

      input?.addEventListener("input", () => {
        dismissed = false;
        render();
      });

      input?.addEventListener("keydown", (ev) => {
        if (ev.key === "Tab" && activeGhost.length > 0) {
          ev.preventDefault();
          acceptAll();
          return;
        }
        if (
          ev.key === "ArrowRight" &&
          activeGhost.length > 0 &&
          input.selectionStart === input.value.length &&
          input.selectionEnd === input.value.length
        ) {
          ev.preventDefault();
          acceptNextWord();
          return;
        }
        if (ev.key === "Escape" && activeGhost.length > 0) {
          ev.preventDefault();
          dismissGhost();
        }
      });

      acceptAllBtn?.addEventListener("click", acceptAll);
      acceptWordBtn?.addEventListener("click", acceptNextWord);
      dismissBtn?.addEventListener("click", dismissGhost);

      resetBtn?.addEventListener("click", () => {
        if (!input) return;
        input.value = initialText;
        anchorText = initialText;
        suggestionIdx = 0;
        dismissed = false;
        render();
        input.focus();
        input.setSelectionRange(input.value.length, input.value.length);
        announce("Draft reset to initial suggestion.");
      });

      render();
    });
  }

  initAiAutocomplete();
  document.addEventListener("astro:page-load", initAiAutocomplete);
</script>
```
