# AI inline citations

> Borderless grounded AI prose with inline domain pills that highlight sentences, open a source preview card and toggle all sources.

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

## Use when
- Attributing individual claims in an AI summary to one or more verifiable web or document sources
- Letting readers hover, focus or click inline domain pills to inspect backing excerpts without cluttering initial prose

## Avoid when
- You need a full answer layout with thumbs feedback, version pagination and a follow-up bar; use ai-answer instead
- Showing citations pinned to page numbers inside an uploaded PDF file; use ai-attachment

## Alternatives
- [ai-answer](https://hazeui.com/blocks/ai-answer.md)
- [ai-attachment](https://hazeui.com/blocks/ai-attachment.md)
- [hover-card](https://hazeui.com/ui/hover-card.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-citations" | no | Unique prefix for landmark heading and source-list ARIA IDs. |
| heading | `string` | "Grounded answer with inline citations" | no | Screen-reader landmark heading for the cited prose section. |
| sources | `{ id: string; domain: string; title: string; excerpt: string; url: string }[]` | 4 demo web sources | no | Reference items displayed in the hover/click preview card and expandable sources list. |
| claims | `{ text: string; sourceIds: string[] }[]` | 4 cited claims | no | Ordered sentences mapped to one or more source IDs. |
| class | `string` |  | no | Extra classes applied to the outer section. |

## Accessibility
- Inline citation pills and multi-source preview tabs are native buttons with aria-pressed state, hover/focus highlight and Escape dismissal.
- The footer sources button uses aria-expanded and aria-controls to toggle the full reference list, announcing changes in a polite status region.
- Key Tab: Move across inline citation pills, preview controls and the sources toggle button
- Key Enter / Space: Pin a citation preview card, switch paired sources or expand the full source list
- Key Escape: Dismiss the active citation preview card and clear the sentence highlight

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze ai-citations block for our product. Replace the demo values of these props with our real content: id, heading, sources, claims, class. Keep the layout, the heading level rules and these accessibility details: Inline citation pills and multi-source preview tabs are native buttons with aria-pressed state, hover/focus highlight and Escape dismissal. The footer sources button uses aria-expanded and aria-controls to toggle the full reference list, announcing changes in a polite status region. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-citations, check it fits: use it when attributing individual claims in an ai summary to one or more verifiable web or document sources; letting readers hover, focus or click inline domain pills to inspect backing excerpts without cluttering initial prose. Avoid it when you need a full answer layout with thumbs feedback, version pagination and a follow-up bar; use ai-answer instead; showing citations pinned to page numbers inside an uploaded pdf file; use ai-attachment. Alternatives: @haze/ai-answer, @haze/ai-attachment, @haze/hover-card.

## Example requests that should lead here
- Add a borderless AI inline citations prose block with tinted initial domain pills, hover preview card and overlapping avatar sources toggle

## Source

```astro
---
import { ChevronDown, ExternalLink, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface CitationSource {
  id: string;
  domain: string;
  title: string;
  excerpt: string;
  url: string;
}

interface CitationClaim {
  text: string;
  sourceIds: string[];
}

interface Props {
  id?: string;
  heading?: string;
  sources?: CitationSource[];
  claims?: CitationClaim[];
  class?: string;
}

const {
  id = "haze-ai-citations",
  heading = "Grounded answer with inline citations",
  sources = [
    {
      id: "s1",
      domain: "astro.build",
      title: "Islands architecture overview",
      excerpt: "Pages render static HTML on the server and selectively hydrate interactive islands only when needed.",
      url: "https://docs.astro.build/en/concepts/islands/",
    },
    {
      id: "s2",
      domain: "web.dev",
      title: "Optimize Interaction to Next Paint (INP)",
      excerpt: "Breaking up long tasks and trimming upfront hydration keeps interaction callbacks snappy on mobile hardware.",
      url: "https://web.dev/articles/inp",
    },
    {
      id: "s3",
      domain: "mdn.io",
      title: "Native HTML controls and focus semantics",
      excerpt: "Built-in browser elements expose keyboard navigation and accessibility roles without extra runtime scripts.",
      url: "https://developer.mozilla.org/en-US/docs/Web/HTML",
    },
    {
      id: "s4",
      domain: "ecma.dev",
      title: "Reduced motion and progressive enhancement",
      excerpt: "Honoring user motion preferences swaps spatial transitions for crisp state changes with zero layout shift.",
      url: "https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion",
    },
  ],
  claims = [
    {
      text: "Keep interactive widgets lightweight. Shipping static HTML first lets pages paint immediately before small scripts hydrate on demand.",
      sourceIds: ["s1"],
    },
    {
      text: "Trimming long main-thread tasks preserves crisp input latency across lower-powered devices.",
      sourceIds: ["s2", "s3"],
    },
    {
      text: "Native buttons and disclosures provide keyboard support and focus semantics without extra framework overhead.",
      sourceIds: ["s3"],
    },
    {
      text: "When a reader requests reduced motion, replace movement with a direct state swap so nothing feels jarring.",
      sourceIds: ["s4"],
    },
  ],
  class: className,
} = Astro.props;

const badgeTones = [
  "bg-muted text-foreground",
  "bg-muted text-foreground",
  "bg-muted text-foreground",
  "bg-muted text-foreground",
];

const sourceIndexMap = new Map(sources.map((s, idx) => [s.id, idx]));
const sourceMap = new Map(sources.map((s) => [s.id, s]));

const getTone = (sourceId: string) => {
  const idx = sourceIndexMap.get(sourceId) ?? 0;
  return badgeTones[idx % badgeTones.length];
};

const getInitial = (domain: string) => (domain.trim().charAt(0) || "S").toUpperCase();

const pillLabel = (ids: string[]) => {
  const first = sourceMap.get(ids[0] ?? "");
  const base = first?.domain ?? "source";
  return ids.length > 1 ? `${base} +${ids.length - 1}` : base;
};
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-citations
  data-sources={JSON.stringify(sources)}
  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">
    <p class="text-[0.9375rem]/7 text-foreground break-words">
      {
        claims.map((claim, idx) => {
          const primaryId = claim.sourceIds[0] ?? "";
          const primary = sourceMap.get(primaryId);
          const label = pillLabel(claim.sourceIds);
          return (
            <>
              <span
                data-cit-sentence={String(idx)}
                data-lit="false"
                class="rounded-sm transition-colors duration-150 ease-snappy data-[lit=true]:bg-accent"
              >
                {claim.text}
              </span>
              {" "}
              <button
                type="button"
                data-cit-pill={String(idx)}
                data-source-ids={claim.sourceIds.join(",")}
                data-active="false"
                aria-pressed="false"
                class="mx-0.5 inline-flex min-h-6 cursor-pointer items-center gap-1.5 rounded-full border border-frame bg-field py-0.5 pr-2 pl-1 align-middle text-xs/4 text-muted-foreground transition-colors duration-150 ease-snappy hover:border-frame-hover hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[active=true]:border-foreground data-[active=true]:bg-accent data-[active=true]:text-foreground"
              >
                <span
                  class={cn(
                    "inline-flex size-4 shrink-0 items-center justify-center rounded-full text-[0.625rem] font-semibold",
                    getTone(primaryId),
                  )}
                  aria-hidden="true"
                >
                  {getInitial(primary?.domain ?? "S")}
                </span>
                <span>{label}</span>
                <span class="sr-only"> — inspect citation</span>
              </button>
              {" "}
            </>
          );
        })
      }
    </p>

    <div
      data-cit-preview
      class="mt-3 hidden rounded-xl border border-border bg-card p-3.5 shadow-float"
    >
      <div class="flex flex-wrap items-center justify-between gap-2">
        <div class="flex flex-wrap items-center gap-1.5">
          <span
            data-cit-prev-domain
            class="font-mono text-xs/4 font-medium text-foreground"
          ></span>
          <div
            data-cit-tabs
            role="group"
            aria-label="Sources supporting this claim"
            class="hidden flex-wrap items-center gap-1"
          ></div>
        </div>

        <div class="flex items-center gap-1">
          <a
            data-cit-prev-link
            href="#"
            target="_blank"
            rel="noopener noreferrer"
            class="inline-flex min-h-7 items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
          >
            <span>Open</span>
            <ExternalLink class="size-3" aria-hidden="true" />
          </a>
          <button
            type="button"
            data-cit-prev-close
            aria-label="Close source preview"
            class="inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
          >
            <X class="size-3.5" aria-hidden="true" />
          </button>
        </div>
      </div>

      <h3 data-cit-prev-title class="mt-2 text-sm/5 font-medium text-foreground break-words"></h3>
      <p data-cit-prev-excerpt class="mt-1 text-xs/5 text-muted-foreground break-words"></p>
    </div>

    <div class="mt-5">
      <button
        type="button"
        data-cit-drawer-btn
        aria-expanded="false"
        aria-controls={`${id}-source-list`}
        class="inline-flex min-h-8 cursor-pointer items-center gap-2 rounded-full py-1 pr-2.5 pl-0.5 text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
      >
        <span class="flex items-center -space-x-1.5" aria-hidden="true">
          {
            sources.slice(0, 4).map((src, idx) => (
              <span
                class={cn(
                  "inline-flex size-5 items-center justify-center rounded-full border border-background text-[0.625rem] font-semibold",
                  badgeTones[idx % badgeTones.length],
                )}
              >
                {getInitial(src.domain)}
              </span>
            ))
          }
        </span>
        <span class="tabular-nums">{sources.length} sources</span>
        <ChevronDown
          data-cit-drawer-chevron
          class="size-3.5 transition-transform duration-150 ease-snappy"
          aria-hidden="true"
        />
      </button>

      <ul
        id={`${id}-source-list`}
        data-cit-drawer
        class="mt-2.5 hidden space-y-1.5"
      >
        {
          sources.map((src, idx) => (
            <li class="flex items-center justify-between gap-2 rounded-xl border border-border bg-card px-3 py-2">
              <button
                type="button"
                data-cit-list-item={src.id}
                class="flex min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-sm text-left focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
              >
                <span
                  class={cn(
                    "inline-flex size-5 shrink-0 items-center justify-center rounded-full text-[0.625rem] font-semibold",
                    badgeTones[idx % badgeTones.length],
                  )}
                  aria-hidden="true"
                >
                  {getInitial(src.domain)}
                </span>
                <span class="min-w-0 flex-1">
                  <span class="block truncate text-xs/5 font-medium text-foreground">{src.title}</span>
                  <span class="block truncate font-mono text-[0.6875rem]/4 text-muted-foreground">{src.domain}</span>
                </span>
              </button>
              <a
                href={src.url}
                target="_blank"
                rel="noopener noreferrer"
                aria-label={`Open ${src.title} on ${src.domain}`}
                class="inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
              >
                <ExternalLink class="size-3.5" aria-hidden="true" />
              </a>
            </li>
          ))
        }
      </ul>
    </div>

    <p data-cit-status role="status" aria-live="polite" class="sr-only"></p>
  </div>
</section>

<script>
  interface CitationSourceData {
    id: string;
    domain: string;
    title: string;
    excerpt: string;
    url: string;
  }

  function initAiCitations() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-citations]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      let sources: CitationSourceData[] = [];
      try {
        const parsed: unknown = JSON.parse(root.dataset.sources ?? "[]");
        if (Array.isArray(parsed)) {
          sources = parsed.filter(
            (item): item is CitationSourceData =>
              typeof item === "object" && item !== null && "id" in item && "domain" in item,
          );
        }
      } catch {
        sources = [];
      }

      const sourceById = new Map<string, CitationSourceData>(sources.map((s) => [s.id, s]));
      const sentences = Array.from(root.querySelectorAll<HTMLElement>("[data-cit-sentence]"));
      const pills = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-cit-pill]"));
      const previewEl = root.querySelector<HTMLElement>("[data-cit-preview]");
      const tabsWrap = root.querySelector<HTMLElement>("[data-cit-tabs]");
      const prevDomain = root.querySelector<HTMLElement>("[data-cit-prev-domain]");
      const prevTitle = root.querySelector<HTMLElement>("[data-cit-prev-title]");
      const prevExcerpt = root.querySelector<HTMLElement>("[data-cit-prev-excerpt]");
      const prevLink = root.querySelector<HTMLAnchorElement>("[data-cit-prev-link]");
      const prevClose = root.querySelector<HTMLButtonElement>("[data-cit-prev-close]");
      const statusEl = root.querySelector<HTMLElement>("[data-cit-status]");
      const drawerBtn = root.querySelector<HTMLButtonElement>("[data-cit-drawer-btn]");
      const drawerEl = root.querySelector<HTMLElement>("[data-cit-drawer]");
      const drawerChevron = root.querySelector<HTMLElement>("[data-cit-drawer-chevron]");
      const listBtns = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-cit-list-item]"));

      let pinnedClaim: number | null = null;
      let hoverClaim: number | null = null;
      let hideTimer = 0;

      const cancelHide = () => {
        if (hideTimer) {
          window.clearTimeout(hideTimer);
          hideTimer = 0;
        }
      };

      const renderPreviewSource = (srcId: string) => {
        const src = sourceById.get(srcId);
        if (!src) return;
        if (prevDomain) prevDomain.textContent = src.domain;
        if (prevTitle) prevTitle.textContent = src.title;
        if (prevExcerpt) prevExcerpt.textContent = src.excerpt;
        if (prevLink) {
          prevLink.href = src.url;
          prevLink.setAttribute("aria-label", `Open ${src.title} on ${src.domain}`);
        }
        tabsWrap?.querySelectorAll<HTMLButtonElement>("[data-cit-tab]").forEach((tab) => {
          tab.setAttribute("aria-pressed", String(tab.dataset.citTab === src.id));
        });
      };

      const renderTabs = (ids: string[], selectedId: string) => {
        if (!tabsWrap) return;
        if (ids.length < 2) {
          tabsWrap.classList.add("hidden");
          tabsWrap.classList.remove("flex");
          tabsWrap.replaceChildren();
          return;
        }
        tabsWrap.classList.remove("hidden");
        tabsWrap.classList.add("flex");
        const frag = document.createDocumentFragment();
        ids.forEach((sid) => {
          const src = sourceById.get(sid);
          if (!src) return;
          const btn = document.createElement("button");
          btn.type = "button";
          btn.dataset.citTab = sid;
          btn.setAttribute("aria-pressed", String(sid === selectedId));
          btn.className =
            "inline-flex min-h-6 cursor-pointer items-center rounded-md border border-frame bg-control px-2 py-0.5 font-mono text-[0.6875rem]/4 text-muted-foreground transition-colors duration-150 ease-snappy hover:border-frame-hover hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring aria-pressed:border-foreground aria-pressed:bg-muted aria-pressed:text-foreground";
          btn.textContent = src.domain;
          btn.addEventListener("click", () => {
            renderPreviewSource(sid);
            if (statusEl) statusEl.textContent = `Switched source preview to ${src.domain}.`;
          });
          frag.appendChild(btn);
        });
        tabsWrap.replaceChildren(frag);
      };

      const clearActive = () => {
        pinnedClaim = null;
        hoverClaim = null;
        sentences.forEach((s) => s.setAttribute("data-lit", "false"));
        pills.forEach((p) => {
          p.setAttribute("data-active", "false");
          p.setAttribute("aria-pressed", "false");
        });
        previewEl?.classList.add("hidden");
      };

      const showClaim = (
        claimIdx: number,
        preferredSourceId: string | null,
        pin: boolean,
        announce: boolean,
      ) => {
        cancelHide();
        if (pin) {
          pinnedClaim = claimIdx;
        } else {
          hoverClaim = claimIdx;
        }

        sentences.forEach((s) => {
          s.setAttribute("data-lit", String(Number(s.dataset.citSentence) === claimIdx));
        });
        pills.forEach((p) => {
          const isMatch = Number(p.dataset.citPill) === claimIdx;
          p.setAttribute("data-active", String(isMatch));
          p.setAttribute("aria-pressed", String(pinnedClaim === Number(p.dataset.citPill)));
        });

        const pill = pills.find((p) => Number(p.dataset.citPill) === claimIdx);
        const ids = (pill?.dataset.sourceIds ?? "")
          .split(",")
          .map((x) => x.trim())
          .filter((x) => sourceById.has(x));

        if (ids.length === 0) return;
        const targetId = preferredSourceId && ids.includes(preferredSourceId) ? preferredSourceId : ids[0];
        renderTabs(ids, targetId);
        renderPreviewSource(targetId);
        previewEl?.classList.remove("hidden");

        if (announce && statusEl) {
          const src = sourceById.get(targetId);
          statusEl.textContent = src
            ? `Showing citation from ${src.domain}.`
            : `Showing citation for sentence ${claimIdx + 1}.`;
        }
      };

      const scheduleHide = () => {
        cancelHide();
        if (pinnedClaim !== null) return;
        hideTimer = window.setTimeout(() => {
          if (pinnedClaim === null) {
            clearActive();
          }
        }, 160);
      };

      pills.forEach((pill) => {
        const idx = Number(pill.dataset.citPill ?? "0");
        pill.addEventListener("mouseenter", () => {
          if (pinnedClaim === null || pinnedClaim === idx) {
            showClaim(idx, null, false, false);
          }
        });
        pill.addEventListener("mouseleave", () => {
          if (hoverClaim === idx && pinnedClaim === null) {
            scheduleHide();
          }
        });
        pill.addEventListener("focus", () => {
          if (pinnedClaim === null) {
            showClaim(idx, null, false, false);
          }
        });
        pill.addEventListener("click", () => {
          if (pinnedClaim === idx) {
            clearActive();
            if (statusEl) statusEl.textContent = "Closed source preview.";
            return;
          }
          showClaim(idx, null, true, true);
        });
      });

      previewEl?.addEventListener("mouseenter", cancelHide);
      previewEl?.addEventListener("mouseleave", scheduleHide);

      prevClose?.addEventListener("click", () => {
        clearActive();
        if (statusEl) statusEl.textContent = "Closed source preview.";
      });

      root.addEventListener("keydown", (ev) => {
        if (ev.key === "Escape" && (pinnedClaim !== null || hoverClaim !== null)) {
          clearActive();
          if (statusEl) statusEl.textContent = "Closed source preview.";
        }
      });

      listBtns.forEach((btn) => {
        btn.addEventListener("click", () => {
          const sid = btn.dataset.citListItem ?? "";
          const matchingPill = pills.find((p) =>
            (p.dataset.sourceIds ?? "")
              .split(",")
              .map((x) => x.trim())
              .includes(sid),
          );
          if (matchingPill) {
            showClaim(Number(matchingPill.dataset.citPill ?? "0"), sid, true, true);
          } else if (sourceById.has(sid)) {
            renderTabs([sid], sid);
            renderPreviewSource(sid);
            previewEl?.classList.remove("hidden");
            const src = sourceById.get(sid);
            if (statusEl && src) statusEl.textContent = `Showing ${src.domain}.`;
          }
        });
      });

      drawerBtn?.addEventListener("click", () => {
        if (!drawerEl) return;
        const nextOpen = drawerBtn.getAttribute("aria-expanded") !== "true";
        drawerBtn.setAttribute("aria-expanded", String(nextOpen));
        drawerEl.classList.toggle("hidden", !nextOpen);
        drawerChevron?.classList.toggle("rotate-180", nextOpen);
        if (statusEl) {
          statusEl.textContent = nextOpen
            ? `Expanded ${sources.length} sources.`
            : "Collapsed source list.";
        }
      });
    });
  }

  initAiCitations();
  document.addEventListener("astro:page-load", initAiCitations);
</script>
```
