# AI attachment reader

> Chat column animating a PDF upload ring into a compact 6-page scan strip with clickable inline page citations and extracted excerpts.

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

## Use when
- Visualizing PDF upload progress followed by page-by-page document indexing inside an AI chat flow
- Linking inline page citations directly to extracted document excerpts and an interactive page strip

## Avoid when
- Extracting structured key-value fields into an editable form table; use document-extract instead
- Citing external web URLs rather than pages of an uploaded file; use ai-citations

## Alternatives
- [document-extract](https://hazeui.com/blocks/document-extract.md)
- [ai-citations](https://hazeui.com/blocks/ai-citations.md)
- [file-upload](https://hazeui.com/ui/file-upload.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-attachment" | no | Unique prefix for section landmark heading ID. |
| heading | `string` | "Document attachment exchange" | no | Screen-reader landmark heading for the chat exchange. |
| fileName | `string` | "Q3-operations-brief.pdf" | no | Filename displayed on the right-aligned PDF attachment card. |
| fileSizeMb | `number` | 4.2 | no | Total file size in megabytes used for the live upload progress readout. |
| question | `string` | "What changed this quarter? Keep it short." | no | User prompt bubble paired beneath the attached document. |
| pages | `{ page: number; title: string; snippet: string }[]` | 6 demo PDF pages | no | Page metadata and extracted excerpts linked to the page strip and citation pills. |
| class | `string` |  | no | Extra classes applied to the outer section. |

## Accessibility
- Circular upload ring is exposed via role="progressbar" with aria-valuemin, aria-valuemax and live aria-valuenow updates.
- Every page pill and inline page citation is a button with aria-pressed state that updates the extracted excerpt and announces changes politely.
- Key Tab: Move across the 6 document page pills, inline page citation pills and the Replay button
- Key Enter / Space: Highlight a referenced page and show its excerpt, or replay the upload sequence

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze ai-attachment block for our product. Replace the demo values of these props with our real content: id, heading, fileName, fileSizeMb, question, pages, class. Keep the layout, the heading level rules and these accessibility details: Circular upload ring is exposed via role="progressbar" with aria-valuemin, aria-valuemax and live aria-valuenow updates. Every page pill and inline page citation is a button with aria-pressed state that updates the extracted excerpt and announces changes politely. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-attachment, check it fits: use it when visualizing pdf upload progress followed by page-by-page document indexing inside an ai chat flow; linking inline page citations directly to extracted document excerpts and an interactive page strip. Avoid it when extracting structured key-value fields into an editable form table; use document-extract instead; citing external web urls rather than pages of an uploaded file; use ai-citations. Alternatives: @haze/document-extract, @haze/ai-citations, @haze/file-upload.

## Example requests that should lead here
- Add an AI attachment chat column with a PDF circular upload ring, user prompt bubble, 6-page scan strip and clickable inline p. 2, p. 4 and p. 6 citations

## Source

```astro
---
import { Check, RotateCcw } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface DocumentPage {
  page: number;
  title: string;
  snippet: string;
}

interface Props {
  id?: string;
  heading?: string;
  fileName?: string;
  fileSizeMb?: number;
  question?: string;
  pages?: DocumentPage[];
  class?: string;
}

const {
  id = "haze-ai-attachment",
  heading = "Document attachment exchange",
  fileName = "Q3-operations-brief.pdf",
  fileSizeMb = 4.2,
  question = "What changed this quarter? Keep it short.",
  pages = [
    {
      page: 1,
      title: "Executive overview",
      snippet: "Q3 regional throughput rose 18% quarter over quarter while onboarding three logistics accounts.",
    },
    {
      page: 2,
      title: "Capacity bottlenecks",
      snippet: "Peak batch indexing hit 84% of EU worker queues during Tuesday billing runs, adding 9-minute delays.",
    },
    {
      page: 3,
      title: "Support desk SLA",
      snippet: "Median first response dropped to 14 minutes after automated priority routing went live.",
    },
    {
      page: 4,
      title: "Cost reduction plan",
      snippet: "Consolidating idle staging clusters and moving archives to cold storage saves $42k per month.",
    },
    {
      page: 5,
      title: "Vendor renewals",
      snippet: "Warehouse and telemetry contracts renew on November 15 with an optional multi-year discount.",
    },
    {
      page: 6,
      title: "Q4 rollout dates",
      snippet: "Autoscaling EU worker pools ship October 8, followed by archive tier validation on October 22.",
    },
  ],
  class: className,
} = Astro.props;

const formattedSize = fileSizeMb.toFixed(1);
const initialPage = pages.find((p) => p.page === 2) ?? pages[0];
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-attachment
  data-file-size={String(fileSizeMb)}
  data-pages={JSON.stringify(pages)}
  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-2.5">
    <div class="flex flex-col items-end gap-2">
      <div class="flex w-full max-w-[18.5rem] items-center gap-3 rounded-2xl border border-border bg-card px-3.5 py-2.5">
        <span
          class="inline-flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted font-mono text-[0.6875rem] font-semibold text-muted-foreground"
          aria-hidden="true"
        >
          PDF
        </span>

        <div class="min-w-0 flex-1">
          <p class="truncate text-sm/5 font-medium text-foreground">{fileName}</p>
          <p data-att-meta class="truncate text-xs/4 text-muted-foreground tabular-nums">
            0.0 MB of {formattedSize} MB
          </p>
        </div>

        <div
          data-att-progress
          role="progressbar"
          aria-label="Attachment upload progress"
          aria-valuemin="0"
          aria-valuemax="100"
          aria-valuenow="0"
          class="relative inline-flex size-5 shrink-0 items-center justify-center"
        >
          <svg
            data-att-ring-svg
            viewBox="0 0 20 20"
            class="size-5"
            fill="none"
            aria-hidden="true"
          >
            <circle
              cx="10"
              cy="10"
              r="7.5"
              class="stroke-border"
              stroke-width="2"
            />
            <circle
              data-att-ring
              cx="10"
              cy="10"
              r="7.5"
              class="stroke-foreground"
              stroke-width="2"
              stroke-linecap="round"
              stroke-dasharray="47.12"
              stroke-dashoffset="47.12"
              transform="rotate(-90 10 10)"
            />
          </svg>
          <span
            data-att-done-icon
            class="hidden size-5 items-center justify-center text-success"
            aria-hidden="true"
          >
            <Check class="size-4" aria-hidden="true" />
          </span>
        </div>
      </div>

      <p class="max-w-[20rem] rounded-2xl bg-muted px-4 py-2.5 text-sm/5 text-foreground break-words">
        {question}
      </p>
    </div>

    <div data-att-reader class="hidden space-y-3 pt-2">
      <div class="space-y-2">
        <p data-att-scan-label class="text-xs/4 text-muted-foreground">
          Reading pages…
        </p>

        <div
          role="group"
          aria-label="Document pages"
          class="flex flex-wrap items-center gap-1.5"
        >
          {
            pages.map((p) => (
              <button
                type="button"
                data-att-tile={String(p.page)}
                data-scan="idle"
                aria-pressed="false"
                aria-label={`p. ${p.page}, ${p.title}`}
                class="inline-flex min-h-7 min-w-11 cursor-pointer items-center justify-center rounded-lg border border-frame bg-field px-2 py-1 font-mono text-xs/4 text-muted-foreground tabular-nums 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-[scan=reading]:border-foreground data-[scan=reading]:bg-accent data-[scan=reading]:text-foreground data-[scan=selected]:border-foreground data-[scan=selected]:bg-muted data-[scan=selected]:text-foreground"
              >
                p. {p.page}
              </button>
            ))
          }
        </div>
      </div>

      <div data-att-answer class="hidden space-y-2.5">
        <p class="text-[0.9375rem]/7 text-foreground break-words">
          EU worker queues hit 84% saturation during Tuesday billing peaks
          {" "}
          <button
            type="button"
            data-att-cite="2"
            aria-pressed="true"
            class="mx-0.5 inline-flex min-h-6 min-w-8 cursor-pointer items-center justify-center rounded-md border border-frame bg-field px-1.5 py-0.5 align-baseline font-mono text-xs/4 font-medium 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-accent aria-pressed:text-foreground"
          >
            p. 2
          </button>
          . Retiring idle staging clusters saves $42k monthly
          {" "}
          <button
            type="button"
            data-att-cite="4"
            aria-pressed="false"
            class="mx-0.5 inline-flex min-h-6 min-w-8 cursor-pointer items-center justify-center rounded-md border border-frame bg-field px-1.5 py-0.5 align-baseline font-mono text-xs/4 font-medium 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-accent aria-pressed:text-foreground"
          >
            p. 4
          </button>
          , and autoscaling ships October 8
          {" "}
          <button
            type="button"
            data-att-cite="6"
            aria-pressed="false"
            class="mx-0.5 inline-flex min-h-6 min-w-8 cursor-pointer items-center justify-center rounded-md border border-frame bg-field px-1.5 py-0.5 align-baseline font-mono text-xs/4 font-medium 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-accent aria-pressed:text-foreground"
          >
            p. 6
          </button>
          .
        </p>

        <div class="border-l-2 border-frame-strong py-0.5 pl-3">
          <p data-att-excerpt-head class="text-xs/4 font-medium text-foreground">
            p. {initialPage?.page ?? 2} · {initialPage?.title ?? ""}
          </p>
          <p data-att-excerpt-body class="mt-1 text-xs/5 text-muted-foreground break-words">
            “{initialPage?.snippet ?? ""}”
          </p>
        </div>

        <button
          type="button"
          data-att-replay
          class="inline-flex min-h-7 cursor-pointer items-center gap-1.5 rounded-md px-1 py-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"
        >
          <RotateCcw class="size-3" aria-hidden="true" />
          <span>Replay</span>
        </button>
      </div>
    </div>

    <p data-att-status role="status" aria-live="polite" class="sr-only"></p>
  </div>
</section>

<script>
  interface AttachmentPageData {
    page: number;
    title: string;
    snippet: string;
  }

  function initAiAttachment() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-attachment]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      let pages: AttachmentPageData[] = [];
      try {
        const parsed: unknown = JSON.parse(root.dataset.pages ?? "[]");
        if (Array.isArray(parsed)) {
          pages = parsed.filter(
            (item): item is AttachmentPageData =>
              typeof item === "object" && item !== null && "page" in item && "snippet" in item,
          );
        }
      } catch {
        pages = [];
      }

      const rawSize = Number(root.dataset.fileSize ?? "4.2");
      const totalMb = Number.isFinite(rawSize) && rawSize > 0 ? rawSize : 4.2;
      const circumference = 2 * Math.PI * 7.5;

      const metaEl = root.querySelector<HTMLElement>("[data-att-meta]");
      const progressWrap = root.querySelector<HTMLElement>("[data-att-progress]");
      const ringSvg = root.querySelector<SVGElement>("[data-att-ring-svg]");
      const ringCircle = root.querySelector<SVGCircleElement>("[data-att-ring]");
      const doneIcon = root.querySelector<HTMLElement>("[data-att-done-icon]");
      const readerEl = root.querySelector<HTMLElement>("[data-att-reader]");
      const scanLabel = root.querySelector<HTMLElement>("[data-att-scan-label]");
      const answerEl = root.querySelector<HTMLElement>("[data-att-answer]");
      const excerptHead = root.querySelector<HTMLElement>("[data-att-excerpt-head]");
      const excerptBody = root.querySelector<HTMLElement>("[data-att-excerpt-body]");
      const statusEl = root.querySelector<HTMLElement>("[data-att-status]");
      const replayBtn = root.querySelector<HTMLButtonElement>("[data-att-replay]");
      const tiles = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-att-tile]"));
      const citeBtns = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-att-cite]"));

      const pageMap = new Map<number, AttachmentPageData>(pages.map((p) => [p.page, p]));

      let seqId = 0;
      let uploadTimer = 0;
      let scanTimer = 0;

      const clearTimers = () => {
        if (uploadTimer) window.clearInterval(uploadTimer);
        if (scanTimer) window.clearTimeout(scanTimer);
        uploadTimer = 0;
        scanTimer = 0;
      };

      const setProgress = (pct: number) => {
        const clamped = Math.max(0, Math.min(100, pct));
        const offset = circumference * (1 - clamped / 100);
        if (ringCircle) {
          ringCircle.style.strokeDashoffset = offset.toFixed(2);
        }
        progressWrap?.setAttribute("aria-valuenow", String(Math.round(clamped)));
      };

      const selectPage = (pageNum: number, announce: boolean) => {
        const data = pageMap.get(pageNum);
        if (!data) return;

        tiles.forEach((tile) => {
          const isSelected = Number(tile.dataset.attTile) === pageNum;
          tile.setAttribute("data-scan", isSelected ? "selected" : "done");
          tile.setAttribute("aria-pressed", String(isSelected));
        });

        citeBtns.forEach((btn) => {
          btn.setAttribute("aria-pressed", String(Number(btn.dataset.attCite) === pageNum));
        });

        if (excerptHead) {
          excerptHead.textContent = `p. ${data.page} · ${data.title}`;
        }
        if (excerptBody) {
          excerptBody.textContent = `“${data.snippet}”`;
        }
        if (announce && statusEl) {
          statusEl.textContent = `Showing page ${data.page}: ${data.title}.`;
        }
      };

      const runSequence = (announceStart: boolean) => {
        clearTimers();
        seqId += 1;
        const currentSeq = seqId;
        const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

        ringSvg?.classList.remove("hidden");
        doneIcon?.classList.add("hidden");
        doneIcon?.classList.remove("inline-flex");
        readerEl?.classList.add("hidden");
        answerEl?.classList.add("hidden");

        setProgress(0);
        if (metaEl) metaEl.textContent = `0.0 MB of ${totalMb.toFixed(1)} MB`;

        tiles.forEach((tile) => {
          tile.setAttribute("data-scan", "idle");
          tile.setAttribute("aria-pressed", "false");
        });

        if (announceStart && statusEl) {
          statusEl.textContent = "Replaying attachment upload.";
        }

        const finishReading = () => {
          if (currentSeq !== seqId) return;
          if (scanLabel) {
            scanLabel.textContent = `Read ${pages.length} pages`;
          }
          answerEl?.classList.remove("hidden");
          selectPage(pageMap.has(2) ? 2 : (pages[0]?.page ?? 1), false);
          if (statusEl) {
            statusEl.textContent = `Finished reading ${pages.length} pages.`;
          }
        };

        const startReading = () => {
          if (currentSeq !== seqId) return;
          ringSvg?.classList.add("hidden");
          doneIcon?.classList.remove("hidden");
          doneIcon?.classList.add("inline-flex");
          if (metaEl) metaEl.textContent = `${totalMb.toFixed(1)} MB · ${pages.length} pages`;
          readerEl?.classList.remove("hidden");

          if (reduced) {
            finishReading();
            return;
          }

          let idx = 0;
          const scanNext = () => {
            if (currentSeq !== seqId) return;
            if (idx > 0 && tiles[idx - 1]) {
              tiles[idx - 1].setAttribute("data-scan", "done");
            }
            if (idx >= tiles.length) {
              finishReading();
              return;
            }
            const tile = tiles[idx];
            const pageNum = Number(tile.dataset.attTile);
            tile.setAttribute("data-scan", "reading");
            if (scanLabel) {
              scanLabel.textContent = `Reading page ${pageNum} of ${tiles.length}…`;
            }
            idx += 1;
            scanTimer = window.setTimeout(scanNext, 160);
          };

          scanNext();
        };

        if (reduced) {
          setProgress(100);
          scanTimer = window.setTimeout(startReading, 140);
          return;
        }

        let step = 0;
        const totalSteps = 16;
        uploadTimer = window.setInterval(() => {
          if (currentSeq !== seqId) return;
          step += 1;
          const pct = Math.min(100, (step / totalSteps) * 100);
          const loadedMb = (totalMb * pct) / 100;
          setProgress(pct);
          if (metaEl) {
            metaEl.textContent = `${loadedMb.toFixed(1)} MB of ${totalMb.toFixed(1)} MB`;
          }

          if (step >= totalSteps) {
            window.clearInterval(uploadTimer);
            uploadTimer = 0;
            scanTimer = window.setTimeout(startReading, 150);
          }
        }, 100);
      };

      tiles.forEach((tile) => {
        tile.addEventListener("click", () => {
          const num = Number(tile.dataset.attTile);
          if (Number.isFinite(num)) {
            selectPage(num, true);
          }
        });
      });

      citeBtns.forEach((btn) => {
        btn.addEventListener("click", () => {
          const num = Number(btn.dataset.attCite);
          if (Number.isFinite(num)) {
            selectPage(num, true);
          }
        });
      });

      replayBtn?.addEventListener("click", () => {
        runSequence(true);
      });

      runSequence(false);
    });
  }

  initAiAttachment();
  document.addEventListener("astro:page-load", initAiAttachment);
</script>
```
