# Integrate `Teletype` from Motion Garden

You are helping me add the **Teletype** 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:** Teletype
- **Category:** Text Animations
- **Summary:** A line of type arriving one character at a time, at a rate that varies and with a beat at every mark.
- **Reference:** https://motion-garden.netlify.app/components/teletype
- **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 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-ink: var(--sg-ink);
}

:root {
  --sg-ink: #16191d;
}

.dark {
  --sg-ink: #e2e6e9;
}
```

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/teletype/teletype.tsx`

```tsx
"use client";

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

export type TeletypeCaret = "block" | "bar" | "underscore" | "none";

export interface TeletypeProps {
  lines?: string[];
  charsPerSecond?: number;
  deleteRate?: number;
  hold?: number;
  gap?: number;
  jitter?: number;
  punctuationPause?: number;
  caret?: TeletypeCaret;
  caretBlink?: number;
  loop?: boolean;
  reserveSpace?: boolean;
  accentColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

function makeRandom(seed: number) {
  let state = seed >>> 0 || 1;
  return () => {
    state ^= state << 13;
    state >>>= 0;
    state ^= state >>> 17;
    state ^= state << 5;
    state >>>= 0;
    return state / 0xffffffff;
  };
}

const BREATH = new Set([",", ".", ";", ":", "!", "?", "—", "…"]);

type Phase = "type" | "punct" | "hold" | "delete" | "gap";

export default function Teletype({
  lines = [],
  charsPerSecond = 22,
  deleteRate = 2.4,
  hold = 1500,
  gap = 420,
  jitter = 0.45,
  punctuationPause = 220,
  caret = "block",
  caretBlink = 1.05,
  loop = true,
  reserveSpace = true,
  accentColor = "#a855f7",
  paused = false,
  reducedMotion = false,
  className,
}: TeletypeProps) {
  const rootRef = useRef<HTMLDivElement>(null);

  const [index, setIndex] = useState(0);
  const [chars, setChars] = useState(0);
  const [steady, setSteady] = useState(false);
  const [done, setDone] = useState(false);

  const halted = paused || reducedMotion;
  const text = lines[index] ?? "";

  const live = useRef({
    lines,
    charsPerSecond,
    deleteRate,
    hold,
    gap,
    jitter,
    punctuationPause,
    loop,
    reducedMotion,
  });
  live.current = {
    lines,
    charsPerSecond,
    deleteRate,
    hold,
    gap,
    jitter,
    punctuationPause,
    loop,
    reducedMotion,
  };

  const fresh = () => ({
    index: 0,
    chars: 0,
    wait: 0,
    rate: 1,
    phase: "type" as Phase,
    breathAt: -1,
    random: makeRandom(0x7e1e),
  });

  const run = useRef(fresh());

  useEffect(() => {
    if (!reducedMotion) return;
    setIndex(0);
    setChars(lines[0]?.length ?? 0);
    setSteady(true);
    setDone(true);
  }, [reducedMotion, lines]);

  useEffect(() => {
    if (reducedMotion) return;
    run.current = fresh();
    setIndex(0);
    setChars(0);
    setSteady(false);
    setDone(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [lines, reducedMotion]);

  useEffect(() => {
    if (loop) setDone(false);
  }, [loop]);

  const drawRef = useRef<((dt: number) => void | false) | null>(null);
  drawRef.current = (dt: number) => {
    const p = live.current;
    if (p.lines.length === 0) return false;
    if (p.reducedMotion) return false;

    const s = run.current;
    const line = p.lines[s.index] ?? "";

    switch (s.phase) {
      case "type": {
        s.chars = Math.min(
          line.length,
          s.chars + p.charsPerSecond * s.rate * dt,
        );
        const landed = Math.floor(s.chars);
        setChars(landed);

        if (s.chars >= line.length) {
          s.wait = p.hold / 1000;
          s.phase = "hold";
          setSteady(true);
          return;
        }
        const last = line[landed - 1];
        if (landed > s.breathAt && last && BREATH.has(last)) {
          s.breathAt = landed;
          s.wait = p.punctuationPause / 1000;
          s.phase = "punct";
        }
        return;
      }

      case "punct": {
        s.wait -= dt;
        if (s.wait <= 0) s.phase = "type";
        return;
      }

      case "hold": {
        s.wait -= dt;
        if (s.wait > 0) return;
        if (!p.loop && s.index >= p.lines.length - 1) {
          setDone(true);
          return false;
        }
        if (p.deleteRate > 0) {
          s.phase = "delete";
          setSteady(false);
          return;
        }
        s.index = (s.index + 1) % p.lines.length;
        s.chars = 0;
        s.breathAt = -1;
        s.rate = Math.max(0.2, 1 + (s.random() * 2 - 1) * p.jitter);
        s.wait = p.gap / 1000;
        s.phase = "gap";
        setIndex(s.index);
        setChars(0);
        return;
      }

      case "delete": {
        s.chars = Math.max(
          0,
          s.chars - p.charsPerSecond * p.deleteRate * s.rate * dt,
        );
        setChars(Math.floor(s.chars));
        if (s.chars > 0) return;
        s.index = (s.index + 1) % p.lines.length;
        s.breathAt = -1;
        s.rate = Math.max(0.2, 1 + (s.random() * 2 - 1) * p.jitter);
        s.wait = p.gap / 1000;
        s.phase = "gap";
        setIndex(s.index);
        setSteady(true);
        return;
      }

      case "gap": {
        s.wait -= dt;
        if (s.wait <= 0) {
          s.phase = "type";
          setSteady(false);
        }
        return;
      }
    }
  };

  const runtime = useAnimationLoop({
    target: rootRef,
    halted,
    onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
  });

  useEffect(() => {
    if (!halted && !done) runtime.start();
  }, [halted, done, lines, loop, runtime]);

  const visible = text.slice(0, chars);
  const blinking = !halted && steady && caretBlink > 0;

  const caretBox =
    caret === "bar"
      ? "w-[2px] h-[1.1em] translate-y-[0.18em]"
      : caret === "underscore"
        ? "w-[0.62em] h-[2px] translate-y-[0.05em]"
        : "w-[0.5em] h-[1em] translate-y-[0.14em]";

  const ghosts = useMemo(() => lines.slice(0, 24), [lines]);

  return (
    <div
      ref={rootRef}
      className={cn(
        "grid w-full font-mono text-ink *:col-1 *:row-1",
        className,
      )}
    >
      {reserveSpace
        ? ghosts.map((line, i) => (
            <span
              key={i}
              aria-hidden
              className="pointer-events-none invisible whitespace-pre-wrap select-none"
            >
              {line}
            </span>
          ))
        : null}

      <p aria-hidden className="whitespace-pre-wrap">
        {visible}
        {caret === "none" ? null : (
          <motion.span
            className={cn("ml-px inline-block align-baseline", caretBox)}
            style={{ backgroundColor: accentColor }}
            animate={blinking ? { opacity: [1, 1, 0, 0] } : { opacity: 1 }}
            transition={
              blinking
                ? { duration: caretBlink, repeat: Infinity, ease: "linear" }
                : { duration: 0 }
            }
          />
        )}
      </p>

      <span className="sr-only">{text}</span>
    </div>
  );
}
```

