# Text morph

> A changing text label reuses matching characters and moves new glyphs into place within a short transition.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/text-morph`
- File: `src/components/haze/ui/text-morph.astro`
- npm dependencies: none
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/text-morph

## Use when
- A compact status or action label changes after a real state update
- Shared letters can help connect the previous label to its replacement

## Avoid when
- Use text-reveal when the sentence stays the same and only its entrance changes
- Use status for a persistent semantic state with an icon

## Alternatives
- [text-reveal](https://hazeui.com/ui/text-reveal.md)
- [status](https://hazeui.com/ui/status.md)
- [action-swap](https://hazeui.com/ui/action-swap.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller-supplied prefix for this component and its related elements. |
| text | `string` | "Ready to review" | no | Initial label; update the root data-text attribute for later values. |
| class | `string` |  | no | Additional classes for the component root. |

## Accessibility
- A visually hidden copy exposes the complete current label while animated glyphs are decorative.
- The host decides whether changes deserve an aria-live announcement; this component does not announce every replacement.
- Repeated character occurrences are matched in order, and reduced motion replaces the text immediately.

## Agent prompts

### Install and use

Install the Haze UI component "Text morph" with `npx shadcn@latest add @haze/text-morph`. 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 TextMorph from "@/components/haze/ui/text-morph.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/ui/text-morph.md

### Customize with real content

Adapt the Haze text-morph ui for our product. Replace the demo values of these props with our real content: id, text, class. Keep the layout, the heading level rules and these accessibility details: A visually hidden copy exposes the complete current label while animated glyphs are decorative. The host decides whether changes deserve an aria-live announcement; this component does not announce every replacement. Repeated character occurrences are matched in order, and reduced motion replaces the text immediately. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using text-morph, check it fits: use it when a compact status or action label changes after a real state update; shared letters can help connect the previous label to its replacement. Avoid it when use text-reveal when the sentence stays the same and only its entrance changes; use status for a persistent semantic state with an icon. Alternatives: @haze/text-reveal, @haze/status, @haze/action-swap.

## Example requests that should lead here
- Add a compact review-state label that morphs when its data-text value changes.

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface Props {
  id: string;
  text?: string;
  class?: string;
}
const { id, text = "Ready to review", class: className } = Astro.props;
---

<span id={id} data-haze-text-morph data-text={text} class={cn("inline-block max-w-full align-bottom text-[0.8125rem]/5 font-medium tracking-[-0.01em]", className)}><span data-morph-accessible class="sr-only">{text}</span><span data-morph-visual aria-hidden="true" class="inline-block whitespace-pre-wrap wrap-anywhere">{Array.from(text).map(character => <span class="inline-block">{character === " " ? "\u00a0" : character}</span>)}</span></span>

<script>
  function initTextMorphs() {
    document.querySelectorAll<HTMLElement>("[data-haze-text-morph]").forEach(root => {
      if (root.hasAttribute("data-enhanced")) return;
      const accessible = root.querySelector<HTMLElement>("[data-morph-accessible]");
      const visual = root.querySelector<HTMLElement>("[data-morph-visual]");
      if (!accessible || !visual) return;
      let text = root.dataset.text ?? "";
      let animations: Animation[] = [];
      const update = () => {
        const next = root.dataset.text ?? "";
        if (next === text) return;
        const oldText = text;
        text = next;
        animations.forEach(animation => animation.cancel());
        animations = [];
        const oldWidth = root.getBoundingClientRect().width;
        visual.style.removeProperty("width");
        // Digits are keyed by place from the right ("1,204 to 1,318" moves only the changed digits, like Torph/NumberFlow);
        // every other character is keyed by its glyph and slides to its new position.
        const isDigit = (character: string) => /\p{Nd}/u.test(character);
        const placeKey = (character: string, index: number, length: number) => isDigit(character) ? `#${length - index}` : character;
        const numeric = (value: string) => Number.parseFloat(value.replace(/[^0-9.-]/g, ""));
        const direction = numeric(next) >= numeric(oldText) ? 1 : -1;
        const previous = new Map<string, { rect: DOMRect; character: string }[]>();
        const oldChars = Array.from(oldText);
        Array.from(visual.children).forEach((child, index) => {
          const character = oldChars[index] ?? "";
          const key = placeKey(character, index, oldChars.length);
          previous.set(key, [...previous.get(key) ?? [], { rect: child.getBoundingClientRect(), character }]);
        });
        accessible.textContent = next;
        visual.replaceChildren(...Array.from(next).map(character => { const span = document.createElement("span"); span.className = "relative inline-block"; span.textContent = character === " " ? "\u00a0" : character; return span; }));
        if (matchMedia("(prefers-reduced-motion: reduce)").matches) return;
        const width = root.getBoundingClientRect().width;
        visual.style.width = `${visual.getBoundingClientRect().width}px`;
        const resizing = root.animate([{ width: `${oldWidth}px` }, { width: `${width}px` }], { duration: 250, easing: "cubic-bezier(.22,1,.36,1)" });
        animations.push(resizing);
        resizing.finished.then(() => { if (text === next) visual.style.removeProperty("width"); }).catch(() => {});
        const newChars = Array.from(next);
        Array.from(visual.children).forEach((child, index) => {
          const character = newChars[index] ?? "";
          const old = previous.get(placeKey(character, index, newChars.length))?.shift();
          const rect = child.getBoundingClientRect();
          const timing = { duration: 250, easing: "cubic-bezier(.22,1,.36,1)" };
          if (old && old.character === character) {
            if (old.rect.left === rect.left && old.rect.top === rect.top) return;
            animations.push(child.animate([{ translate: `${old.rect.left - rect.left}px ${old.rect.top - rect.top}px` }, { translate: "0 0" }], timing));
            return;
          }
          const shift = isDigit(character) ? direction * 60 : 25;
          animations.push(child.animate([{ opacity: 0, translate: `0 ${shift}%` }, { opacity: 1, translate: "0 0" }], timing));
          if (old) {
            const ghost = document.createElement("span");
            ghost.className = "absolute inset-0";
            ghost.textContent = old.character === " " ? " " : old.character;
            child.append(ghost);
            const out = ghost.animate([{ opacity: 1, translate: "0 0" }, { opacity: 0, translate: `0 ${-shift}%` }], timing);
            animations.push(out);
            out.finished.then(() => ghost.remove(), () => ghost.remove());
          }
        });
      };
      new MutationObserver(update).observe(root, { attributes: true, attributeFilter: ["data-text"] });
      root.setAttribute("data-enhanced", "");
    });
  }
  initTextMorphs();
  if (!document.documentElement.hasAttribute("data-haze-text-morph-listener")) {
    document.documentElement.setAttribute("data-haze-text-morph-listener", "");
    document.addEventListener("astro:page-load", initTextMorphs);
  }
</script>
```
