# AI token alternatives

> Compact chat card marking uncertain tokens with dotted underlines, a probability popover for downstream rewrites and a confidence switch.

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

## Use when
- Exposing token-level model uncertainty so editors can inspect alternative phrasing without regenerating an entire reply
- Building interactive writing or scheduling assistants where one word choice branches the remainder of the response

## Avoid when
- Users need full sentence-to-source attribution links rather than token probabilities; use ai-citations instead
- Comparing completely separate parallel assistant drafts side by side; use ai-branches

## Alternatives
- [ai-citations](https://hazeui.com/blocks/ai-citations.md)
- [ai-branches](https://hazeui.com/blocks/ai-branches.md)
- [ai-inline-rewrite](https://hazeui.com/blocks/ai-inline-rewrite.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-token-alternatives" | no | Unique prefix for landmark heading, popover and switch ARIA IDs. |
| heading | `string` | "Assistant reply with alternative tokens" | no | Screen-reader landmark heading for the chat card. |
| prompt | `string` | Launch review scheduling prompt | no | User prompt displayed in the right-aligned bubble above the assistant reply. |
| class | `string` |  | no | Extra classes applied to the outer section. |

## Accessibility
- Uncertain tokens are native buttons with aria-expanded and aria-controls linked to the candidate popover, which dismisses on Escape.
- The Confidence toggle uses role="switch" with aria-checked, and token swaps are announced politely in a role="status" live region.
- Key Tab: Move across dotted token buttons, candidate alternatives and the Confidence switch
- Key Enter / Space: Open candidate alternatives, swap a token to rewrite downstream or toggle confidence percentages
- Key Escape: Close the open token alternatives popover and return focus to the active word button

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze ai-token-alternatives block for our product. Replace the demo values of these props with our real content: id, heading, prompt, class. Keep the layout, the heading level rules and these accessibility details: Uncertain tokens are native buttons with aria-expanded and aria-controls linked to the candidate popover, which dismisses on Escape. The Confidence toggle uses role="switch" with aria-checked, and token swaps 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-token-alternatives, check it fits: use it when exposing token-level model uncertainty so editors can inspect alternative phrasing without regenerating an entire reply; building interactive writing or scheduling assistants where one word choice branches the remainder of the response. Avoid it when users need full sentence-to-source attribution links rather than token probabilities; use ai-citations instead; comparing completely separate parallel assistant drafts side by side; use ai-branches. Alternatives: @haze/ai-citations, @haze/ai-branches, @haze/ai-inline-rewrite.

## Example requests that should lead here
- Add an AI token alternatives chat card with subtle dotted uncertain words, a candidate probability popover and a Confidence switch footer

## Source

```astro
---
import { X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id?: string;
  heading?: string;
  prompt?: string;
  class?: string;
}

const {
  id = "haze-ai-token-alternatives",
  heading = "Assistant reply with alternative tokens",
  prompt = "Alex wants to push the launch review. Can you draft a quick reply?",
  class: className,
} = Astro.props;
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-token-alternatives
  data-show-confidence="false"
  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 overflow-hidden rounded-2xl border border-border bg-card shadow-key">
    <div class="space-y-5 p-5">
      <div class="flex justify-end">
        <p class="max-w-[85%] rounded-2xl bg-muted px-4 py-2.5 text-sm/5 text-foreground break-words">
          {prompt}
        </p>
      </div>

      <div>
        <p data-tok-reply class="text-[0.9375rem]/7 text-foreground break-words">
          <button
            type="button"
            data-tok-btn="0"
            aria-expanded="false"
            aria-controls={`${id}-panel`}
            class="inline-flex min-h-6 cursor-pointer items-baseline gap-1 rounded-sm px-0.5 align-baseline text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[active=true]:bg-accent data-[active=true]:text-foreground"
          >
            <span data-tok-word class="underline decoration-dotted decoration-muted-foreground underline-offset-4">Sure</span>
            <span data-tok-pct class="hidden rounded-sm bg-muted px-1 py-0.5 font-mono text-[0.625rem]/3 font-semibold text-foreground tabular-nums">58%</span>
            <span class="sr-only">, inspect alternatives</span>
          </button>
          <span data-tok-seg="0">, </span>
          <button
            type="button"
            data-tok-btn="1"
            aria-expanded="false"
            aria-controls={`${id}-panel`}
            class="inline-flex min-h-6 cursor-pointer items-baseline gap-1 rounded-sm px-0.5 align-baseline text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[active=true]:bg-accent data-[active=true]:text-foreground"
          >
            <span data-tok-word class="underline decoration-dotted decoration-muted-foreground underline-offset-4">Thursday</span>
            <span data-tok-pct class="hidden rounded-sm bg-muted px-1 py-0.5 font-mono text-[0.625rem]/3 font-semibold text-foreground tabular-nums">41%</span>
            <span class="sr-only">, inspect alternatives</span>
          </button>
          <span data-tok-seg="1"> works better for me, and it leaves time to share a </span>
          <button
            type="button"
            data-tok-btn="2"
            aria-expanded="false"
            aria-controls={`${id}-panel`}
            class="inline-flex min-h-6 cursor-pointer items-baseline gap-1 rounded-sm px-0.5 align-baseline text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[active=true]:bg-accent data-[active=true]:text-foreground"
          >
            <span data-tok-word class="underline decoration-dotted decoration-muted-foreground underline-offset-4">concise</span>
            <span data-tok-pct class="hidden rounded-sm bg-muted px-1 py-0.5 font-mono text-[0.625rem]/3 font-semibold text-foreground tabular-nums">64%</span>
            <span class="sr-only">, inspect alternatives</span>
          </button>
          <span data-tok-seg="2"> partner checklist before sign-off.</span>
        </p>

        <div
          id={`${id}-panel`}
          data-tok-panel
          class="mt-3 hidden rounded-xl border border-border bg-popover p-2.5 shadow-float"
        >
          <div class="flex items-center justify-between gap-2 px-1 pb-2">
            <h3 data-tok-panel-title class="text-xs/4 font-medium text-muted-foreground">
              Alternatives
            </h3>
            <button
              type="button"
              data-tok-close
              aria-label="Close token alternatives"
              class="inline-flex size-6 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 data-tok-options class="space-y-1"></div>
        </div>
      </div>
    </div>

    <div class="flex flex-wrap items-center justify-between gap-3 border-t border-border px-5 py-3">
      <div class="flex items-center gap-2.5">
        <button
          type="button"
          id={`${id}-confidence`}
          data-tok-confidence
          role="switch"
          aria-checked="false"
          aria-labelledby={`${id}-confidence-label`}
          class="relative inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border border-transparent bg-input p-0.5 transition-colors duration-150 ease-snappy focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
        >
          <span
            data-tok-thumb
            class="pointer-events-none block size-4 translate-x-0 rounded-full bg-foreground shadow-key transition-transform duration-150 ease-snappy"
          ></span>
        </button>
        <label
          id={`${id}-confidence-label`}
          for={`${id}-confidence`}
          class="cursor-pointer text-xs font-medium text-foreground select-none"
        >
          Confidence
        </label>
      </div>

      <span class="text-xs text-muted-foreground">
        Click a dotted word to swap it
      </span>
    </div>

    <p data-tok-status role="status" aria-live="polite" class="sr-only"></p>
  </div>
</section>

<script>
  interface TokenOption {
    word: string;
    prob: number;
    afterText: string;
    nextSelections?: Record<number, number>;
  }

  const TOKEN_SLOTS: TokenOption[][] = [
    [
      {
        word: "Sure",
        prob: 58,
        afterText: ", ",
        nextSelections: { 1: 0, 2: 0 },
      },
      {
        word: "Certainly",
        prob: 27,
        afterText: " — moving the review to ",
        nextSelections: { 1: 1, 2: 2 },
      },
      {
        word: "Probably",
        prob: 15,
        afterText: " — if QA signs off tonight, ",
        nextSelections: { 1: 2, 2: 1 },
      },
    ],
    [
      {
        word: "Thursday",
        prob: 41,
        afterText: " works better for me, and it leaves time to share a ",
        nextSelections: { 2: 0 },
      },
      {
        word: "Friday",
        prob: 34,
        afterText: " morning gives design an extra day and lets us send a ",
        nextSelections: { 2: 2 },
      },
      {
        word: "Monday",
        prob: 18,
        afterText: " clears the weekend freeze and gives us room for a ",
        nextSelections: { 2: 1 },
      },
    ],
    [
      {
        word: "concise",
        prob: 64,
        afterText: " partner checklist before sign-off.",
      },
      {
        word: "detailed",
        prob: 22,
        afterText: " rollout brief covering cutover windows and owners.",
      },
      {
        word: "final",
        prob: 14,
        afterText: " summary with updated dates and rollback steps.",
      },
    ],
  ];

  function initAiTokenAlternatives() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-token-alternatives]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const tokenBtns = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-tok-btn]"));
      const segEls = Array.from(root.querySelectorAll<HTMLElement>("[data-tok-seg]"));
      const panel = root.querySelector<HTMLElement>("[data-tok-panel]");
      const panelTitle = root.querySelector<HTMLElement>("[data-tok-panel-title]");
      const optionsWrap = root.querySelector<HTMLElement>("[data-tok-options]");
      const closeBtn = root.querySelector<HTMLButtonElement>("[data-tok-close]");
      const confSwitch = root.querySelector<HTMLButtonElement>("[data-tok-confidence]");
      const confThumb = root.querySelector<HTMLElement>("[data-tok-thumb]");
      const statusEl = root.querySelector<HTMLElement>("[data-tok-status]");

      if (!panel || !optionsWrap) return;

      const selected = [0, 0, 0];
      let openSlot: number | null = null;
      let showConfidence = false;

      const syncReply = () => {
        tokenBtns.forEach((btn, idx) => {
          const opt = TOKEN_SLOTS[idx]?.[selected[idx]];
          if (!opt) return;
          const wordEl = btn.querySelector<HTMLElement>("[data-tok-word]");
          const pctEl = btn.querySelector<HTMLElement>("[data-tok-pct]");
          if (wordEl) {
            wordEl.textContent = opt.word;
            wordEl.classList.toggle("decoration-foreground", showConfidence);
            wordEl.classList.toggle("decoration-muted-foreground", !showConfidence);
          }
          if (pctEl) {
            pctEl.textContent = `${opt.prob}%`;
            pctEl.classList.toggle("hidden", !showConfidence);
          }
          const isActive = openSlot === idx;
          btn.setAttribute("data-active", String(isActive));
          btn.setAttribute("aria-expanded", String(isActive));

          const seg = segEls[idx];
          if (seg) seg.textContent = opt.afterText;
        });
      };

      const closePanel = (announce: boolean) => {
        openSlot = null;
        panel.classList.add("hidden");
        syncReply();
        if (announce && statusEl) {
          statusEl.textContent = "Closed token alternatives.";
        }
      };

      const openPanelFor = (slotIdx: number) => {
        const candidates = TOKEN_SLOTS[slotIdx];
        if (!candidates) return;
        openSlot = slotIdx;
        const activeWord = candidates[selected[slotIdx]]?.word ?? "";
        if (panelTitle) {
          panelTitle.textContent = `Alternatives for “${activeWord}”`;
        }

        const frag = document.createDocumentFragment();
        candidates.forEach((cand, candIdx) => {
          const isPicked = selected[slotIdx] === candIdx;
          const btn = document.createElement("button");
          btn.type = "button";
          btn.setAttribute("aria-pressed", String(isPicked));
          btn.className =
            "flex w-full cursor-pointer items-center gap-3 rounded-lg px-2.5 py-2 text-left transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring aria-pressed:bg-accent";

          const wordSpan = document.createElement("span");
          wordSpan.className = "w-20 shrink-0 truncate text-xs/4 font-medium text-foreground";
          wordSpan.textContent = cand.word;

          const track = document.createElement("span");
          track.className = "block h-1.5 flex-1 overflow-hidden rounded-full bg-muted";
          track.setAttribute("aria-hidden", "true");

          const bar = document.createElement("span");
          bar.className = "block h-full rounded-full bg-primary transition-[width] duration-200 ease-smooth";
          bar.style.width = `${cand.prob}%`;
          track.appendChild(bar);

          const pctSpan = document.createElement("span");
          pctSpan.className = "w-9 shrink-0 text-right font-mono text-xs/4 text-muted-foreground tabular-nums";
          pctSpan.textContent = `${cand.prob}%`;

          btn.append(wordSpan, track, pctSpan);

          btn.addEventListener("click", () => {
            selected[slotIdx] = candIdx;
            if (cand.nextSelections) {
              Object.entries(cand.nextSelections).forEach(([k, v]) => {
                const targetIdx = Number(k);
                if (targetIdx > slotIdx && targetIdx < selected.length) {
                  selected[targetIdx] = v;
                }
              });
            }
            openSlot = null;
            panel.classList.add("hidden");
            syncReply();
            tokenBtns[slotIdx]?.focus();
            if (statusEl) {
              statusEl.textContent = `Swapped token to “${cand.word}” (${cand.prob}%) and updated the reply.`;
            }
          });

          frag.appendChild(btn);
        });

        optionsWrap.replaceChildren(frag);
        panel.classList.remove("hidden");
        syncReply();
      };

      tokenBtns.forEach((btn, idx) => {
        btn.addEventListener("click", () => {
          if (openSlot === idx) {
            closePanel(true);
            return;
          }
          openPanelFor(idx);
          const cur = TOKEN_SLOTS[idx]?.[selected[idx]];
          if (statusEl && cur) {
            statusEl.textContent = `Showing 3 alternatives for “${cur.word}”.`;
          }
        });
      });

      closeBtn?.addEventListener("click", () => closePanel(true));

      root.addEventListener("keydown", (ev) => {
        if (ev.key === "Escape" && openSlot !== null) {
          const returnBtn = tokenBtns[openSlot];
          closePanel(true);
          returnBtn?.focus();
        }
      });

      confSwitch?.addEventListener("click", () => {
        showConfidence = !showConfidence;
        confSwitch.setAttribute("aria-checked", String(showConfidence));
        confSwitch.classList.toggle("bg-primary", showConfidence);
        confSwitch.classList.toggle("bg-input", !showConfidence);
        confThumb?.classList.toggle("translate-x-4", showConfidence);
        confThumb?.classList.toggle("translate-x-0", !showConfidence);
        confThumb?.classList.toggle("bg-primary-foreground", showConfidence);
        confThumb?.classList.toggle("bg-foreground", !showConfidence);
        syncReply();
        if (statusEl) {
          statusEl.textContent = showConfidence
            ? "Token confidence percentages shown."
            : "Token confidence percentages hidden.";
        }
      });

      syncReply();
    });
  }

  initAiTokenAlternatives();
  document.addEventListener("astro:page-load", initAiTokenAlternatives);
</script>
```
