# Integrate `Inscribe` from Motion Garden

You are helping me add the **Inscribe** 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:** Inscribe
- **Category:** Text Animations
- **Summary:** Text engraved stroke by stroke. Every character is a real SVG tspan with native kerning and selectable words, wearing the uniform-dash trick, because glyph outlines expose no pathLength and measuring their true perimeter has no API: the chisel simply travels each letter at its own apparent speed. When a stroke closes, its fill carves in after a beat, and the engraved finish darkens the fill and adds an inset relief so the word reads as cut into the panel rather than printed on it. The whole timeline runs on the animation-loop clock, so the bench pause freezes the chisel mid-stroke, and with no JavaScript at all the text simply sits there finished.
- **Reference:** https://motion-garden.netlify.app/components/inscribe
- **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
# Inscribe 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/inscribe/inscribe.tsx`

```tsx
"use client";

import { useLayoutEffect, useRef } from "react";
import { useAnimationLoop } from "@/hooks/use-animation-loop";

export type InscribeFinish = "engraved" | "inlay" | "stroke-only";

export interface InscribeProps {
  text?: string;
  duration?: number;
  stagger?: number;
  fillDelay?: number;
  strokeWidth?: number;
  finish?: InscribeFinish;
  replay?: boolean;
  replayDelay?: number;
  strokeColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const DASH = 520;

const FILL_S = 0.3;

const darken = (hex: string, factor: number): string => {
  const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  if (!m) return hex;
  const ch = (s: string) =>
    Math.round(parseInt(s, 16) * factor)
      .toString(16)
      .padStart(2, "0");
  return `#${ch(m[1])}${ch(m[2])}${ch(m[3])}`;
};

const Inscribe = ({
  text = "Inscribe",
  duration = 900,
  stagger = 90,
  fillDelay = 250,
  strokeWidth = 1.5,
  finish = "engraved",
  replay = true,
  replayDelay = 2500,
  strokeColor = "#c4b5fd",
  paused = false,
  reducedMotion = false,
  className = "",
}: InscribeProps) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const glyphRefs = useRef<Array<SVGTSpanElement | null>>([]);

  const chars = Array.from(text);

  const live = useRef({
    duration,
    stagger,
    fillDelay,
    replay,
    replayDelay,
    paused,
    reducedMotion,
    count: chars.length,
  });
  live.current = {
    duration,
    stagger,
    fillDelay,
    replay,
    replayDelay,
    paused,
    reducedMotion,
    count: chars.length,
  };

  const clock = useRef({ t: 0 });

  const apply = (el: SVGTSpanElement, offset: number, fill: number) => {
    const o = offset.toFixed(2);
    const f = fill.toFixed(3);
    if (el.style.strokeDashoffset !== o) el.style.strokeDashoffset = o;
    if (el.style.fillOpacity !== f) el.style.fillOpacity = f;
  };

  const render = (t: number) => {
    const cfg = live.current;
    const dur = Math.max(cfg.duration, 50) / 1000;
    const stag = cfg.stagger / 1000;
    const fdel = cfg.fillDelay / 1000;
    for (let i = 0; i < cfg.count; i++) {
      const el = glyphRefs.current[i];
      if (!el) continue;
      const start = i * stag;
      const p = Math.min(Math.max((t - start) / dur, 0), 1);
      const fp = Math.min(Math.max((t - start - dur - fdel) / FILL_S, 0), 1);
      apply(el, DASH * (1 - p), fp);
    }
  };

  const totalFor = () => {
    const cfg = live.current;
    return (
      ((cfg.count - 1) * cfg.stagger + Math.max(cfg.duration, 50)) / 1000 +
      cfg.fillDelay / 1000 +
      FILL_S
    );
  };

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

      if (cfg.reducedMotion) {
        render(Number.POSITIVE_INFINITY);
        return false;
      }

      c.t += dt;
      const total = totalFor();

      if (c.t >= total) {
        render(total);
        if (!cfg.replay) return false;
        if (c.t >= total + cfg.replayDelay / 1000) c.t = 0;
        return;
      }
      render(c.t);
    },
  });

  useLayoutEffect(() => {
    clock.current.t = 0;
    if (reducedMotion) render(Number.POSITIVE_INFINITY);
    else render(0);
    loop.start();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [text, finish, reducedMotion, loop]);

  useLayoutEffect(() => {
    loop.start();
  }, [paused, replay, loop]);

  const vbWidth = Math.max(240, chars.length * 52 + 64);
  const fillColor =
    finish === "stroke-only"
      ? "none"
      : finish === "engraved"
        ? darken(strokeColor, 0.42)
        : strokeColor;

  return (
    <div ref={containerRef} className={`w-full ${className}`.trim()}>
      <svg viewBox={`0 0 ${vbWidth} 150`} className="block h-auto w-full">
        <text
          x={vbWidth / 2}
          y={78}
          textAnchor="middle"
          dominantBaseline="central"
          className="font-display font-bold"
          fontSize={84}
          letterSpacing="0.02em"
          fill={fillColor}
          stroke={strokeColor}
          strokeWidth={strokeWidth}
          strokeLinejoin="round"
          strokeLinecap="round"
          strokeDasharray={DASH}
          style={
            finish === "engraved"
              ? {
                  filter:
                    "drop-shadow(0 -1px 0 rgba(0,0,0,0.55)) drop-shadow(0 1px 0 rgba(255,255,255,0.14))",
                }
              : undefined
          }
        >
          {chars.map((ch, i) => (
            <tspan
              key={`${i}-${ch}`}
              ref={(el) => {
                glyphRefs.current[i] = el;
              }}
            >
              {ch === " " ? "\u00A0" : ch}
            </tspan>
          ))}
        </text>
      </svg>
    </div>
  );
};

export default Inscribe;
```

### 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 |
| --- | --- | --- | --- |
| `duration` | `number` | `900` | Time for one character's stroke to draw. Range 300–3000 ms. |
| `stagger` | `number` | `90` | Delay between one chisel start and the next. Range 0–400 ms. |
| `fillDelay` | `number` | `250` | Beat between a finished stroke and its fill arriving. Range 0–1500 ms. |
| `strokeWidth` | `number` | `1.5` | Chisel line weight in viewBox units. Range 0.5–4. |
| `finish` | `"engraved" | "inlay" | "stroke-only"` | `"engraved"` | Carved-in fill, bright accent inlay, or the bare trace. |
| `replay` | `boolean` | `true` | Wipe and re-engrave on a timer. |
| `replayDelay` | `number` | `2500` | Dwell on the finished engraving before the wipe. Range 500–8000 ms. Ignored while `replay` is `false`. |
| `strokeColor` | `string (hex)` | `"#c4b5fd"` | The chisel trace; the engraved fill derives from it at lower luminance, the inlay at full. |

## Usage

```tsx
import Inscribe from "@/components/registry/inscribe/inscribe";

<Inscribe
  duration={900}
  stagger={90}
  fillDelay={250}
  strokeWidth={1.5}
  finish="engraved"
  replay={true}
  replayDelay={2500}
  strokeColor="#c4b5fd"
/>
```

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.
