# AI text loading

> Minimal centered AI thinking status text that cycles phrases with a per-character luminance wave and optional elapsed seconds readout.

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

## Use when
- Displaying a lightweight live thinking phrase while an AI reply is being prepared
- Replacing raw spinner rings with human-readable status cues that cycle through synthesis stages

## Avoid when
- Users need an expandable list of timed tool calls and execution logs; use ai-loading instead
- A compact inline loading indicator inside a button is needed; use spinner

## Alternatives
- [text-shimmer](https://hazeui.com/ui/text-shimmer.md)
- [ai-loading](https://hazeui.com/blocks/ai-loading.md)
- [spinner](https://hazeui.com/ui/spinner.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-text-loading" | no | Unique prefix for the section landmark heading ID. |
| heading | `string` | "Assistant thinking status" | no | Screen-reader landmark heading for the loading status region. |
| phrases | `string[]` | 4 demo thinking phrases | no | Ordered status phrases cycled with a per-character token luminance wave. |
| showElapsed | `boolean` | false | no | Shows a subtle live elapsed seconds readout beside the cycling phrase. |
| intervalMs | `number` | 2400 | no | Duration in milliseconds before advancing to the next phrase. |
| class | `string` |  | no | Extra classes applied to the outer section. |

## Accessibility
- Per-character visual spans carry aria-hidden="true" so assistive technology reads clean whole phrases from the polite role="status" region.
- Honors prefers-reduced-motion by disabling the character luminance wave and switching cleanly between whole phrases.
- Key Tab: Passes cleanly past the non-interactive status indicator without trapping focus

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze ai-text-loading block for our product. Replace the demo values of these props with our real content: id, heading, phrases, showElapsed, intervalMs, class. Keep the layout, the heading level rules and these accessibility details: Per-character visual spans carry aria-hidden="true" so assistive technology reads clean whole phrases from the polite role="status" region. Honors prefers-reduced-motion by disabling the character luminance wave and switching cleanly between whole phrases. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-text-loading, check it fits: use it when displaying a lightweight live thinking phrase while an ai reply is being prepared; replacing raw spinner rings with human-readable status cues that cycle through synthesis stages. Avoid it when users need an expandable list of timed tool calls and execution logs; use ai-loading instead; a compact inline loading indicator inside a button is needed; use spinner. Alternatives: @haze/text-shimmer, @haze/ai-loading, @haze/spinner.

## Example requests that should lead here
- Add a minimal borderless AI text loading block that sweeps foreground luminance across cycling thinking phrases

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface Props {
  id?: string;
  heading?: string;
  phrases?: string[];
  showElapsed?: boolean;
  intervalMs?: number;
  class?: string;
}

const {
  id = "haze-ai-text-loading",
  heading = "Assistant thinking status",
  phrases = [
    "Thinking…",
    "Processing…",
    "Analyzing…",
    "Drafting…",
  ],
  showElapsed = false,
  intervalMs = 2400,
  class: className,
} = Astro.props;

const initialPhrase = phrases[0] ?? "Thinking…";
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-text-loading
  data-phrases={JSON.stringify(phrases)}
  data-interval={String(intervalMs)}
  data-show-elapsed={String(showElapsed)}
  class={cn("bg-background px-4 py-14 sm:px-6 sm:py-20", className)}
>
  <h2 id={`${id}-title`} class="sr-only">{heading}</h2>

  <div class="mx-auto flex max-w-sm flex-wrap items-baseline justify-center gap-2.5 text-center">
    <p
      data-tl-stage
      aria-hidden="true"
      class="min-h-7 text-lg/7 font-medium tracking-tight text-muted-foreground break-words"
    >
      {
        Array.from(initialPhrase).map((ch, idx) => (
          <span
            class={cn(
              "inline-block transition-colors duration-150 ease-smooth",
              idx < 3 ? "text-foreground" : "text-muted-foreground",
            )}
          >
            {ch === " " ? "\u00A0" : ch}
          </span>
        ))
      }
    </p>

    {
      showElapsed && (
        <span
          data-tl-elapsed
          class="font-mono text-xs/5 text-muted-foreground tabular-nums"
        >
          0.0s
        </span>
      )
    }

    <p data-tl-status role="status" aria-live="polite" class="sr-only">
      {initialPhrase}
    </p>
  </div>
</section>

<script>
  function initAiTextLoading() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-text-loading]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const stageEl = root.querySelector<HTMLElement>("[data-tl-stage]");
      const elapsedEl = root.querySelector<HTMLElement>("[data-tl-elapsed]");
      const statusEl = root.querySelector<HTMLElement>("[data-tl-status]");

      if (!stageEl) return;

      let phrases: string[] = ["Thinking…", "Processing…", "Analyzing…", "Drafting…"];
      try {
        const parsed: unknown = JSON.parse(root.dataset.phrases ?? "[]");
        if (Array.isArray(parsed) && parsed.length > 0) {
          phrases = parsed.map((item) => String(item));
        }
      } catch {
        // keep defaults
      }

      const rawInterval = Number(root.dataset.interval ?? "2400");
      const intervalMs = Number.isFinite(rawInterval) && rawInterval >= 600 ? rawInterval : 2400;
      const reducedQuery = window.matchMedia("(prefers-reduced-motion: reduce)");

      let phraseIdx = 0;
      let wavePos = 0;
      let startMs = performance.now();
      let charSpans: HTMLSpanElement[] = [];

      const renderChars = (text: string, highlightAll: boolean) => {
        const frag = document.createDocumentFragment();
        const spans: HTMLSpanElement[] = [];
        for (const ch of Array.from(text)) {
          const span = document.createElement("span");
          span.className = highlightAll
            ? "inline-block transition-colors duration-150 ease-smooth text-foreground"
            : "inline-block transition-colors duration-150 ease-smooth text-muted-foreground";
          span.textContent = ch === " " ? "\u00A0" : ch;
          spans.push(span);
          frag.appendChild(span);
        }
        stageEl.replaceChildren(frag);
        charSpans = spans;
      };

      const paintWave = () => {
        if (reducedQuery.matches) return;
        for (let i = 0; i < charSpans.length; i += 1) {
          const lit = Math.abs(i - wavePos) <= 2;
          charSpans[i].classList.toggle("text-foreground", lit);
          charSpans[i].classList.toggle("text-muted-foreground", !lit);
        }
      };

      const setPhrase = (nextIdx: number) => {
        phraseIdx = nextIdx;
        const target = phrases[phraseIdx] ?? "";
        if (statusEl) statusEl.textContent = target;
        wavePos = 0;
        renderChars(target, reducedQuery.matches);
        paintWave();
      };

      renderChars(phrases[0] ?? "", reducedQuery.matches);
      paintWave();

      if (!reducedQuery.matches) {
        window.setInterval(() => {
          wavePos = (wavePos + 1) % (charSpans.length + 5);
          paintWave();
        }, 75);
      }

      if (phrases.length > 1) {
        window.setInterval(() => {
          setPhrase((phraseIdx + 1) % phrases.length);
        }, intervalMs);
      }

      if (elapsedEl) {
        startMs = performance.now();
        window.setInterval(() => {
          const secs = (performance.now() - startMs) / 1000;
          elapsedEl.textContent = `${secs.toFixed(1)}s`;
        }, 100);
      }
    });
  }

  initAiTextLoading();
  document.addEventListener("astro:page-load", initAiTextLoading);
</script>
```
