# Integrate `Rime` from Motion Garden

You are helping me add the **Rime** 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:** Rime
- **Category:** Text Animations
- **Summary:** Hoarfrost taking a word. This is Molten's opposite number, the same idea of type as a coverage field run cold. Crystal tips seeded on the glyph edges creep across the letters, fork at a fixed lattice angle, and die where they run out of glyph or hit ice already there, so the cost tracks the growing edge rather than the area. The text underneath is never redrawn. It stays a real span at its real colour the whole time, which makes the thaw nothing more than fading the ice off type that was always there.
- **Reference:** https://motion-garden.netlify.app/components/rime
- **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
# Rime needs no npm packages
```

## 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 {
  --font-display: "Space Mono", ui-monospace, "SFMono-Regular", monospace;
}
```

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.

`font-display` expects Space Mono, and this CSS only names it. Load the font (with `next/font/google`, for example) or put my own display face first in the stack; until then it falls back to the system monospace.

## Files to create

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

```tsx
"use client";

import { memo, useEffect, useRef } from "react";
import { useAnimationLoop, type Metrics } from "@/hooks/use-animation-loop";

export type RimeMode = "loop" | "hover" | "hold";

interface RimeProps {
  text?: string;
  mode?: RimeMode;
  growth?: number;
  branching?: number;
  density?: number;
  seeds?: number;
  thaw?: number;
  hold?: number;
  sparkle?: number;
  frostColor?: string;
  baseColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const CELL = 2;

const STEP = 1.15;

const RATE = 4000;

const OVERHANG = 3;

const CROSSINGS = 2;

const JITTER = 0.18;

const STEER = 0.42;

const RELIEF = 3;

const CATCHUP_MAX = 90_000;

interface Tip {
  x: number;
  y: number;
  dir: number;
  out: number;
}

const Rime = memo(
  ({
    text = "RIME",
    mode = "loop",
    growth = 1,
    branching = 0.55,
    density = 0.7,
    seeds = 14,
    thaw = 1,
    hold = 1.5,
    sparkle = 0.35,
    frostColor = "#d6ecff",
    baseColor = "#e9e6f2",
    paused = false,
    reducedMotion = false,
    className,
  }: RimeProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const textRef = useRef<HTMLSpanElement>(null);
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const drawRef = useRef<((dt: number) => void | false) | null>(null);
    const measureRef = useRef<((m: Metrics) => void) | null>(null);
    const engaged = useRef(false);

    const loop = useAnimationLoop({
      target: containerRef,
      halted: paused || reducedMotion,
      dpr: "auto",
      onResize: (metrics) => measureRef.current?.(metrics),
      onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
    });

    const live = useRef({
      mode, growth, branching, density, seeds, thaw, hold, sparkle,
      frostColor, baseColor, reducedMotion,
    });
    live.current = {
      mode, growth, branching, density, seeds, thaw, hold, sparkle,
      frostColor, baseColor, reducedMotion,
    };

    useEffect(() => {
      const container = containerRef.current;
      const span = textRef.current;
      const canvas = canvasRef.current;
      if (!container || !span || !canvas) return;

      const ctx = canvas.getContext("2d");
      if (!ctx) return;

      const frost = document.createElement("canvas");
      const fctx = frost.getContext("2d");
      if (!fctx) return;

      const mask = document.createElement("canvas");

      let gw = 0;
      let gh = 0;
      let cover: Uint8Array = new Uint8Array(0);
      let taken: Uint8Array = new Uint8Array(0);
      let edges: Int32Array = new Int32Array(0);
      let edgeCount = 0;
      let tips: Tip[] = [];
      let glints: number[] = [];
      let steps = 0;
      let width = 0;
      let height = 0;
      let dprNow = 1;
      let elapsed = 0;
      let melt = 0;
      let held = 0;
      let seeded = false;
      let painted = "";

      let rngState = 0x2f6e2b1 >>> 0;
      const rnd = () => {
        rngState ^= rngState << 13;
        rngState ^= rngState >>> 17;
        rngState ^= rngState << 5;
        rngState >>>= 0;
        return rngState / 4294967296;
      };

      const rasterMask = () => {
        const outer = container.getBoundingClientRect();
        const box = span.getBoundingClientRect();
        if (box.width < 1 || outer.width < 1) return false;

        gw = Math.max(4, Math.ceil(outer.width / CELL));
        gh = Math.max(4, Math.ceil(outer.height / CELL));
        mask.width = gw;
        mask.height = gh;
        const mctx = mask.getContext("2d", { willReadFrequently: true });
        if (!mctx) return false;

        const style = getComputedStyle(span);
        const size = parseFloat(style.fontSize) || 16;
        const scale = 1 / CELL;

        mctx.clearRect(0, 0, gw, gh);
        mctx.font = `${style.fontStyle} ${style.fontWeight} ${size * scale}px ${style.fontFamily}`;
        if ("letterSpacing" in mctx) {
          const sp = style.letterSpacing === "normal" ? 0 : parseFloat(style.letterSpacing) || 0;
          mctx.letterSpacing = `${sp * scale}px`;
        }
        mctx.textAlign = "left";
        mctx.textBaseline = "alphabetic";
        mctx.fillStyle = "#fff";

        const m = mctx.measureText(text);
        const asc = m.fontBoundingBoxAscent || size * scale * 0.8;
        const desc = m.fontBoundingBoxDescent || size * scale * 0.2;
        const lineH = box.height * scale;
        const baseline = (box.top - outer.top) * scale + (lineH - (asc + desc)) / 2 + asc;

        mctx.fillText(text, (box.left - outer.left) * scale, baseline);

        const data = mctx.getImageData(0, 0, gw, gh).data;
        const n = gw * gh;
        if (cover.length !== n) {
          cover = new Uint8Array(n);
          taken = new Uint8Array(n);
          edges = new Int32Array(n);
        }
        for (let i = 0; i < n; i++) cover[i] = data[i * 4 + 3];

        edgeCount = 0;
        for (let y = 1; y < gh - 1; y++) {
          for (let x = 1; x < gw - 1; x++) {
            const i = y * gw + x;
            if (cover[i] < 110) continue;
            if (
              cover[i - 1] < 110 ||
              cover[i + 1] < 110 ||
              cover[i - gw] < 110 ||
              cover[i + gw] < 110
            ) {
              edges[edgeCount++] = i;
            }
          }
        }
        return edgeCount > 0;
      };

      const reset = () => {
        taken.fill(0);
        tips = [];
        glints = [];
        steps = 0;
        rngState = 0x2f6e2b1 >>> 0;
        fctx.setTransform(1, 0, 0, 1, 0, 0);
        fctx.clearRect(0, 0, frost.width, frost.height);
        fctx.setTransform(dprNow, 0, 0, dprNow, 0, 0);

        const want = Math.max(1, Math.round(live.current.seeds));
        for (let s = 0; s < want && edgeCount > 0; s++) {
          const i = edges[Math.floor(rnd() * edgeCount)];
          const x = i % gw;
          const y = Math.floor(i / gw);

          const gx =
            (cover[i + 1] ?? 0) - (cover[i - 1] ?? 0);
          const gy =
            (cover[i + gw] ?? 0) - (cover[i - gw] ?? 0);
          const dir =
            gx === 0 && gy === 0
              ? rnd() * Math.PI * 2
              : Math.atan2(gy, gx) + (rnd() - 0.5) * 1.1;

          tips.push({ x, y, dir, out: 0 });
        }
        seeded = tips.length > 0;
      };

      const advance = (budget: number) => {
        const l = live.current;
        if (!tips.length) return;

        const cap = Math.max(24, Math.round(l.density * 400));
        const FORK = Math.PI / 3;

        fctx.strokeStyle = l.frostColor;
        fctx.shadowColor = "rgba(4, 12, 24, 0.95)";
        fctx.shadowBlur = RELIEF;
        fctx.lineWidth = 1;
        fctx.lineCap = "round";
        fctx.beginPath();

        let drawn = 0;
        for (let n = 0; n < budget && tips.length; n++) {
          const ti = steps % tips.length;
          const tip = tips[ti];

          tip.dir += (rnd() - 0.5) * JITTER;
          const nx = tip.x + Math.cos(tip.dir) * STEP;
          const ny = tip.y + Math.sin(tip.dir) * STEP;
          steps++;

          const gx = Math.round(nx);
          const gy = Math.round(ny);
          if (gx < 0 || gy < 0 || gx >= gw || gy >= gh) {
            tips.splice(ti, 1);
            continue;
          }

          const idx = gy * gw + gx;

          if (cover[idx] >= 90) {
            tip.out = 0;
          } else {
            if (++tip.out > OVERHANG) {
              tips.splice(ti, 1);
              continue;
            }
            const gx = (cover[idx + 1] ?? 0) - (cover[idx - 1] ?? 0);
            const gy = (cover[idx + gw] ?? 0) - (cover[idx - gw] ?? 0);
            if (gx !== 0 || gy !== 0) {
              let turn = Math.atan2(gy, gx) - tip.dir;
              while (turn > Math.PI) turn -= Math.PI * 2;
              while (turn < -Math.PI) turn += Math.PI * 2;
              tip.dir += turn * STEER;
            }
          }

          if (taken[idx] > CROSSINGS) {
            tips.splice(ti, 1);
            continue;
          }
          taken[idx]++;

          fctx.moveTo(tip.x * CELL, tip.y * CELL);
          fctx.lineTo(nx * CELL, ny * CELL);
          drawn++;

          tip.x = nx;
          tip.y = ny;

          if (glints.length < 220 && rnd() < 0.02) {
            glints.push(nx * CELL, ny * CELL);
          }

          if (tips.length < cap && rnd() < l.branching * 0.07) {
            tips.push({
              x: nx,
              y: ny,
              dir: tip.dir + (rnd() < 0.5 ? FORK : -FORK),
              out: tip.out,
            });
          }
        }

        if (drawn) fctx.stroke();
      };

      measureRef.current = ({ width: w, height: h, dpr, bufferWidth, bufferHeight }) => {
        if (w < 1 || h < 1) return;
        width = w;
        height = h;
        dprNow = dpr;

        canvas.width = bufferWidth;
        canvas.height = bufferHeight;
        canvas.style.width = `${w}px`;
        canvas.style.height = `${h}px`;
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

        frost.width = bufferWidth;
        frost.height = bufferHeight;

        if (!rasterMask()) return;

        const had = steps;
        reset();
        if (had > 0) advance(Math.min(had, CATCHUP_MAX));
      };

      drawRef.current = (dt) => {
        const l = live.current;
        if (width < 1 || !cover.length) return;
        if (!seeded && edgeCount > 0) reset();

        if (painted !== l.frostColor) {
          painted = l.frostColor;
          const had = steps;
          reset();
          if (had > 0) advance(Math.min(had, CATCHUP_MAX));
        }

        elapsed = (elapsed + dt) % 3600;

        const growing = () => advance(Math.round(l.growth * RATE * dt));
        const rate = Math.max(l.thaw, 0.05);
        const complete = tips.length === 0 && steps > 0;

        if (l.reducedMotion) {
          if (!complete) advance(CATCHUP_MAX);
          melt = 0;
        } else if (l.mode === "loop") {
          if (!complete) {
            growing();
          } else if (held < l.hold) {
            held += dt;
          } else {
            melt += rate * dt;
            if (melt >= 1) {
              melt = 0;
              held = 0;
              reset();
            }
          }
        } else if (l.mode === "hover") {
          if (engaged.current) {
            melt = Math.min(1, melt + rate * dt);
          } else {
            if (melt >= 1) {
              melt = 0;
              reset();
            } else {
              melt = Math.max(0, melt - rate * dt);
            }
            if (!complete) growing();
          }
        } else {
          if (engaged.current) {
            melt = Math.max(0, melt - rate * 2 * dt);
            if (!complete) growing();
          } else {
            melt = Math.min(1, melt + rate * dt);
            if (melt >= 1 && steps > 0) reset();
          }
        }

        ctx.clearRect(0, 0, width, height);

        const opacity = 1 - melt;
        if (opacity <= 0.001) return;

        ctx.save();
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.globalAlpha = opacity;
        ctx.drawImage(frost, 0, 0);
        ctx.restore();

        if (l.sparkle > 0.01 && glints.length) {
          ctx.save();
          ctx.globalCompositeOperation = "lighter";
          ctx.fillStyle = "#ffffff";
          for (let i = 0; i < glints.length; i += 2) {
            const phase = i * 1.37;
            const tw = Math.sin(elapsed * 2.6 + phase) * 0.5 + 0.5;
            const a = Math.pow(tw, 6) * l.sparkle * opacity;
            if (a < 0.02) continue;
            ctx.globalAlpha = a;
            ctx.fillRect(glints[i] - 0.75, glints[i + 1] - 0.75, 1.5, 1.5);
          }
          ctx.restore();
        }
      };

      let alive = true;
      const style = getComputedStyle(span);
      const size = parseFloat(style.fontSize) || 16;
      Promise.resolve()
        .then(() => document.fonts.load(`${style.fontWeight} ${size}px ${style.fontFamily}`))
        .then(() => document.fonts.ready)
        .then(() => {
          if (!alive) return;
          loop.resize();
        })
        .catch(() => {});

      loop.resize();
      loop.start();

      return () => {
        alive = false;
        drawRef.current = null;
        measureRef.current = null;
      };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [text]);

    const engage = () => {
      if (reducedMotion) return;
      engaged.current = true;
      loop.start();
    };
    const release = () => {
      engaged.current = false;
      loop.start();
    };

    const hover = mode === "hover";
    const held = mode === "hold";

    return (
      <div
        ref={containerRef}
        className={`relative inline-block ${className ?? "font-display text-[clamp(2.5rem,11vw,6.5rem)] leading-none font-extrabold tracking-tight"}`}
        onPointerEnter={hover ? engage : undefined}
        onPointerLeave={hover || held ? release : undefined}
        onPointerDown={held ? engage : undefined}
        onPointerUp={held ? release : undefined}
        onPointerCancel={release}
      >
        <span
          ref={textRef}
          className="relative block whitespace-pre"
          style={{ color: baseColor }}
        >
          {text}
        </span>
        <canvas
          ref={canvasRef}
          className="pointer-events-none absolute inset-0 block"
        />
      </div>
    );
  },
);

Rime.displayName = "Rime";

export default Rime;
```

