Skip to content
Shaken UI
Sign in

Text Reveal

Save

Reveals text as a whole, by line, by word, or by character with a fade, a short rise, or a blur that comes into focus, on mount, in view, or on demand.

Category
Core
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Text Reveal preview

The migration finished in 4 minutes

All 2,318 rows moved to the new schema. The old table stays readable for seven days, then it is dropped on its own.

Installation

npx @shakenui/cli add text-reveal

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add text-reveal --dry-run

Usage

text-reveal-example.tsx
import { TextReveal } from "@/components/shaken/ui/text-reveal";

export default function TextRevealExample() {
  return (
    <div className="grid w-full max-w-md gap-3">
      <TextReveal as="h2" by="word" effect="rise" className="text-2xl font-semibold tracking-[-0.02em] text-zinc-950 dark:text-white">
        Your agents closed 14 tickets overnight
      </TextReveal>
      <TextReveal by="line" effect="blur" delay={0.25} className="text-sm leading-relaxed text-zinc-600 dark:text-zinc-400">
        Three pull requests are waiting for review, and one deploy is paused until you approve the database migration it needs. Everything
        else shipped without a retry.
      </TextReveal>
    </div>
  );
}

API

PropTypeDefaultDescription
childrenstring—The text to reveal. Plain text, so it can be split.
by"whole" | "line" | "word" | "character""word"The unit that appears together. Lines are measured from where the text wraps and re-measured on resize.
effect"fade" | "rise" | "blur""rise"Opacity only, a short lift, or a blur that sharpens.
trigger"mount" | "inView" | "manual""mount"When to reveal: on first render, once scrolled into view, or following show.
showbooleantrueWith trigger="manual", shows the text when true and hides it with a quick plain fade when false.
staggernumber—Seconds between pieces. Defaults to 0.09 for lines, 0.04 for words and 0.016 for characters.
maxSpreadnumber1.2The longest time in seconds between the first and last piece starting; long texts compress the stagger to fit.
delay / durationnumber—Seconds before the first piece, and seconds each piece takes.
as"p" | "span" | "div" | "h1" to "h4" | "blockquote" | "figcaption" | "li""p"Element to render.
onRevealComplete() => void—Called once the last piece has appeared.

Accessibility

  • The full text sits once in the accessibility tree in a visually hidden span; the split pieces are aria-hidden, so screen readers never read it letter by letter.
  • Headings keep their role and their accessible name is the full text.
  • Characters of one word stay in one unbreakable group, and graphemes such as emoji are split with Intl.Segmenter so they never break apart.
  • Hiding is a short fade without movement.
  • With reduced motion preferred, the text appears at once with no movement, blur, or fade.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/text-reveal.tsxtext-reveal
  • npm packages: motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/text-reveal/0.1.0.json.

ui/text-reveal.tsxShow
ui/text-reveal.tsx
"use client";

