# Integrate `Neon` from Motion Garden

You are helping me add the **Neon** 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:** Neon
- **Category:** Text Animations
- **Summary:** A neon sign, with everything that is wrong with a neon sign. Tubes strike one at a time rather than together, each settling at its own moment inside the ignition. The steady state carries a mains hum, and every so often one tube gives up for a third of a second and comes back. The glow is baked once per letter into a sprite, so a frame is a handful of draws no matter how wide the word, and the word itself never stops being a real, selectable text node underneath.
- **Reference:** https://motion-garden.netlify.app/components/neon
- **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
# Neon 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/neon/neon.tsx`

```tsx
"use client";

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

export type NeonMode = "loop" | "hover" | "steady";

interface NeonProps {
  text?: string;
  mode?: NeonMode;
  tubeColor?: string;
  glow?: number;
  core?: number;
  ignition?: number;
  cycle?: number;
  hum?: number;
  flicker?: number;
  offGlass?: boolean;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const SS = 2;

const PAD = 2;

const TUBE = 0.055;

const SPUTTER_WINDOW = 1.7;

const DARK = 1.2;

const hash = (n: number) => {
  const s = Math.sin(n * 127.1 + 311.7) * 43758.5453;
  return s - Math.floor(s);
};

const hexToRgb = (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 [255, 255, 255];
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
};

interface Tube {
  on: HTMLCanvasElement | null;
  off: HTMLCanvasElement | null;
  x: number;
  y: number;
  w: number;
  h: number;
}

const Neon = memo(
  ({
    text = "OPEN",
    mode = "loop",
    tubeColor = "#a855f7",
    glow = 18,
    core = 0.85,
    ignition = 1.6,
    cycle = 7,
    hum = 0.18,
    flicker = 0.3,
    offGlass = true,
    paused = false,
    reducedMotion = false,
    className,
  }: NeonProps) => {
    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 [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),
    });

    const live = useRef({
      mode, tubeColor, glow, core, ignition, cycle, hum, flicker, offGlass,
      reducedMotion,
    });
    live.current = {
      mode, tubeColor, glow, core, ignition, cycle, hum, flicker, offGlass,
      reducedMotion,
    };

    const state = useRef({
      ctx: null as CanvasRenderingContext2D | null,
      tubes: [] as Tube[],
      key: "",
      dpr: 1,
      w: 0,
      h: 0,
      elapsed: 0,
      lit: 0,
    });

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

      const ctx = canvas.getContext("2d");
      if (!ctx) {
        setFallback(true);
        return;
      }
      state.current.ctx = ctx;

      const bake = () => {
        const s = state.current;
        const l = live.current;
        const outer = container.getBoundingClientRect();
        const box = span.getBoundingClientRect();
        if (box.width < 1 || box.height < 1) return;

        const style = getComputedStyle(span);
        const size = parseFloat(style.fontSize) || 16;
        const font = `${style.fontStyle} ${style.fontWeight} ${size * SS}px ${style.fontFamily}`;
        const spacing =
          style.letterSpacing === "normal" ? 0 : parseFloat(style.letterSpacing) || 0;

        const probe = document.createElement("canvas").getContext("2d");
        if (!probe) return;
        probe.font = font;
        if ("letterSpacing" in probe) probe.letterSpacing = `${spacing * SS}px`;

        const prefix: number[] = [0];
        for (let i = 1; i <= text.length; i++) {
          prefix.push(probe.measureText(text.slice(0, i)).width / SS);
        }

        const pad = l.glow * PAD;
        const [r, g, b] = hexToRgb(l.tubeColor);
        const tube = `rgb(${r},${g},${b})`;
        const cr = Math.round(r + (255 - r) * l.core * 0.92);
        const cg = Math.round(g + (255 - g) * l.core * 0.92);
        const cb = Math.round(b + (255 - b) * l.core * 0.92);
        const hot = `rgb(${cr},${cg},${cb})`;

        const h = box.height;
        const tubes: Tube[] = [];

        for (let i = 0; i < text.length; i++) {
          const ch = text[i];
          const w = prefix[i + 1] - prefix[i];
          const t: Tube = {
            on: null,
            off: null,
            x: box.left - outer.left + prefix[i] - pad,
            y: box.top - outer.top - pad,
            w: w + pad * 2,
            h: h + pad * 2,
          };

          if (ch.trim() !== "") {
            const sw = Math.max(2, Math.round(t.w * SS));
            const sh = Math.max(2, Math.round(t.h * SS));

            const paint = (
              passes: Array<[number, number, string]>,
            ): HTMLCanvasElement | null => {
              const off = document.createElement("canvas");
              off.width = sw;
              off.height = sh;
              const c = off.getContext("2d");
              if (!c) return null;
              c.font = font;
              if ("letterSpacing" in c) c.letterSpacing = `${spacing * SS}px`;
              c.textAlign = "center";
              c.textBaseline = "middle";
              c.lineJoin = "round";
              c.lineCap = "round";
              c.globalCompositeOperation = "lighter";
              const cx = sw / 2 - (spacing * SS) / 2;
              const cy = sh / 2;
              for (const [blur, width, color] of passes) {
                c.shadowColor = color;
                c.shadowBlur = blur;
                c.strokeStyle = color;
                c.lineWidth = Math.max(1, size * SS * width);
                c.strokeText(ch, cx, cy);
              }
              return off;
            };

            t.on = paint([
              [l.glow * SS * 2.0, TUBE, tube],
              [l.glow * SS * 1.0, TUBE, tube],
              [l.glow * SS * 0.45, TUBE * 0.75, tube],
              [l.glow * SS * 0.18, TUBE * 0.42, hot],
            ]);
            t.off = paint([[0, TUBE, "rgba(255,255,255,0.13)"]]);
          }

          tubes.push(t);
        }

        s.tubes = tubes;
      };

      const bakeKey = () => {
        const l = live.current;
        const s = state.current;
        return `${text}|${l.tubeColor}|${l.glow}|${l.core}|${s.w}x${s.h}`;
      };

      measureRef.current = ({ width, height, dpr, bufferWidth, bufferHeight }) => {
        const s = state.current;
        canvas.width = bufferWidth;
        canvas.height = bufferHeight;
        canvas.style.width = `${width}px`;
        canvas.style.height = `${height}px`;
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        s.dpr = dpr;
        s.w = width;
        s.h = height;
        s.key = "";
      };

      drawRef.current = (dt) => {
        const s = state.current;
        const l = live.current;
        if (s.w < 1) return;

        const key = bakeKey();
        if (key !== s.key) {
          s.key = key;
          bake();
        }

        s.elapsed = (s.elapsed + dt) % 3600;
        const t = s.elapsed;
        const n = s.tubes.length;

        let ig: number;
        if (l.reducedMotion || l.mode === "steady") {
          ig = 1;
        } else if (l.mode === "loop") {
          const period = Math.max(l.cycle, 0.5) + DARK;
          const at = t % period;
          ig = at < Math.max(l.cycle, 0.5) ? at / Math.max(l.ignition, 0.05) : 0;
        } else {
          s.lit = engaged.current
            ? s.lit + dt
            : Math.max(0, s.lit - dt * Math.max(l.ignition, 0.05) * 4);
          ig = s.lit / Math.max(l.ignition, 0.05);
        }
        ig = Math.min(ig, 1);

        let victim = -1;
        if (!l.reducedMotion && l.flicker > 0 && n > 0) {
          const win = Math.floor(t / SPUTTER_WINDOW);
          if (hash(win * 7.31) < l.flicker * 0.55) {
            victim = Math.floor(hash(win * 13.17) * n);
          }
        }
        const inBurst = (t % SPUTTER_WINDOW) / SPUTTER_WINDOW < 0.3;

        ctx.clearRect(0, 0, s.w, s.h);
        ctx.globalCompositeOperation = "lighter";

        for (let i = 0; i < n; i++) {
          const tube = s.tubes[i];
          if (!tube.on) continue;

          const settle = 0.28 + hash(i * 3.7 + 1.1) * 0.68;
          let brightness: number;

          if (ig <= 0) {
            brightness = 0;
          } else if (ig < settle) {
            const odds = Math.pow(ig / settle, 1.7);
            brightness = hash(i * 17.3 + Math.floor(t * 26) * 1.7) < odds ? 1 : 0.06;
          } else {
            const phase = hash(i * 5.3) * 6.283;
            const h1 = Math.sin(t * 12.566 + phase);
            const h2 = Math.sin(t * 3.1 + phase * 2.1);
            brightness = 1 - l.hum * (0.5 + 0.5 * h1) * 0.4 - l.hum * (0.5 + 0.5 * h2) * 0.18;
          }

          if (i === victim && inBurst && ig >= settle) {
            brightness *= hash(i * 2.9 + Math.floor(t * 34) * 3.1) < 0.42 ? 1 : 0.08;
          }

          if (l.offGlass && tube.off && brightness < 0.9) {
            ctx.globalAlpha = 1 - brightness;
            ctx.drawImage(tube.off, tube.x, tube.y, tube.w, tube.h);
          }
          if (brightness > 0.01) {
            ctx.globalAlpha = brightness;
            ctx.drawImage(tube.on, tube.x, tube.y, tube.w, tube.h);
          }
        }

        ctx.globalAlpha = 1;
        ctx.globalCompositeOperation = "source-over";
      };

      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;
          state.current.key = "";
          loop.paint();
        })
        .catch(() => {});

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

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

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

    const hover = mode === "hover";

    return (
      <div
        ref={containerRef}
        style={{ padding: `${glow * PAD}px` }}
        className={`relative inline-block ${className ?? "font-display text-[clamp(2.25rem,6vw,5.5rem)] leading-none font-bold tracking-[0.1em]"}`}
        onPointerEnter={hover ? engage : undefined}
        onPointerLeave={hover ? release : undefined}
        onPointerCancel={hover ? release : undefined}
      >
        <span
          ref={textRef}
          className="relative block whitespace-pre"
          style={{ color: fallback ? tubeColor : "transparent" }}
        >
          {text}
        </span>
        <canvas
          ref={canvasRef}
          className="pointer-events-none absolute inset-0 block"
        />
      </div>
    );
  },
);

Neon.displayName = "Neon";

export default Neon;
```