### 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],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `mode` | `"loop" | "hover" | "hold"` | `"loop"` | What drives the freeze. Loop grows the crystal, holds it, thaws it and starts a new one. Hover rests frozen and clears under the pointer, regrowing once it has fully melted. Hold is the mirror of a melt: ice advances only while the pointer is down and retreats the moment it lifts. |
| `growth` | `number` | `1` | How fast the crystal front advances. This is a budget of steps per second shared across every live tip, so a heavily branched frost spreads each tip more slowly — which is exactly how a real front behaves as it runs out of room. Range 0.2–3. |
| `branching` | `number` | `0.55` | How readily a tip splits in two, and the difference between needles and ferns. Forks are quantised to a sixty-degree lattice angle on purpose: free angles read as mould rather than as ice. Range 0–1. |
| `density` | `number` | `0.7` | Ceiling on how many tips may be alive at once, which decides how much ice the letters hold before the front runs out of room and the freeze completes. Low leaves the type legible under a tracery; high buries it. Range 0.1–1. |
| `seeds` | `number` | `14` | How many places the frost starts from. Every seed lands on a glyph edge rather than in the middle of a stem, because that is where condensation actually nucleates — and it is why the ice always looks like it arrived from outside the letter. Range 3–40. |
| `thaw` | `number` | `1` | How fast the ice clears. The crystal is not redrawn to melt it — the overlay simply fades — so this is free at any speed and the word beneath is legible throughout. Range 0.2–3. |
| `hold` | `number` | `1.5` | Seconds spent at full freeze before the thaw begins. The pause is what lets the finished crystal be looked at; without it the loop reads as a shimmer rather than as a process with an end. Range 0–6 s. Ignored unless `mode` is `loop`. |
| `sparkle` | `number` | `0.35` | Glints on the facets, sampled from points the front actually passed through rather than scattered over the box. They fade with the thaw, so the last thing to go is the light. Range 0–1. |
| `frostColor` | `string (hex)` | `"#d6ecff"` | The ice. The crystal is stored white and tinted on the way out, so this repaints the whole thing without touching a single stored segment. |
| `baseColor` | `string (hex)` | `"#e9e6f2"` | The type underneath, which never moves and is never redrawn. |

## Usage

```tsx
import Rime from "@/components/registry/rime/rime";

<Rime
  mode="loop"
  growth={1}
  branching={0.55}
  density={0.7}
  seeds={14}
  thaw={1}
  hold={1.5}
  sparkle={0.35}
  frostColor="#d6ecff"
  baseColor="#e9e6f2"
/>
```

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.
- 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.
