Text morph
A changing text label reuses matching characters and moves new glyphs into place within a short transition.
pnpm dlx shadcn@latest add @haze/text-morph---
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>When to use
- A compact status or action label changes after a real state update
- Shared letters can help connect the previous label to its replacement
When not to use
- Use text-reveal when the sentence stays the same and only its entrance changes
- Use status for a persistent semantic state with an icon
Installation
Add the Haze registry to components.json once, then install Text morph with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/text-morphnpx shadcn@latest add @haze/text-morphyarn dlx shadcn@latest add @haze/text-morphbunx --bun shadcn@latest add @haze/text-morphFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller-supplied prefix for this component and its related elements. |
| text | string | "Ready to review" | Initial label; update the root data-text attribute for later values. |
| class | string | – | 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.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
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": "http://localhost:4329/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: http://localhost:4329/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.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.