import { motion, useInView, useReducedMotion, type Variants } from "motion/react";
import { type ComponentProps, type ElementType, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

export type TextRevealBy = "whole" | "line" | "word" | "character";
export type TextRevealEffect = "fade" | "rise" | "blur";
export type TextRevealTrigger = "mount" | "inView" | "manual";

type RevealElement = "p" | "span" | "div" | "h1" | "h2" | "h3" | "h4" | "blockquote" | "figcaption" | "li";

export interface TextRevealProps extends Omit<ComponentProps<"p">, "children"> {
  /** The text to reveal. Plain text only, so it can be split. */
  children: string;
  /** The unit that appears together: the whole block, each wrapped line, each word, or each character. */
  by?: TextRevealBy;
  /** `fade` changes opacity only, `rise` lifts each piece a little, `blur` brings each piece into focus. */
  effect?: TextRevealEffect;
  /** `mount` reveals on first render, `inView` when scrolled into view (once), `manual` follows `show`. */
  trigger?: TextRevealTrigger;
  /** With `trigger="manual"`, shows the text when true and hides it when false. */
  show?: boolean;
  /** Seconds between pieces. Long texts compress it so the whole reveal stays under `maxSpread`. */
  stagger?: number;
  /** Seconds before the first piece starts. */
  delay?: number;
  /** Seconds each piece takes. Defaults depend on `by`. */
  duration?: number;
  /** The longest time, in seconds, between the first piece starting and the last one starting. */
  maxSpread?: number;
  /** Element to render. */
  as?: RevealElement;
  /** Called once the last piece has finished appearing. */
  onRevealComplete?: () => void;
}

const ease = [0.23, 1, 0.32, 1] as const;

/** Reduced-motion preference, read only after hydration so server and client render the same markup first. */
function useReducedMotionAfterMount() {
  const reduce = useReducedMotion();
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  return mounted && reduce === true;
}

const defaults: Record<TextRevealBy, { stagger: number; duration: number }> = {
  whole: { stagger: 0, duration: 0.6 },
  line: { stagger: 0.09, duration: 0.6 },
  word: { stagger: 0.04, duration: 0.5 },
  character: { stagger: 0.016, duration: 0.42 },
};

const hiddenState: Record<TextRevealEffect, Record<string, string | number>> = {
  fade: { opacity: 0 },
  rise: { opacity: 0, y: "0.45em" },
  blur: { opacity: 0, y: "0.1em", filter: "blur(8px)" },
};

const shownState: Record<TextRevealEffect, Record<string, string | number>> = {
  fade: { opacity: 1 },
  rise: { opacity: 1, y: "0em" },
  blur: { opacity: 1, y: "0em", filter: "blur(0px)" },
};

function graphemes(word: string): string[] {
  if (typeof Intl !== "undefined" && "Segmenter" in Intl) {
    return Array.from(new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(word), (part) => part.segment);
  }
  return Array.from(word);
}

type Token = { word: string; chars: string[]; index: number } | { space: string };

function tokenize(text: string, by: TextRevealBy): Token[] {
  const tokens: Token[] = [];
  let index = 0;
  for (const part of text.split(/(\s+)/)) {
    if (!part) continue;
    if (/^\s+$/.test(part)) tokens.push({ space: part });
    else {
      const chars = by === "character" ? graphemes(part) : [part];
      tokens.push({ word: part, chars, index });
      index += chars.length;
    }
  }
  return tokens;
}

/**
 * Reveals text as a whole, by line, by word, or by character, with a fade, a short rise, or a
 * blur that comes into focus. Hiding is a quick plain fade, so leaving never competes with the
 * next thing on screen. The full text sits once in the accessibility tree; the animated pieces
 * are hidden from screen readers.
 */
export function TextReveal({
  children: text,
  by = "word",
  effect = "rise",
  trigger = "mount",
  show = true,
  stagger,
  delay = 0,
  duration,
  maxSpread = 1.2,
  as = "p",
  onRevealComplete,
  className,
  ...props
}: TextRevealProps) {
  const Root = as as ElementType;
  const rootRef = useRef<HTMLElement>(null);
  const reduceMotion = useReducedMotionAfterMount();
  const inView = useInView(rootRef, { once: true, amount: 0.35 });
  const visible = trigger === "manual" ? show : trigger === "inView" ? inView : true;

  const tokens = useMemo(() => tokenize(text, by), [text, by]);
  const wordCount = tokens.filter((token) => "word" in token).length;
  const pieceCount = by === "character" ? tokens.reduce((sum, token) => sum + ("chars" in token ? token.chars.length : 0), 0) : wordCount;

  // Lines are found by measuring where each word wrapped, and measured again when the width changes.
  const wordRefs = useRef<(HTMLSpanElement | null)[]>([]);
  const [lines, setLines] = useState<number[] | null>(null);
  useLayoutEffect(() => {
    if (by !== "line") return;
    const root = rootRef.current;
    if (!root) return;
    const measure = () => {
      let line = -1;
      let lastTop = Number.NEGATIVE_INFINITY;
      const next = wordRefs.current.slice(0, wordCount).map((element) => {
        const top = element?.offsetTop ?? lastTop;
        if (top > lastTop + 2) {
          line += 1;
          lastTop = top;
        }
        return Math.max(line, 0);
      });
      setLines((previous) => (previous && previous.join() === next.join() ? previous : next));
    };
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(root);
    return () => observer.disconnect();
  }, [by, wordCount, text]);

  const timing = defaults[by];
  const pieceDuration = duration ?? timing.duration;
  const steps = by === "line" ? Math.max(0, ...(lines ?? [])) : Math.max(pieceCount - 1, 0);
  const baseStagger = stagger ?? timing.stagger;
  const spread = steps > 0 ? Math.min(baseStagger, maxSpread / steps) : 0;

  const variants: Variants = useMemo(
    () => ({
      hidden: { ...hiddenState[effect], transition: { duration: 0.16, ease: "easeOut" } },
      shown: (order: number) => ({ ...shownState[effect], transition: { duration: pieceDuration, ease, delay: delay + order * spread } }),
    }),
    [effect, pieceDuration, delay, spread],
  );

  const ready = by !== "line" || lines !== null;
  const animateTo = visible && ready ? "shown" : "hidden";
  const lastOrder = by === "whole" ? 0 : steps;

  function piece(content: string, order: number, key: string | number, ref?: (element: HTMLSpanElement | null) => void) {
    if (reduceMotion) {
      return (
        <span key={key} ref={ref} className={cx("inline-block whitespace-pre", !visible && "opacity-0")}>
          {content}
        </span>
      );
    }
    return (
      <motion.span
        key={key}
        ref={ref}
        custom={order}
        variants={variants}
        initial="hidden"
        animate={animateTo}
        onAnimationComplete={order === lastOrder ? (definition) => definition === "shown" && onRevealComplete?.() : undefined}
        className="inline-block whitespace-pre"
      >
        {content}
      </motion.span>
    );
  }

  let visual;
  if (by === "whole") {
    visual = reduceMotion ? (
      <span className={cx(!visible && "opacity-0")}>{text}</span>
    ) : (
      <motion.span
        custom={0}
        variants={variants}
        initial="hidden"
        animate={animateTo}
        onAnimationComplete={(definition) => definition === "shown" && onRevealComplete?.()}
        className="inline-block"
      >
        {text}
      </motion.span>
    );
  } else {
    let wordIndex = -1;
    visual = tokens.map((token, tokenIndex) => {
      if ("space" in token) return token.space;
      wordIndex += 1;
      const current = wordIndex;
      const setRef = (element: HTMLSpanElement | null) => {
        wordRefs.current[current] = element;
      };
      if (by === "character") {
        // Characters of one word stay together so a word never breaks mid-reveal.
        return (
          <span key={tokenIndex} ref={setRef} className="inline-block whitespace-nowrap">
            {token.chars.map((char, charIndex) => piece(char, token.index + charIndex, charIndex))}
          </span>
        );
      }
      const order = by === "line" ? (lines?.[current] ?? 0) : current;
      return piece(token.word, order, tokenIndex, setRef);
    });
  }

  return (
    <Root ref={rootRef} className={className} {...props}>
      <span className="sr-only select-none">{text}</span>
      <span aria-hidden="true">{visual}</span>
    </Root>
  );
}