# Integrate `Inlay` from Motion Garden

You are helping me add the **Inlay** 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:** Inlay
- **Category:** Text Animations
- **Summary:** A live shader material poured into real letterforms — molten rock, aurora, chrome, embers, tide. The text stays a real text node at transparent, so it is still selectable, searchable and read aloud exactly once while something genuinely animated fills it.
- **Reference:** https://motion-garden.netlify.app/components/inlay
- **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 ogl
```

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

```tsx
"use client";

import { memo, useEffect, useRef, useState } from "react";
import { Renderer, Program, Mesh, Triangle, Texture } from "ogl";
import { useAnimationLoop, type Metrics } from "@/hooks/use-animation-loop";

export type InlayMaterial = "molten" | "aurora" | "chrome" | "embers" | "tide";

interface InlayProps {
  text?: string;
  material?: InlayMaterial;
  flowSpeed?: number;
  scale?: number;
  sweep?: number;
  glow?: number;
  grain?: number;
  warp?: number;
  hoverBoost?: number;
  colorA?: string;
  colorB?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const MATERIAL_ID: Record<string, number> = {
  molten: 0, aurora: 1, chrome: 2, embers: 3, tide: 4,
};

const hexToRgb01 = (hex: string): [number, number, number] => {
  const h = hex.replace("#", "");
  const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
  const n = parseInt(full, 16);
  if (Number.isNaN(n) || full.length !== 6) return [1, 1, 1];
  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
};

const supportsWebGL2 = () => {
  try {
    return !!document.createElement("canvas").getContext("webgl2");
  } catch {
    return false;
  }
};

const vertex = `#version 300 es
in vec2 position;
in vec2 uv;
out vec2 vUv;
void main() { vUv = uv; gl_Position = vec4(position, 0.0, 1.0); }`;

const fragment = `#version 300 es
precision highp float;
in vec2 vUv;
out vec4 fragColor;

uniform sampler2D uMask;
uniform vec2  uResolution;
uniform float uTime;
uniform float uMaterial;
uniform float uScale;
uniform float uSweep;
uniform float uGlow;
uniform float uGrain;
uniform float uWarp;
uniform float uBoost;
uniform vec2  uPointer;
uniform vec3  uA;
uniform vec3  uB;

float hash21(vec2 p) {
  p = fract(p * vec2(127.1, 311.7));
  p += dot(p, p + 34.56);
  return fract(p.x * p.y);
}
float vnoise(vec2 p) {
  vec2 i = floor(p), f = fract(p);
  vec2 u = f * f * (3.0 - 2.0 * f);
  return mix(mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x),
             mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x), u.y);
}
float fbm(vec2 p) {
  float a = 0.5, s = 0.0;
  for (int i = 0; i < 4; i++) { s += a * vnoise(p); p *= 2.03; a *= 0.5; }
  return s;
}

vec3 materialAt(vec2 p, float t) {
  if (uMaterial < 0.5) {
    float v = fbm(p + vec2(t * 0.6, t * 0.2));
    float veins = smoothstep(0.42, 0.72, v);
    return mix(uA * 0.35, uB, veins) + uB * pow(veins, 3.0) * 0.6;
  }
  if (uMaterial < 1.5) {
    float band = fbm(p * vec2(0.7, 2.2) + vec2(t * 0.35, 0.0));
    return mix(uA, uB, smoothstep(0.25, 0.85, band)) * (0.7 + 0.6 * band);
  }
  if (uMaterial < 2.5) {
    // Chrome: hard light-to-dark steps rather than a gradient. The sharpness of
    // the transition is what reads as metal.
    float h = fbm(p * 1.4 + vec2(t * 0.25, 0.0));
    float step1 = smoothstep(0.44, 0.5, h);
    float step2 = smoothstep(0.62, 0.66, h);
    vec3 base = mix(uA * 0.25, vec3(0.85), step1);
    return mix(base, uB, step2 * 0.7);
  }
  if (uMaterial < 3.5) {
    float heat = fbm(p * 1.6 - vec2(0.0, t * 1.1));
    float core = smoothstep(0.35, 0.9, heat);
    return mix(uA * 0.2, uB, core) + vec3(1.0, 0.55, 0.15) * pow(core, 4.0) * 0.9;
  }
  float w = sin(p.x * 2.2 + t) * 0.5 + fbm(p + t * 0.15);
  return mix(uA, uB, smoothstep(-0.2, 1.2, w));
}

void main() {
  vec2 uv = vUv;
  float aspect = uResolution.x / max(uResolution.y, 1.0);
  vec2 p = vec2(uv.x * aspect, uv.y) * max(uScale, 0.05) * 3.0;

  float t = uTime * (1.0 + uBoost);
  vec2 warp = vec2(fbm(p + t * 0.2), fbm(p.yx + 4.1 - t * 0.15)) - 0.5;
  vec3 col = materialAt(p + warp * uWarp * 1.6, t);

  // The pour runs against the glyph's own horizontal position, so it follows the
  // letterforms instead of a rectangle crossing them.
  float pour = uSweep <= 0.001 ? 1.0 : smoothstep(0.0, 1.0, (uTime / max(uSweep, 0.02)) - uv.x * 0.9);
  col *= pour;

  float mask = texture(uMask, vec2(uv.x, 1.0 - uv.y)).a;

  // Bloom taps the mask around the fragment rather than blurring the material —
  // the glow has to belong to the glyph edge, not to whatever colour happens to
  // sit near it.
  vec2 px = 1.0 / max(uResolution, vec2(1.0));
  float halo = 0.0;
  halo += texture(uMask, vec2(uv.x + px.x * 3.0, 1.0 - uv.y)).a;
  halo += texture(uMask, vec2(uv.x - px.x * 3.0, 1.0 - uv.y)).a;
  halo += texture(uMask, vec2(uv.x, 1.0 - uv.y + px.y * 3.0)).a;
  halo += texture(uMask, vec2(uv.x, 1.0 - uv.y - px.y * 3.0)).a;
  halo *= 0.25;

  float g = hash21(gl_FragCoord.xy) - 0.5;
  col += g * uGrain * 0.35;

  float pointerLift = exp(-dot(uv - uPointer, uv - uPointer) * 18.0) * uBoost * 0.4;
  col *= 1.0 + pointerLift;

  float alpha = clamp(mask + halo * uGlow * 0.55, 0.0, 1.0) * pour;
  fragColor = vec4(col * alpha, alpha);
}`;

const Inlay = memo(
  ({
    text = "MOTION GARDEN",
    material = "molten",
    flowSpeed = 0.4,
    scale = 1.6,
    sweep = 0.8,
    glow = 0.4,
    grain = 0.15,
    warp = 0.25,
    hoverBoost = 0.6,
    colorA = "#a855f7",
    colorB = "#38bdf8",
    paused = false,
    reducedMotion = false,
    className,
  }: InlayProps) => {
    const containerRef = useRef<HTMLSpanElement>(null);
    const textRef = useRef<HTMLSpanElement>(null);
    const drawRef = useRef<((dt: number) => void | false) | null>(null);
    const measureRef = useRef<((m: Metrics) => void) | null>(null);
    const glRef = useRef<WebGLRenderingContext | WebGL2RenderingContext | null>(null);
    const pointer = useRef({ x: 0.5, y: 0.5, over: false });

    const [fallback, setFallback] = useState(false);

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

    const pourFor = reducedMotion ? 0 : sweep;

    const live = useRef({
      text, material, flowSpeed, scale, sweep: pourFor, glow, grain, warp,
      hoverBoost, colorA, colorB,
    });
    live.current = {
      text, material, flowSpeed, scale, sweep: pourFor, glow, grain, warp,
      hoverBoost, colorA, colorB,
    };

    useEffect(() => {
      const container = containerRef.current;
      if (fallback || !container) return;
      if (!supportsWebGL2()) {
        setFallback(true);
        return;
      }

      const renderer = new Renderer({
        webgl: 2,
        alpha: true,
        antialias: false,
        premultipliedAlpha: true,
        powerPreference: "high-performance",
        dpr: Math.min(window.devicePixelRatio || 1, 2),
      });
      const glc = renderer.gl;
      const gl2 = glc as unknown as WebGL2RenderingContext;
      glRef.current = gl2;
      glc.clearColor(0, 0, 0, 0);

      const canvas = glc.canvas as HTMLCanvasElement;
      canvas.style.display = "block";
      canvas.style.position = "absolute";
      canvas.style.top = "0";
      canvas.style.left = "0";
      canvas.style.pointerEvents = "none";
      container.appendChild(canvas);

      const maskCanvas = document.createElement("canvas");
      const maskTexture = new Texture(glc, {
        image: maskCanvas,
        generateMipmaps: false,
        minFilter: gl2.LINEAR,
        magFilter: gl2.LINEAR,
        wrapS: gl2.CLAMP_TO_EDGE,
        wrapT: gl2.CLAMP_TO_EDGE,
        premultiplyAlpha: false,
        flipY: false,
      });

      const program = new Program(glc, {
        vertex,
        fragment,
        transparent: true,
        uniforms: {
          uMask: { value: maskTexture },
          uResolution: { value: new Float32Array([1, 1]) },
          uTime: { value: 0 },
          uMaterial: { value: MATERIAL_ID[material] ?? 0 },
          uScale: { value: scale },
          uSweep: { value: pourFor },
          uGlow: { value: glow },
          uGrain: { value: grain },
          uWarp: { value: warp },
          uBoost: { value: 0 },
          uPointer: { value: new Float32Array([0.5, 0.5]) },
          uA: { value: new Float32Array(hexToRgb01(colorA)) },
          uB: { value: new Float32Array(hexToRgb01(colorB)) },
        },
      });
      const mesh = new Mesh(glc, { geometry: new Triangle(glc), program });
      const u = program.uniforms as Record<string, { value: unknown }>;

      let time = 0;
      let boost = 0;

      const rebuildMask = (w: number, h: number, dpr: number) => {
        const node = textRef.current;
        if (!node || w < 1 || h < 1) return;
        maskCanvas.width = Math.max(1, Math.round(w * dpr));
        maskCanvas.height = Math.max(1, Math.round(h * dpr));
        const ctx = maskCanvas.getContext("2d");
        if (!ctx) return;
        const cs = getComputedStyle(node);
        ctx.clearRect(0, 0, maskCanvas.width, maskCanvas.height);
        ctx.scale(dpr, dpr);
        ctx.font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} / ${cs.lineHeight} ${cs.fontFamily}`;
        ctx.letterSpacing = cs.letterSpacing;
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.fillStyle = "#fff";
        ctx.fillText(live.current.text, w / 2, h / 2);
        maskTexture.image = maskCanvas;
        maskTexture.needsUpdate = true;
      };

      const sync = () => {
        const l = live.current;
        (u.uTime as { value: number }).value = time;
        (u.uMaterial as { value: number }).value = MATERIAL_ID[l.material] ?? 0;
        (u.uScale as { value: number }).value = l.scale;
        (u.uSweep as { value: number }).value = l.sweep;
        (u.uGlow as { value: number }).value = l.glow;
        (u.uGrain as { value: number }).value = l.grain;
        (u.uWarp as { value: number }).value = l.warp;
        (u.uBoost as { value: number }).value = boost;
        const pv = (u.uPointer as { value: Float32Array }).value;
        pv[0] = pointer.current.x;
        pv[1] = pointer.current.y;
        ((u.uA as { value: Float32Array }).value).set(hexToRgb01(l.colorA));
        ((u.uB as { value: Float32Array }).value).set(hexToRgb01(l.colorB));
      };

      drawRef.current = (dt) => {
        const l = live.current;
        time += dt * l.flowSpeed;
        const want = pointer.current.over ? l.hoverBoost : 0;
        boost += (want - boost) * Math.min(1, dt * 6);
        sync();
        renderer.render({ scene: mesh });
      };

      measureRef.current = ({ width, height, dpr }) => {
        renderer.dpr = dpr;
        renderer.setSize(Math.max(1, Math.floor(width)), Math.max(1, Math.floor(height)));
        const res = (u.uResolution as { value: Float32Array }).value;
        res[0] = glc.drawingBufferWidth;
        res[1] = glc.drawingBufferHeight;
        rebuildMask(width, height, dpr);
        sync();
        renderer.render({ scene: mesh });
      };

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

      let disposed = false;
      document.fonts?.ready.then(() => {
        if (disposed) return;
        loop.resize();
      });

      return () => {
        disposed = true;
        drawRef.current = null;
        measureRef.current = null;
        if (container.contains(canvas)) container.removeChild(canvas);
      };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [fallback]);

    useEffect(() => {
      loop.resize();
    }, [text, loop]);

    useEffect(() => {
      loop.paint();
    }, [material, flowSpeed, scale, pourFor, glow, grain, warp, hoverBoost, colorA, colorB, loop]);

    const track = (e: React.PointerEvent<HTMLSpanElement>) => {
      const r = e.currentTarget.getBoundingClientRect();
      if (r.width === 0 || r.height === 0) return;
      pointer.current.x = (e.clientX - r.left) / r.width;
      pointer.current.y = 1 - (e.clientY - r.top) / r.height;
      pointer.current.over = true;
      loop.start();
    };
    const release = () => {
      pointer.current.over = false;
      loop.start();
    };

    if (fallback) {
      return (
        <span
          className={className ?? "relative inline-block"}
          style={{
            backgroundImage: `linear-gradient(100deg, ${colorA}, ${colorB})`,
            backgroundClip: "text",
            WebkitBackgroundClip: "text",
            color: "transparent",
          }}
        >
          {text}
        </span>
      );
    }

    return (
      <span
        ref={containerRef}
        className={className ?? "relative inline-block"}
        onPointerMove={track}
        onPointerLeave={release}
        onPointerCancel={release}
      >
        <span ref={textRef} style={{ color: "transparent" }}>
          {text}
        </span>
      </span>
    );
  },
);

Inlay.displayName = "Inlay";

export default Inlay;
```

### 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 |
| --- | --- | --- | --- |
| `material` | `"molten" | "aurora" | "chrome" | "embers" | "tide"` | `"molten"` | What is poured into the letterforms. Each is a different branch over the same glyph mask, so switching is a uniform change and never a relayout — the type does not move when the material does. |
| `flowSpeed` | `number` | `0.4` | Rate the material flows. At zero it sets, which is the only way to judge the fill on its own rather than the motion carrying it. Range 0–2 ×. |
| `scale` | `number` | `1.6` | Size of the material's features relative to the type. Under about one the pattern is larger than the word and the letters read as flat colour; over three it turns to grain inside the strokes and the word stops being legible before it stops being pretty. Range 0.3–6. |
| `sweep` | `number` | `0.8` | How long the material takes to pour across the line on mount. The wipe runs in the shader against the glyph's own horizontal position, so it follows the letterforms rather than being a rectangle crossing them. Zero fills instantly. Range 0–3 s. |
| `glow` | `number` | `0.4` | Bloom bleeding past the glyph edge. It is sampled from the mask around each fragment rather than by blurring the material, so the halo belongs to the letterform instead of to whatever colour happened to sit next to it. Past about one the letters fatten and the counters close up. Range 0–1.5. |
| `grain` | `number` | `0.15` | Dither over the fill. A smooth gradient inside a letterform bands on an eight-bit display more visibly than almost anywhere else, because there is a hard edge right beside it for the eye to compare against. Range 0–0.6. |
| `warp` | `number` | `0.25` | How far the material drags its own coordinates before it is sampled. This is what turns a moving gradient into something that looks like it is being stirred. Range 0–1. |
| `hoverBoost` | `number` | `0.6` | How much the material accelerates and lifts under the pointer. The real text sits underneath at transparent — selection works, a screen reader reads it, a crawler indexes it — so this is decoration on a working headline rather than a replacement for one. Range 0–2 ×. |
| `colorA` | `string (hex)` | `"#a855f7"` | The material's shadow. |
| `colorB` | `string (hex)` | `"#38bdf8"` | The material's light. |

## Usage

```tsx
import Inlay from "@/components/registry/inlay/inlay";

<Inlay
  material="molten"
  flowSpeed={0.4}
  scale={1.6}
  sweep={0.8}
  glow={0.4}
  grain={0.15}
  warp={0.25}
  hoverBoost={0.6}
  colorA="#a855f7"
  colorB="#38bdf8"
/>
```

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. Wire the component into the place I point you at, with sensible props for that context.
4. 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.
