# Comet Text

Streaming text with a comet at its edge: a full block leads, and a trail of thinner and thinner bars resolves into the letters behind it.

Live demo: https://bearerop.in/craft/comet-text

## Install

### 1. Copy and paste the following code into your project.

One file, React only, no dependencies. It runs on requestAnimationFrame and re-renders once per character.

#### Usage

```tsx
import { CometText } from "@/components/craft/comet-text";

// Play a known text in
<p>
  <CometText text="The whole answer does not exist yet." speed={70} />
</p>

// Or feed it a reply as it arrives: appended text carries on, it does not restart
function Reply({ stream }: { stream: string }) {
  return (
    <p>
      <CometText text={stream} speed={120} />
    </p>
  );
}

// A shorter, coloured trail
<CometText text="Thinking it over" trail={[1, 0.7, 0.4, 0.15]} trailColor="#0358f7" loop />
```

#### Source

```tsx
"use client";

import { useEffect, useRef, useState, type CSSProperties } from "react";

export interface CometTextProps {
  /**
   * The text to stream. Pass the whole text to have it played in, or keep
   * appending to it (a model's reply arriving in chunks): the stream carries
   * on from where it is instead of starting over.
   */
  text: string;
  /** Characters per second. */
  speed?: number;
  /**
   * The trail, leading edge first: how much of its character's width each
   * bar fills, 0 to 1. Its length is the trail's length in characters.
   */
  trail?: readonly number[];
  /** Colour of the trail. Defaults to the text colour at 55% strength. */
  trailColor?: string;
  /** Start over after the text has finished. */
  loop?: boolean;
  /** Rest on the finished text before looping, in ms. */
  loopDelay?: number;
  /** Set to false to hold the text hidden until you flip it on. */
  autoPlay?: boolean;
  className?: string;
  style?: CSSProperties;
  /** Called each time the last character has landed. */
  onDone?: () => void;
}

/** A full block at the head, thinning to a sliver where the words land. */
const TRAIL = [1, 0.9, 0.85, 0.75, 0.6, 0.5, 0.35, 0.25, 0.1] as const;

/** Bars are as tall as a capital letter and sit on the baseline. */
const BAR: CSSProperties = { position: "absolute", left: 0, bottom: "0.2em", height: "0.72em" };
/**
 * Hides a character while it keeps its place. The fill is cleared, not
 * `color`, so `currentColor` still means the text colour for the bar over it.
 */
const UNSEEN: CSSProperties = { WebkitTextFillColor: "transparent" };

/**
 * Streams text behind a comet: a full block leads, and a trail of thinner
 * and thinner bars follows it, each resolving into the letter it was holding
 * the place of.
 *
 * The complete text is in the page from the first frame (the part not yet
 * streamed is transparent), so the layout never reflows, lines wrap where
 * they will end up, and assistive tech reads the text once, whole. Works in
 * any font: each bar takes the width of the character under it.
 */
export function CometText({
  text,
  speed = 70,
  trail = TRAIL,
  trailColor,
  loop = false,
  loopDelay = 1800,
  autoPlay = true,
  className,
  style,
  onDone,
}: CometTextProps) {
  // How many characters the head has passed. The trail covers the last `trail.length` of them.
  const [head, setHead] = useState(0);
  const characters = Array.from(text);
  const length = characters.length;
  const end = length + trail.length;

  // Everything the clock reads lives in refs, so new props never restart it
  const position = useRef(0);
  const live = useRef({ end, speed, loop, loopDelay, onDone });
  live.current = { end, speed, loop, loopDelay, onDone };

  // Appended text carries on; different text starts again from the beginning
  const previous = useRef(text);
  useEffect(() => {
    if (!text.startsWith(previous.current)) {
      position.current = 0;
      setHead(0);
    }
    previous.current = text;
  }, [text]);

  useEffect(() => {
    if (!autoPlay) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      position.current = Number.MAX_SAFE_INTEGER;
      setHead(Number.MAX_SAFE_INTEGER);
      return;
    }

    let frame = 0;
    let last = performance.now();
    let rested = 0;
    let announced = false;

    const tick = (now: number) => {
      const delta = now - last;
      last = now;
      const current = live.current;

      if (position.current < current.end) {
        announced = false;
        rested = 0;
        position.current = Math.min(current.end, position.current + (delta / 1000) * current.speed);
        // Re-render only when the head reaches a new character
        setHead(Math.floor(position.current));
      } else {
        if (!announced) {
          announced = true;
          current.onDone?.();
        }
        rested += delta;
        if (current.loop && rested >= current.loopDelay) {
          position.current = 0;
          setHead(0);
        }
      }
      frame = requestAnimationFrame(tick);
    };

    frame = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(frame);
  }, [autoPlay]);

  // Three stretches: letters that have landed, the trail, and the text still to come
  const landed = Math.max(0, Math.min(length, head - trail.length));
  const front = Math.max(0, Math.min(length, head));
  const state = !autoPlay ? "idle" : head >= end ? "done" : "streaming";

  return (
    <span className={className} style={style} data-comet-state={state}>
      {characters.slice(0, landed).join("")}
      {characters.slice(landed, front).map((character, offset) => {
        const index = landed + offset;
        // 0 is the leading edge
        const fill = trail[head - 1 - index] ?? 0;
        return (
          <span key={index} style={{ position: "relative", ...UNSEEN }}>
            {character}
            {/\S/.test(character) || fill > 0 ? (
              <span
                aria-hidden="true"
                style={{
                  ...BAR,
                  width: `${fill * 100}%`,
                  background: trailColor ?? "currentColor",
                  opacity: trailColor ? 1 : 0.55,
                }}
              />
            ) : null}
          </span>
        );
      })}
      <span style={UNSEEN}>{characters.slice(front).join("")}</span>
    </span>
  );
}

export default CometText;
```

## Features

- **Made for real streams**: Keep appending to the text and it carries on from where it is, instead of starting over
- **No reflow**: The whole text is laid out from the first frame, so lines wrap where they will end up and nothing below it moves
- **Any font**: Each bar takes the width of the character it stands in for, so it works in proportional type as well as mono
- **The trail is yours**: Pass any list of widths: a long soft tail, a short hard one, or a single block cursor
- **Readable by screen readers**: The text is real text from the start, not revealed character by character to assistive tech
- **Respects reduced motion**: The text simply appears

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| text | string | - | The text to stream; append to it for a live stream |
| speed | number | 70 | Characters per second |
| trail | number[] | 9 steps | Bar widths, leading edge first, each 0 to 1 |
| trailColor | string | text colour, 55% | Colour of the trail |
| loop | boolean | false | Start over after finishing |
| loopDelay | number | 1800 | Rest before looping, in ms |
| autoPlay | boolean | true | Set false to hold the text hidden |
| onDone | () => void | - | Called when the last character lands |
