Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All componentsStream textAI
PreviousNext: Tool trace
Why does the island wait before it shrinks?

Watch the answer stream in. Turn the blur up to see each burst of words land.

Stream text

AI

Text that arrives the way a model writes it. Each new word clears out of a blur while the words already there stay perfectly still, and a soft caret rides the end until the stream stops.

Customize 4

6
500
1.00
Install & copy sourceInstall & copy sourceSee propsSee props6

Live code

As tuned above.

Every control in the inspector updates this snippet directly. Defaults are omitted to keep your markup minimal.

example.tsx

import { StreamText } from '@/components/lilt/ui/stream-text';

export function Answer({ text, done }: { text: string; done: boolean }) {
  return <StreamText text={text} streaming={!done} />;
}

Installation1

Source you own.

This is source, not a package: the shadcn CLI copies it into your project and it is yours to change. Take it whole, or lift the one detail you like.

$npx shadcn@latest add https://liltui.vercel.app/r/stream-text.json
components/lilt/ui/stream-text.tsx

stream-text.tsx

'use client';

import { AnimatePresence, motion, useReducedMotion } from 'motion/react';
import { useCallback, useRef, type CSSProperties } from 'react';

export interface StreamTextProps {
  /** Everything received so far. Pass the growing text as it streams in. */
  text: string;
  /** Still arriving: a caret rides the end of the text until it stops. Default false. */
  streaming?: boolean;
  /** Milliseconds a new word takes to clear. Default 500. */
  duration?: number;
  /** How blurred a word arrives, in pixels. Default 6. */
  blur?: number;
  /** Show the caret while streaming. Default true. */
  caret?: boolean;
  className?: string;
  style?: CSSProperties;
}

interface Piece {
  /** Where it starts in the text, which keys it. */
  at: number;
  text: string;
  /** Seconds after it arrives that it starts to clear, so a burst of words reads left to right. */
  delay: number;
}

const STAGGER = 0.035;
const MOST_STAGGER = 0.28;
const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)';

/** The new text, cut into words that each keep the space before them. */
function piecesOf(text: string, from: number): Piece[] {
  const pieces: Piece[] = [];
  let at = from;
  for (const [index, word] of (text.slice(from).match(/\s*\S+|\s+/g) ?? []).entries()) {
    pieces.push({ at, text: word, delay: Math.min(index * STAGGER, MOST_STAGGER) });
    at += word.length;
  }
  return pieces;
}

/**
 * Text that arrives the way a model writes it. Each new word clears out of a blur, a burst of
 * them a beat apart, while the words already there stay perfectly still; even a word that arrives
 * in halves blurs in half by half. A quiet caret rides the end while it streams and blurs away
 * when it stops. Pass the whole text so far each time; if it stops being a continuation, it starts
 * over.
 */
export function StreamText({
  text,
  streaming = false,
  duration = 500,
  blur = 6,
  caret = true,
  className,
  style,
}: StreamTextProps) {
  const reduced = useReducedMotion();
  const memo = useRef<{ text: string; pieces: Piece[] }>({ text: '', pieces: [] });
  if (memo.current.text !== text) {
    const continues = text.startsWith(memo.current.text);
    memo.current = {
      text,
      pieces: continues
        ? [...memo.current.pieces, ...piecesOf(text, memo.current.text.length)]
        : piecesOf(text, 0),
    };
  }

  // Read when a word lands, so changing them never replays the words already there.
  const settings = useRef({ duration, blur, reduced });
  settings.current = { duration, blur, reduced };
  // Each word animates once, when it lands; a stable ref means a re-render never replays it.
  const arrive = useCallback((element: HTMLSpanElement | null) => {
    const { duration, blur, reduced } = settings.current;
    if (!element || reduced || typeof element.animate !== 'function') return;
    element.animate(
      [
        { opacity: 0, filter: `blur(${blur}px)` },
        { opacity: 1, filter: 'blur(0px)' },
      ],
      { duration, delay: Number(element.dataset.delay) * 1000, easing: EASE, fill: 'backwards' },
    );
  }, []);

  return (
    <>
      <style href="lilt-ui-stream-text" precedence="default">
        {css}
      </style>
      <div
        className={['lilt-stx', className].filter(Boolean).join(' ')}
        aria-busy={streaming}
        style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', ...style }}
      >
        {memo.current.pieces.map((piece) => (
          <span key={piece.at} ref={arrive} data-delay={piece.delay}>
            {piece.text}
          </span>
        ))}
        <AnimatePresence>
          {streaming && caret ? (
            <motion.span
              aria-hidden="true"
              className="lilt-stx-caret"
              initial={{ opacity: 0, scale: 0.4, filter: 'blur(4px)' }}
              animate={{ opacity: 0.85, scale: 1, filter: 'blur(0px)' }}
              exit={{ opacity: 0, scale: 0.4, filter: 'blur(4px)' }}
              transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
            />
          ) : null}
        </AnimatePresence>
      </div>
    </>
  );
}

const css = /* css */ `
.lilt-stx {
  -webkit-font-smoothing: antialiased;
}
.lilt-stx-caret {
  display: inline-block;
  width: 0.56em;
  height: 0.56em;
  margin-left: 0.28em;
  border-radius: 50%;
  vertical-align: -0.03em;
  background: currentColor;
  animation: lilt-stx-pulse 1.4s ease-in-out infinite;
}
@keyframes lilt-stx-pulse {
  0%, 100% { opacity: 0.4; }
  50% { opacity: 0.9; }
}
@media (prefers-reduced-motion: reduce) {
  .lilt-stx-caret { animation: none; }
}
`;

Usage

How it behaves.

It inherits its font and takes its colours from the text colour around it, so it fits light and dark pages alike. It needs React and Motion; the shadcn CLI installs Motion for you. With reduced motion it keeps its states but drops the movement. Only the new words animate, each once, so a long answer costs no more than a short one. It keeps the text's line breaks; render Markdown yourself once it finishes if you need it.

Props6

Every option.

Pass these directly to StreamText.

PropTypeDefaultWhat it does
blurnumber6How blurred a word arrives, in pixels.
durationnumber500Milliseconds a new word takes to clear.
caretbooleantrueA soft dot riding the end of the text while it streams.
textstring—Everything received so far. Pass the growing text each time; if it stops being a continuation, it starts over.
streamingbooleanfalseStill arriving. Shows the caret, and sets `aria-busy`.
className, stylestring, CSSProperties—Passed to the outer element.
Previous componentThinkingNext componentTool trace

Ready when your data is. Start with one install.

Install a package, import the stylesheet once, and drop in a card or a scene.

Read the guideRead the guideView on GitHubView on GitHub
ChartsAll chartsAll chartsFinanceFinanceCustomizeCustomizeFeaturesFeatures
ComponentsAll componentsAll componentsAIAIStatusStatusActionsActionsDataData
VisualsAll visualsAll visualsAIAIDataDataSecuritySecurityProductProduct
ASCIIAll scenesAll scenesTextTextInterfaceInterfaceBackgroundsBackgroundsMediaMediaDataData
DocsGetting startedGetting startedAPI referenceAPI referenceMotion & accessibilityMotion & accessibilityllms.txtllms.txt
React components with a little lilt.GitHubGitHubnpmnpm