### 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 |
| --- | --- | --- | --- |
| `charsPerSecond` | `number` | `22` | Typing rate before jitter. Above roughly 40 the reader stops perceiving individual keystrokes and starts seeing a wipe. Range 4–90. |
| `deleteRate` | `number` | `2.4` | Erase rate as a multiple of the typing rate — deleting is never as deliberate as writing. At 0 the line is not erased at all: it is cut, and the next one starts clean. Range 0–6. |
| `hold` | `number` | `1500` | Dwell on a finished line before it is taken away. This is the only window the reader has to actually read it. Range 0–4000 ms. |
| `gap` | `number` | `420` | Empty beat between one line clearing and the next starting. Range 0–2000 ms. |
| `jitter` | `number` | `0.45` | Spread on the per-line rate. At 0 the machine is a metronome, which reads as a progress bar rendered in letters rather than as typing. Range 0–1. |
| `punctuationPause` | `number` | `220` | Extra beat after a comma, period, dash or colon. The pause a reader hears at a mark is the silence that follows it, so it lands after the glyph, never before. Range 0–800 ms. |
| `caret` | `"block" | "bar" | "underscore" | "none"` | `"block"` | Shape of the cursor trailing the text. |
| `caretBlink` | `number` | `1.05` | Seconds per blink cycle. The caret holds steady while characters are arriving and only blinks once the line is at rest — a terminal does the same, and the contrast is what makes the typing read as live. Range 0.2–3 s. Ignored while `caret` is `none`. |
| `loop` | `boolean` | `true` | Wrap to the first line when the list runs out. |
| `reserveSpace` | `boolean` | `true` | Hold the box at the size of the longest line. Turn it off to watch everything below the type walk up and down the page — which is the reason it is on. |
| `accentColor` | `string (hex)` | `"#a855f7"` | The caret. |

## Usage

```tsx
import Teletype from "@/components/registry/teletype/teletype";

<Teletype
  charsPerSecond={22}
  deleteRate={2.4}
  hold={1500}
  gap={420}
  jitter={0.45}
  punctuationPause={220}
  caret="block"
  caretBlink={1.05}
  loop={true}
  reserveSpace={true}
  accentColor="#a855f7"
/>
```

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.