### 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" | "steady"` | `"loop"` | What drives the ignition. Loop runs the sign as a shopfront does — lit, cut, struck again. Hover strikes it under the pointer and kills it a quarter of a second after the pointer leaves, because a sign does not fade out. Steady skips the start-up entirely and leaves only the hum and the failing tube. |
| `tubeColor` | `string (hex)` | `"#a855f7"` | The gas. |
| `glow` | `number` | `18` | Halo spread, and also the layout room reserved for it — the root pads itself by twice this, because a halo that leaves its box gets painted over by whatever the page put beside it. Changing this rebakes every sprite, so it is a setting rather than something to animate. Range 4–40 px. |
| `core` | `number` | `0.85` | How white-hot the centre of the tube runs against the saturated halo around it. It never reaches pure white on purpose: a white centre reads as a lightbulb behind a coloured filter rather than as excited gas. Range 0–1. |
| `ignition` | `number` | `1.6` | Seconds from cold to steady. Each letter picks its own settle point inside this window and its chance of holding climbs as it warms, so the stutter thins out by itself instead of stopping on a timer. Range 0.3–4 s. Ignored while `mode` is `steady`. |
| `cycle` | `number` | `7` | Seconds lit before the power cuts and the sign strikes again. The dark between is fixed and short — long enough to register as off, short enough that nobody walks away during it. Range 3–20 s. Ignored unless `mode` is `loop`. |
| `hum` | `number` | `0.18` | Depth of the mains hum once a tube is lit. Two frequencies rather than one, because a single sine reads as a pulse effect; the beat between them is what reads as electricity. Range 0–1. |
| `flicker` | `number` | `0.3` | How often a tube gives up for a moment. One roll every one and a bit seconds decides whether a letter fails and which one, so failures are occasional and specific rather than a permanent shimmer across the whole word. Range 0–1. |
| `offGlass` | `boolean` | `true` | Show the dark glass where a tube is unlit. It carries no glow at all — a dark tube that still glows is the tell that the sign was never really off. |

## Usage

```tsx
import Neon from "@/components/registry/neon/neon";

<Neon
  mode="loop"
  tubeColor="#a855f7"
  glow={18}
  core={0.85}
  ignition={1.6}
  cycle={7}
  hum={0.18}
  flicker={0.3}
  offGlass={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.
- 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.
