# Integrate `Stream` from Motion Garden

You are helping me add the **Stream** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Stream
- **Category:** Power-User Systems
- **Summary:** An AI response surface that streams the way live chat UIs stream. A shimmer while the model thinks, tokens arriving on an irregular clock and blurring into place, a generation caret riding the last word, and stop and regenerate controls that actually interrupt. The cadence rides the animation clock rather than timer chains, so pausing the bench freezes generation mid-word. Only the trailing window of tokens are live animated elements, and everything older folds into one static text node, so a long answer never accumulates a thousand springs. An invisible ghost of the full answer holds the final height, so neither the thinking-to-streaming swap nor the stream itself ever moves layout.
- **Reference:** https://motion-garden.netlify.app/components/stream
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add motion lucide-react clsx tailwind-merge
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme inline {
  --color-panel: var(--sg-panel);
  --color-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-panel: #101215;
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-dim: #bcc2c8;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

## Files to create

3 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/stream/stream.tsx`

```tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { motion } from "motion/react";
import { RotateCcw, Square } from "lucide-react";
import { cn } from "@/lib/utils";
import { useAnimationLoop } from "@/hooks/use-animation-loop";

export type StreamChunking = "word" | "character";
export type StreamCaret = "bar" | "block" | "none";

export interface StreamProps {
  text?: string;
  tokensPerSecond?: number;
  jitter?: number;
  chunking?: StreamChunking;
  blurAmount?: number;
  thinkingMs?: number;
  caret?: StreamCaret;
  caretColor?: string;
  autoReplay?: boolean;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

type Phase = "thinking" | "streaming" | "done" | "stopped";

const WINDOW = 24;

const DEFAULT_TEXT =
  "The registry is the single source of truth here: every tunable prop is declared once as a schema entry, and that one declaration drives both the controls panel you are reading and the props table below it. Nothing is documented twice, so nothing can drift. The code tab reads the shipped source straight from disk, strips the comments on the way out, and serves exactly what the copy button puts on your clipboard.";

const splitTokens = (text: string, chunking: StreamChunking): string[] => {
  if (chunking === "character") return Array.from(text);
  return text.match(/\S+\s*/g) ?? [];
};

const Stream = ({
  text = DEFAULT_TEXT,
  tokensPerSecond = 18,
  jitter = 0.35,
  chunking = "word",
  blurAmount = 6,
  thinkingMs = 1200,
  caret = "bar",
  caretColor = "#a78bfa",
  autoReplay = true,
  paused = false,
  reducedMotion = false,
  className,
}: StreamProps) => {
  const containerRef = useRef<HTMLDivElement | null>(null);

  const live = useRef({
    tokensPerSecond,
    jitter,
    blurAmount,
    thinkingMs,
    autoReplay,
    paused,
    reducedMotion,
  });
  live.current = {
    tokensPerSecond,
    jitter,
    blurAmount,
    thinkingMs,
    autoReplay,
    paused,
    reducedMotion,
  };

  const tokens = splitTokens(text, chunking);

  const [phase, setPhase] = useState<Phase>("thinking");
  const [count, setCount] = useState(0);

  const clock = useRef({
    phase: "thinking" as Phase,
    count: 0,
    tokenTotal: tokens.length,
    thinkingLeft: thinkingMs / 1000,
    untilNext: 0,
    replayLeft: 0,
  });
  clock.current.tokenTotal = tokens.length;

  const loop = useAnimationLoop({
    target: containerRef,
    halted: paused,
    onFrame: ({ dt }) => {
      const c = clock.current;
      const L = live.current;

      if (c.phase === "thinking") {
        c.thinkingLeft -= dt;
        if (c.thinkingLeft <= 0) {
          c.phase = "streaming";
          c.untilNext = 0;
          setPhase("streaming");
        }
        return;
      }

      if (c.phase === "streaming") {
        c.untilNext -= dt;
        let emitted = 0;
        while (c.untilNext <= 0 && c.count < c.tokenTotal && emitted < 6) {
          c.count++;
          emitted++;
          const base = 1 / Math.max(L.tokensPerSecond, 0.5);
          const wobble = 1 + L.jitter * (Math.random() * 2 - 1);
          const stall =
            Math.random() < L.jitter * 0.05 ? base * (4 + Math.random() * 8) : 0;
          c.untilNext += base * Math.max(wobble, 0.25) + stall;
        }
        if (emitted > 0) setCount(c.count);
        if (c.count >= c.tokenTotal) {
          c.phase = "done";
          c.replayLeft = 2.6;
          setPhase("done");
        }
        return;
      }

      if (c.phase === "done" && L.autoReplay) {
        c.replayLeft -= dt;
        if (c.replayLeft <= 0) {
          c.phase = "thinking";
          c.count = 0;
          c.thinkingLeft = L.thinkingMs / 1000;
          setPhase("thinking");
          setCount(0);
        }
        return;
      }

      return false;
    },
  });

  useEffect(() => {
    loop.start();
  }, [paused, autoReplay, loop]);

  useEffect(() => {
    const c = clock.current;
    c.phase = "thinking";
    c.count = 0;
    c.thinkingLeft = live.current.thinkingMs / 1000;
    setPhase("thinking");
    setCount(0);
    loop.start();
  }, [text, chunking, loop]);

  const stop = () => {
    const c = clock.current;
    if (c.phase !== "streaming" && c.phase !== "thinking") return;
    c.phase = "stopped";
    setPhase("stopped");
  };

  const regenerate = () => {
    const c = clock.current;
    c.phase = "thinking";
    c.count = 0;
    c.thinkingLeft = live.current.thinkingMs / 1000;
    setPhase("thinking");
    setCount(0);
    loop.start();
  };

  const generating = phase === "thinking" || phase === "streaming";
  const windowStart = Math.max(0, count - WINDOW);
  const settledText = tokens.slice(0, windowStart).join("");
  const liveTokens = tokens.slice(windowStart, count);

  const caretEl =
    caret !== "none" && phase === "streaming" ? (
      <motion.span
        aria-hidden
        className="ml-px inline-block align-baseline"
        style={{
          width: caret === "block" ? "0.55em" : "2px",
          height: "1.1em",
          marginBottom: "-0.2em",
          background: caretColor,
        }}
        animate={reducedMotion ? { opacity: 1 } : { opacity: [1, 1, 0, 0] }}
        transition={
          reducedMotion
            ? undefined
            : { duration: 0.9, repeat: Infinity, ease: "linear" }
        }
      />
    ) : null;

  return (
    <div
      ref={containerRef}
      className={cn(
        "flex h-full w-full flex-col gap-4 rounded-lg border border-hairline bg-panel p-5",
        className,
      )}
    >
      <div className="relative min-h-0 flex-1 overflow-hidden">
        <div
          aria-hidden
          className="invisible text-sm leading-relaxed"
        >
          {text}
        </div>

        {phase === "thinking" ? (
          <div className="absolute inset-0 flex flex-col gap-2.5 pt-1">
            {[0.92, 0.98, 0.62].map((w, i) => (
              <div
                key={i}
                className="relative h-3.5 overflow-hidden rounded bg-raised"
                style={{ width: `${w * 100}%` }}
              >
                {!reducedMotion && (
                  <motion.div
                    className="absolute inset-y-0 w-1/2"
                    style={{
                      background:
                        "linear-gradient(105deg, transparent, color-mix(in oklab, var(--sg-ink) 12%, transparent), transparent)",
                    }}
                    initial={{ x: "-110%" }}
                    animate={{ x: "310%" }}
                    transition={{
                      duration: 1.3,
                      repeat: Infinity,
                      ease: "linear",
                      delay: i * 0.18,
                    }}
                  />
                )}
              </div>
            ))}
          </div>
        ) : (
          <p className="absolute inset-0 overflow-hidden text-sm leading-relaxed text-ink">
            <span>{settledText}</span>
            {liveTokens.map((token, i) => (
              <motion.span
                key={windowStart + i}
                className="inline"
                initial={
                  reducedMotion
                    ? false
                    : { opacity: 0, y: 2, filter: `blur(${blurAmount}px)` }
                }
                animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
                transition={{ duration: 0.3, ease: "easeOut" }}
              >
                {token}
              </motion.span>
            ))}
            {caretEl}
          </p>
        )}
      </div>

      <div className="flex items-center gap-2">
        {generating ? (
          <button
            type="button"
            onClick={stop}
            className="inline-flex items-center gap-1.5 rounded-md border border-hairline bg-raised px-2.5 py-1.5 font-mono text-xs text-ink-dim transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-accent"
          >
            <Square className="size-3" fill="currentColor" />
            Stop
          </button>
        ) : (
          <button
            type="button"
            onClick={regenerate}
            className="inline-flex items-center gap-1.5 rounded-md border border-hairline bg-raised px-2.5 py-1.5 font-mono text-xs text-ink-dim transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-accent"
          >
            <RotateCcw className="size-3" />
            Regenerate
          </button>
        )}
        <span className="font-mono text-[10px] uppercase tracking-widest text-ink-mute">
          {phase === "thinking" && "thinking…"}
          {phase === "streaming" && `${count}/${tokens.length} tokens`}
          {phase === "done" && "complete"}
          {phase === "stopped" && "stopped"}
        </span>
      </div>
    </div>
  );
};

export default Stream;
```

### 2. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```

### 3. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `tokensPerSecond` | `number` | `18` | Average emission rate. Range 2–60. |
| `jitter` | `number` | `0.35` | Cadence irregularity — bursts and occasional stalls that make it read as a live model rather than a metronome. Range 0–1. |
| `chunking` | `"word" | "character"` | `"word"` | Emission granularity. Words read like a model; characters read like a terminal. |
| `blurAmount` | `number` | `6` | Blur each token arrives from. Range 0–16 px. |
| `thinkingMs` | `number` | `1200` | Shimmer skeleton phase before the first token. Range 0–4000 ms. |
| `caret` | `"bar" | "block" | "none"` | `"bar"` | Generation caret riding the last token. |
| `caretColor` | `string (hex)` | `"#a78bfa"` | Caret tint. Ignored while `caret` is `none`. |
| `autoReplay` | `boolean` | `true` | Regenerate automatically after settling, so the demo loops hands-free. |

## Usage

```tsx
import Stream from "@/components/registry/stream/stream";

<Stream
  tokensPerSecond={18}
  jitter={0.35}
  chunking="word"
  blurAmount={6}
  thinkingMs={1200}
  caret="bar"
  caretColor="#a78bfa"
  autoReplay={true}
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
