AI answer
Article-style AI answer with compact source cards, inline citation highlights, version switcher, feedback controls and follow-up bar.
pnpm dlx shadcn@latest add @haze/ai-answer---
import { ArrowRight, BookOpen, ChevronLeft, ChevronRight, Copy, RotateCw, Share2, Sparkles, ThumbsDown, ThumbsUp } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Citation {
id: number;
title: string;
source: string;
excerpt: string;
}
interface Props {
id?: string;
question?: string;
citations?: Citation[];
class?: string;
}
const {
id = "haze-ai-answer",
question = "How does Astro islands hydration affect Core Web Vitals on content-heavy pages?",
citations = [
{ id: 1, title: "Astro Islands Architecture", source: "docs.astro.build", excerpt: "Static HTML ships with zero client JavaScript by default; only opted-in islands hydrate." },
{ id: 2, title: "Web Vitals Field Report", source: "web.dev", excerpt: "Reducing main-thread hydration work directly improves INP and Time to Interactive." },
{ id: 3, title: "Client Directives Reference", source: "docs.astro.build", excerpt: "Use client:visible for below-the-fold widgets so hero LCP stays unblocked." },
],
class: className,
} = Astro.props;
---
<section aria-labelledby={`${id}-title`} data-haze-ai-answer class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}>
<article class="mx-auto max-w-3xl rounded-2xl border border-border bg-card p-5 sm:p-7">
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="inline-flex items-center gap-1.5 rounded-full border border-frame bg-muted px-2.5 py-0.5 text-xs/5 font-medium text-foreground">
<Sparkles class="size-3.5" aria-hidden="true" />
Synthesized answer
</span>
<span class="text-xs/5 text-muted-foreground tabular-nums">3 sources · 1.4s</span>
</div>
<h2 id={`${id}-title`} class="mt-3 text-xl/7 font-semibold tracking-tight text-foreground sm:text-2xl/8">{question}</h2>
<div class="mt-4 grid gap-2 sm:grid-cols-3">
{
citations.map((c) => (
<button
type="button"
data-ans-cite={String(c.id)}
class="flex cursor-pointer flex-col items-start rounded-xl border border-border bg-muted/40 p-3 text-left transition-colors duration-150 ease-snappy hover:border-border-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring data-[active=true]:border-foreground data-[active=true]:bg-accent active:scale-[0.97] active:duration-75"
>
<span class="flex w-full items-center gap-1.5 text-[0.6875rem]/4 text-muted-foreground">
<span class="inline-flex size-4 shrink-0 items-center justify-center rounded-sm bg-muted font-mono text-[0.625rem] font-semibold text-foreground">{c.id}</span>
<span class="truncate">{c.source}</span>
</span>
<span class="mt-1.5 line-clamp-1 text-xs/5 font-medium text-foreground">{c.title}</span>
</button>
))
}
</div>
<div data-ans-body class="mt-5 space-y-3 text-sm/7 text-foreground">
<p>
<span data-ans-span="1" class="rounded-sm px-0.5 transition-colors duration-150 data-[lit=true]:bg-accent">
Astro renders every page to static HTML at build time and strips component JavaScript unless you explicitly attach a hydration directive.
</span>
<button type="button" data-ans-cite="1" aria-label="Highlight source 1" class="mx-1 inline-flex size-5 cursor-pointer items-center justify-center rounded-sm border border-frame bg-muted align-baseline font-mono text-[0.6875rem] font-semibold text-foreground hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring">1</button>
<span data-ans-span="2" class="rounded-sm px-0.5 transition-colors duration-150 data-[lit=true]:bg-accent">
Because the browser does not parse or execute a full application bundle up front, main-thread blocking drops sharply and INP stays responsive on mid-tier devices.
</span>
<button type="button" data-ans-cite="2" aria-label="Highlight source 2" class="mx-1 inline-flex size-5 cursor-pointer items-center justify-center rounded-sm border border-frame bg-muted align-baseline font-mono text-[0.6875rem] font-semibold text-foreground hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring">2</button>
</p>
<p>
<span data-ans-span="3" class="rounded-sm px-0.5 transition-colors duration-150 data-[lit=true]:bg-accent">
For interactive widgets below the fold, pairing native HTML disclosures with deferred hydration keeps hero LCP fast while preserving full interactivity.
</span>
<button type="button" data-ans-cite="3" aria-label="Highlight source 3" class="mx-1 inline-flex size-5 cursor-pointer items-center justify-center rounded-sm border border-frame bg-muted align-baseline font-mono text-[0.6875rem] font-semibold text-foreground hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring">3</button>
</p>
</div>
<div class="mt-5 flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4">
<div class="flex flex-wrap items-center gap-1">
<button type="button" data-ans-copy class="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-2.5 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
<Copy class="size-3.5" aria-hidden="true" />
Copy
</button>
<button type="button" data-ans-regen class="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-2.5 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
<RotateCw class="size-3.5" aria-hidden="true" />
Regenerate
</button>
<button type="button" data-ans-share class="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-lg px-2.5 text-xs font-medium text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
<Share2 class="size-3.5" aria-hidden="true" />
Share
</button>
<button type="button" data-ans-rate="up" aria-pressed="false" aria-label="Rate helpful" class="inline-flex size-8 cursor-pointer items-center justify-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground aria-pressed:bg-success/14 aria-pressed:text-success focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
<ThumbsUp class="size-3.5" aria-hidden="true" />
</button>
<button type="button" data-ans-rate="down" aria-pressed="false" aria-label="Rate unhelpful" class="inline-flex size-8 cursor-pointer items-center justify-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground aria-pressed:bg-destructive/14 aria-pressed:text-destructive focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
<ThumbsDown class="size-3.5" aria-hidden="true" />
</button>
</div>
<div class="flex items-center gap-1 text-xs text-muted-foreground tabular-nums">
<button type="button" data-ans-ver="-1" aria-label="Previous version" class="inline-flex size-7 cursor-pointer items-center justify-center rounded-md hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
<ChevronLeft class="size-3.5" aria-hidden="true" />
</button>
<span data-ans-ver-label>1 / 2</span>
<button type="button" data-ans-ver="1" aria-label="Next version" class="inline-flex size-7 cursor-pointer items-center justify-center rounded-md hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
<ChevronRight class="size-3.5" aria-hidden="true" />
</button>
</div>
</div>
<form data-ans-followup class="mt-4 flex items-center gap-2 rounded-xl border border-frame-input bg-field p-1.5 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">
<BookOpen class="ml-2 size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
<label for={`${id}-follow`} class="sr-only">Ask a follow-up question</label>
<input id={`${id}-follow`} type="text" placeholder="Ask a follow-up question…" class="h-8 min-w-0 flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-hidden" />
<button type="submit" aria-label="Ask follow-up" class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg bg-primary text-primary-foreground hover:opacity-90 focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
<ArrowRight class="size-4" aria-hidden="true" />
</button>
</form>
<p data-ans-status role="status" class="mt-2 min-h-4 text-xs/4 text-muted-foreground"></p>
</article>
</section>
<script>
function initAiAnswers() {
document.querySelectorAll<HTMLElement>("[data-haze-ai-answer]").forEach((root) => {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const status = root.querySelector<HTMLElement>("[data-ans-status]");
const verLabel = root.querySelector<HTMLElement>("[data-ans-ver-label]");
let ver = 1;
const totalVer = 2;
const highlight = (id: string | null) => {
root.querySelectorAll<HTMLElement>("[data-ans-span]").forEach((s) => s.setAttribute("data-lit", String(s.dataset.ansSpan === id)));
root.querySelectorAll<HTMLElement>("[data-ans-cite]").forEach((c) => c.setAttribute("data-active", String(c.dataset.ansCite === id)));
};
root.querySelectorAll<HTMLElement>("[data-ans-cite]").forEach((btn) => {
const cid = btn.dataset.ansCite ?? null;
btn.addEventListener("mouseenter", () => highlight(cid));
btn.addEventListener("mouseleave", () => highlight(null));
btn.addEventListener("click", () => {
highlight(cid);
if (status) status.textContent = `Highlighted sentence supported by source ${cid}.`;
});
});
root.querySelector<HTMLButtonElement>("[data-ans-copy]")?.addEventListener("click", () => {
const txt = root.querySelector<HTMLElement>("[data-ans-body]")?.innerText ?? "";
navigator.clipboard?.writeText(txt).catch(() => {});
if (status) status.textContent = "Answer copied to clipboard.";
});
root.querySelector<HTMLButtonElement>("[data-ans-regen]")?.addEventListener("click", () => {
ver = ver === totalVer ? 1 : ver + 1;
if (verLabel) verLabel.textContent = `${ver} / ${totalVer}`;
if (status) status.textContent = `Showing regenerated version ${ver} of ${totalVer}.`;
});
root.querySelector<HTMLButtonElement>("[data-ans-share]")?.addEventListener("click", () => {
if (status) status.textContent = "Share link copied.";
});
root.querySelectorAll<HTMLButtonElement>("[data-ans-rate]").forEach((btn) => {
btn.addEventListener("click", () => {
const on = btn.getAttribute("aria-pressed") !== "true";
root.querySelectorAll<HTMLButtonElement>("[data-ans-rate]").forEach((b) => b.setAttribute("aria-pressed", "false"));
btn.setAttribute("aria-pressed", String(on));
if (status) status.textContent = on ? "Feedback recorded." : "Feedback removed.";
});
});
root.querySelectorAll<HTMLButtonElement>("[data-ans-ver]").forEach((btn) => {
btn.addEventListener("click", () => {
ver = ((ver - 1 + Number(btn.dataset.ansVer) + totalVer) % totalVer) + 1;
if (verLabel) verLabel.textContent = `${ver} / ${totalVer}`;
if (status) status.textContent = `Viewing version ${ver} of ${totalVer}.`;
});
});
root.querySelector<HTMLFormElement>("[data-ans-followup]")?.addEventListener("submit", (ev) => {
ev.preventDefault();
const inp = ev.currentTarget instanceof HTMLFormElement ? ev.currentTarget.querySelector<HTMLInputElement>("input") : null;
if (!inp?.value.trim()) return;
if (status) status.textContent = `Follow-up queued: "${inp.value.trim()}".`;
inp.value = "";
});
});
}
initAiAnswers();
document.addEventListener("astro:page-load", initAiAnswers);
</script>When to use
- Presenting a single grounded answer with inline sentence-level citations
- Building a documentation or search answer card with regenerate, share and follow-up actions
When not to use
- Users need a multi-turn back-and-forth conversation sidebar; use ai-chat instead
Installation
Add the Haze registry to components.json once, then install AI answer with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ai-answernpx shadcn@latest add @haze/ai-answeryarn dlx shadcn@latest add @haze/ai-answerbunx --bun shadcn@latest add @haze/ai-answerFirst 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-answer" | Unique prefix for headings and input labels. |
| question | string | Astro islands question | Question displayed as the article heading. |
| citations | { id: number; title: string; source: string; excerpt: string }[] | 3 demo citations | Source cards paired with numbered inline citations. |
| class | string | – | Extra classes on the outer section. |
Keyboard interactions
- Tab
- Move across source cards, inline citation buttons, toolbar actions and follow-up input
- EnterSpace
- Highlight a cited sentence, copy, rate, switch versions or submit a follow-up
Accessibility
- Every citation card and inline citation chip is a native button that highlights its supporting sentence on hover or activation.
- Copy, version switches and follow-up submissions announce their result in a polite role="status" element.
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 answer" with `npx shadcn@latest add @haze/ai-answer`. 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 AiAnswer from "@/components/haze/blocks/ai-answer.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-answer.md
Customize with real content
Adapt the Haze ai-answer block for our product. Replace the demo values of these props with our real content: id, question, citations, class. Keep the layout, the heading level rules and these accessibility details: Every citation card and inline citation chip is a native button that highlights its supporting sentence on hover or activation. Copy, version switches and follow-up submissions announce their result in a polite role="status" element. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ai-answer, check it fits: use it when presenting a single grounded answer with inline sentence-level citations; building a documentation or search answer card with regenerate, share and follow-up actions. Avoid it when users need a multi-turn back-and-forth conversation sidebar; use ai-chat instead. Alternatives: @haze/ai-chat, @haze/card.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.