AI ghost autocomplete
Email reply composer with live ghost completion, Tab full-accept, ArrowRight word-accept, prefix matching and accessible toolbar buttons.
pnpm dlx shadcn@latest add @haze/ai-autocomplete---
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>When to use
- 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
When not to use
- 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
Installation
Add the Haze registry to components.json once, then install AI ghost autocomplete with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ai-autocompletenpx shadcn@latest add @haze/ai-autocompleteyarn dlx shadcn@latest add @haze/ai-autocompletebunx --bun shadcn@latest add @haze/ai-autocompleteFirst 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 | "haze-ai-autocomplete" | Unique prefix for textarea label and hint references. |
| heading | string | "AI ghost autocomplete" | Screen-reader section heading for the reply compose card. |
| recipient | string | "Hana Sato" | Recipient name shown in the compose header. |
| subject | string | "Re: Launch review" | Subject line displayed in the compose header. |
| initialText | string | "Thanks for the update on the " | Pre-filled starting draft text before the ghost suggestion. |
| suggestions | string[] | 3 contextual continuations | Ghost completion candidates users can accept or cycle through. |
| class | string | – | Extra classes on the outer section. |
Keyboard interactions
- Tab
- Accept the entire active ghost completion
- ArrowRight
- Accept one word at a time when the caret is at the end of the draft
- Escape
- Dismiss the current ghost completion
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.
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 block "AI ghost autocomplete" with `npx shadcn@latest add @haze/ai-autocomplete`. 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 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: http://localhost:4329/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.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.