# AI state loading

> Borderless collapsible AI progress log tracking ordered steps with a vertical timeline stem, mono sub-logs, timer and auto-fold summary.

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

## Use when
- Showing multi-stage reasoning or retrieval progress while an AI assistant prepares a response
- Collapsing finished tool and search steps into a compact summary row users can inspect on demand

## Avoid when
- A single lightweight thinking phrase without per-step timing is enough; use ai-text-loading instead
- Displaying detailed JSON arguments and outputs for individual function calls; use ai-tool-calls

## Alternatives
- [ai-text-loading](https://hazeui.com/blocks/ai-text-loading.md)
- [ai-tool-calls](https://hazeui.com/blocks/ai-tool-calls.md)
- [workflow-steps](https://hazeui.com/ui/workflow-steps.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-loading" | no | Prefix used for landmark heading and collapsible panel ARIA IDs. |
| heading | `string` | "Agent progress" | no | Screen-reader landmark heading for the progress region. |
| steps | `{ label: string; detail: string; durationMs: number }[]` | 4 demo agent steps | no | Ordered steps with mono sub-log detail and duration in milliseconds. |
| autoStart | `boolean` | true | no | Automatically starts the step progression sequence on load. |
| class | `string` |  | no | Extra classes applied to the outer section. |

## Accessibility
- Top summary row is a native disclosure button with aria-expanded and aria-controls linked to the ordered vertical step list.
- Run start, completion, auto-fold and manual collapse changes are announced politely in a role="status" live region.
- Key Tab: Move focus between the collapsible progress toggle and the Replay button once completed
- Key Enter / Space: Toggle the step list open or closed, or replay the timed sequence

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze ai-loading block for our product. Replace the demo values of these props with our real content: id, heading, steps, autoStart, class. Keep the layout, the heading level rules and these accessibility details: Top summary row is a native disclosure button with aria-expanded and aria-controls linked to the ordered vertical step list. Run start, completion, auto-fold and manual collapse changes are announced politely in a role="status" live region. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-loading, check it fits: use it when showing multi-stage reasoning or retrieval progress while an ai assistant prepares a response; collapsing finished tool and search steps into a compact summary row users can inspect on demand. Avoid it when a single lightweight thinking phrase without per-step timing is enough; use ai-text-loading instead; displaying detailed json arguments and outputs for individual function calls; use ai-tool-calls. Alternatives: @haze/ai-text-loading, @haze/ai-tool-calls, @haze/workflow-steps.

## Example requests that should lead here
- Add a borderless AI state loading block with four timed steps, a vertical stem, mono sub-log lines and an auto-folding summary row

## Source

```astro
---
import { Check, ChevronDown, RotateCcw } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface LoadingStep {
  label: string;
  detail: string;
  durationMs: number;
}

interface Props {
  id?: string;
  heading?: string;
  steps?: LoadingStep[];
  autoStart?: boolean;
  class?: string;
}

const {
  id = "haze-ai-loading",
  heading = "Agent progress",
  steps = [
    { label: "Searching the web", detail: "query: loading states in agent UIs", durationMs: 1100 },
    { label: "Reading 4 sources", detail: "fetch: 4 docs · 18.4 KB extracted", durationMs: 1000 },
    { label: "Comparing approaches", detail: "rank: clarity, latency, motion safety", durationMs: 1100 },
    { label: "Writing the summary", detail: "draft: 3 key findings ready", durationMs: 1000 },
  ],
  autoStart = true,
  class: className,
} = Astro.props;
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-loading
  data-auto-start={String(autoStart)}
  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-sm">
    <button
      type="button"
      data-load-toggle
      aria-expanded="true"
      aria-controls={`${id}-steps`}
      class="flex min-h-9 w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-1 py-1 text-left transition-colors duration-150 ease-snappy hover:bg-accent/50 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
    >
      <span class="flex min-w-0 items-baseline gap-2">
        <span data-load-head-label class="truncate text-sm/5 font-medium text-foreground">
          {steps[0]?.label ?? "Working…"}
        </span>
        <span
          data-load-timer
          class="shrink-0 font-mono text-xs/5 text-muted-foreground tabular-nums"
        >
          1s
        </span>
      </span>

      <ChevronDown
        data-load-chevron
        class="size-4 shrink-0 rotate-180 text-muted-foreground transition-transform duration-150 ease-snappy"
        aria-hidden="true"
      />
    </button>

    <div id={`${id}-steps`} data-load-panel class="mt-3 pl-1">
      <ol class="space-y-0">
        {
          steps.map((step, index) => {
            const isLast = index === steps.length - 1;
            return (
              <li
                data-load-step={String(index)}
                data-duration={String(step.durationMs)}
                data-label={step.label}
                data-state={index === 0 ? "active" : "pending"}
                class="flex items-stretch gap-3"
              >
                <div class="flex w-4 shrink-0 flex-col items-center">
                  <span
                    data-step-icon="pending"
                    class={cn(
                      "mt-1.5 inline-flex size-2 shrink-0 items-center justify-center rounded-full bg-muted-foreground",
                      index === 0 && "hidden",
                    )}
                    aria-hidden="true"
                  ></span>

                  <span
                    data-step-icon="active"
                    class={cn(
                      "mt-0.5 inline-flex size-4 shrink-0 items-center justify-center",
                      index !== 0 && "hidden",
                    )}
                    aria-hidden="true"
                  >
                    <svg
                      viewBox="0 0 16 16"
                      class="size-3.5 motion-safe:animate-spin"
                      fill="none"
                      aria-hidden="true"
                    >
                      <circle
                        cx="8"
                        cy="8"
                        r="6"
                        class="stroke-border"
                        stroke-width="1.75"
                      />
                      <circle
                        cx="8"
                        cy="8"
                        r="6"
                        class="stroke-success"
                        stroke-width="1.75"
                        stroke-linecap="round"
                        stroke-dasharray="12 28"
                      />
                    </svg>
                  </span>

                  <span
                    data-step-icon="done"
                    class="mt-0.5 hidden size-4 shrink-0 items-center justify-center text-success"
                    aria-hidden="true"
                  >
                    <Check class="size-3.5" aria-hidden="true" />
                  </span>

                  {
                    !isLast && (
                      <span
                        class="my-1.5 w-px min-h-3 flex-1 bg-border"
                        aria-hidden="true"
                      ></span>
                    )
                  }
                </div>

                <div class={cn("min-w-0 flex-1", !isLast && "pb-3")}>
                  <p
                    data-step-title
                    class={cn(
                      "text-sm/5 break-words transition-colors duration-150 ease-snappy",
                      index === 0 ? "font-medium text-foreground" : "text-muted-foreground",
                    )}
                  >
                    {step.label}
                  </p>

                  <p
                    data-step-detail
                    class={cn(
                      "mt-2 flex items-baseline gap-2.5 pl-1 font-mono text-xs/5 text-muted-foreground break-words",
                      index !== 0 && "hidden",
                    )}
                  >
                    <span class="shrink-0 tabular-nums">{index + 1}</span>
                    <span class="min-w-0 break-words">{step.detail}</span>
                  </p>
                </div>
              </li>
            );
          })
        }
      </ol>
    </div>

    <div data-load-replay-wrap class="mt-2 hidden pl-1">
      <button
        type="button"
        data-load-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>

    <p data-load-status role="status" aria-live="polite" class="sr-only"></p>
  </div>
</section>

<script>
  function initAiLoading() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-loading]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const toggleBtn = root.querySelector<HTMLButtonElement>("[data-load-toggle]");
      const panel = root.querySelector<HTMLElement>("[data-load-panel]");
      const chevron = root.querySelector<HTMLElement>("[data-load-chevron]");
      const headLabel = root.querySelector<HTMLElement>("[data-load-head-label]");
      const timerEl = root.querySelector<HTMLElement>("[data-load-timer]");
      const statusEl = root.querySelector<HTMLElement>("[data-load-status]");
      const replayWrap = root.querySelector<HTMLElement>("[data-load-replay-wrap]");
      const replayBtn = root.querySelector<HTMLButtonElement>("[data-load-replay]");
      const stepEls = Array.from(root.querySelectorAll<HTMLElement>("[data-load-step]"));

      if (!toggleBtn || !panel || stepEls.length === 0) return;

      let runId = 0;
      let timerHandle = 0;
      let stepHandle = 0;
      let foldHandle = 0;
      let userToggled = false;
      let startMs = 0;

      const setOpen = (open: boolean) => {
        toggleBtn.setAttribute("aria-expanded", String(open));
        panel.classList.toggle("hidden", !open);
        chevron?.classList.toggle("rotate-180", open);
      };

      const clearTimers = () => {
        if (timerHandle) window.clearInterval(timerHandle);
        if (stepHandle) window.clearTimeout(stepHandle);
        if (foldHandle) window.clearTimeout(foldHandle);
        timerHandle = 0;
        stepHandle = 0;
        foldHandle = 0;
      };

      const renderStep = (el: HTMLElement, state: "pending" | "active" | "done") => {
        el.setAttribute("data-state", state);
        const iconPending = el.querySelector<HTMLElement>('[data-step-icon="pending"]');
        const iconActive = el.querySelector<HTMLElement>('[data-step-icon="active"]');
        const iconDone = el.querySelector<HTMLElement>('[data-step-icon="done"]');
        const titleEl = el.querySelector<HTMLElement>("[data-step-title]");
        const detailEl = el.querySelector<HTMLElement>("[data-step-detail]");

        iconPending?.classList.toggle("hidden", state !== "pending");
        iconActive?.classList.toggle("hidden", state !== "active");
        iconDone?.classList.toggle("hidden", state !== "done");
        detailEl?.classList.toggle("hidden", state !== "active");

        if (titleEl) {
          titleEl.classList.toggle("text-foreground", state === "active");
          titleEl.classList.toggle("font-medium", state === "active");
          titleEl.classList.toggle("text-muted-foreground", state !== "active");
        }
      };

      const startRun = (announce: boolean) => {
        clearTimers();
        runId += 1;
        const currentRun = runId;
        userToggled = false;
        setOpen(true);
        replayWrap?.classList.add("hidden");

        const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
        const durations = stepEls.map((el) => {
          const raw = Number(el.dataset.duration ?? "1000");
          return Number.isFinite(raw) && raw > 0 ? raw : 1000;
        });

        if (timerEl) timerEl.textContent = "1s";
        if (announce && statusEl) {
          statusEl.textContent = `Running ${stepEls.length} steps.`;
        }

        stepEls.forEach((el, idx) => {
          renderStep(el, idx === 0 ? "active" : "pending");
        });

        startMs = performance.now();
        timerHandle = window.setInterval(() => {
          if (currentRun !== runId) return;
          const secs = Math.max(1, Math.ceil((performance.now() - startMs) / 1000));
          if (timerEl) timerEl.textContent = `${secs}s`;
        }, 250);

        const runStep = (idx: number) => {
          if (currentRun !== runId) return;
          const currentEl = stepEls[idx];
          if (!currentEl) return;

          const label = currentEl.dataset.label ?? `Step ${idx + 1}`;
          if (headLabel) headLabel.textContent = label;
          renderStep(currentEl, "active");

          const waitMs = reduced ? Math.min(220, durations[idx]) : durations[idx];
          stepHandle = window.setTimeout(() => {
            if (currentRun !== runId) return;
            renderStep(currentEl, "done");

            if (idx + 1 < stepEls.length) {
              runStep(idx + 1);
              return;
            }

            if (timerHandle) {
              window.clearInterval(timerHandle);
              timerHandle = 0;
            }

            const totalPlanned = (durations.reduce((a, b) => a + b, 0) / 1000).toFixed(1);
            const finalSec = reduced ? totalPlanned : ((performance.now() - startMs) / 1000).toFixed(1);
            if (headLabel) headLabel.textContent = `Completed ${stepEls.length} steps`;
            if (timerEl) timerEl.textContent = `· ${finalSec}s`;
            replayWrap?.classList.remove("hidden");

            if (statusEl) {
              statusEl.textContent = `Completed ${stepEls.length} steps in ${finalSec}s.`;
            }

            foldHandle = window.setTimeout(() => {
              if (currentRun !== runId || userToggled) return;
              setOpen(false);
            }, reduced ? 120 : 450);
          }, waitMs);
        };

        runStep(0);
      };

      toggleBtn.addEventListener("click", () => {
        userToggled = true;
        const expanded = toggleBtn.getAttribute("aria-expanded") === "true";
        setOpen(!expanded);
        if (statusEl) {
          statusEl.textContent = expanded ? "Step details collapsed." : "Step details expanded.";
        }
      });

      replayBtn?.addEventListener("click", () => {
        startRun(true);
      });

      if (root.dataset.autoStart !== "false") {
        startRun(false);
      }
    });
  }

  initAiLoading();
  document.addEventListener("astro:page-load", initAiLoading);
</script>
```
