# Integrate `Constellation` from Motion Garden

You are helping me add the **Constellation** 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:** Constellation
- **Category:** Backgrounds
- **Summary:** A constellation network. Drifting particles link by proximity, chase and flee the cursor, and glow.
- **Reference:** https://motion-garden.netlify.app/components/constellation
- **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
# Constellation needs no npm packages
```

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

```tsx
"use client";

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

const TWO_PI = Math.PI * 2;

interface ConstellationProps {
	colors?: string[];
	density?: number;
	speed?: number;
	connectDistance?: number;
	cursorDistance?: number;
	repelForce?: number;
	lineOpacity?: number;
	glow?: number;
	paused?: boolean;
	[key: string]: unknown;
}

interface Particle {
	x: number;
	y: number;
	vx: number;
	vy: number;
	baseRadius: number;
	radius: number;
	colorIndex: number;
}

type Rgb = [number, number, number];

const DEFAULT_COLORS = ["#a855f7", "#ff9207", "#22d3ee"];

function hexToRgb(hex: string): Rgb {
	const h = hex.replace("#", "");
	const full =
		h.length === 3
			? h
					.split("")
					.map((c) => c + c)
					.join("")
			: h;
	const n = parseInt(full, 16);
	return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}

function lift(c: number): number {
	return Math.round(c + (255 - c) * 0.65);
}

const Constellation = memo(
	({
		colors = DEFAULT_COLORS,
		density = 1,
		speed = 0.8,
		connectDistance = 120,
		cursorDistance = 150,
		repelForce = 2,
		lineOpacity = 0.5,
		glow = 10,
		paused = false,
		...rest
	}: ConstellationProps) => {
		const canvasRef = useRef<HTMLCanvasElement>(null);
		const particlesRef = useRef<Particle[]>([]);
		const mouseRef = useRef({ x: -1000, y: -1000 });
		const sizeRef = useRef({ w: 0, h: 0 });
		const rafRef = useRef<number | null>(null);
		const propsRef = useRef({
			colors,
			density,
			speed,
			connectDistance,
			cursorDistance,
			repelForce,
			lineOpacity,
			glow,
			paused,
		});
		propsRef.current = {
			colors,
			density,
			speed,
			connectDistance,
			cursorDistance,
			repelForce,
			lineOpacity,
			glow,
			paused,
		};
		const rebuildRef = useRef<(() => void) | null>(null);
		const containerRef = useRef<HTMLDivElement>(null);
		const drawRef = useRef<(() => void | false) | null>(null);
		const measureRef = useRef<((m: Metrics) => void) | null>(null);

		const loop = useAnimationLoop({
			target: containerRef,
			halted: paused,
			dpr: 2,
			resizeDebounceMs: 100,
			onResize: (metrics) => measureRef.current?.(metrics),
			onFrame: () => (drawRef.current ? drawRef.current() : false),
		});

		useEffect(() => {
			const canvas = canvasRef.current;
			if (!canvas) return;
			const ctx = canvas.getContext("2d", { alpha: true });
			if (!ctx) return;
			let frame = 0;

			function initParticles() {
				const { w, h } = sizeRef.current;
				const p = propsRef.current;
				const count = Math.max(
					8,
					Math.min(250, Math.floor(((w * h) / 10000) * p.density)),
				);
				const max = p.speed;
				const min = p.speed * 0.4;
				const particles: Particle[] = new Array(count);
				for (let i = 0; i < count; i++) {
					const v = Math.random() * (max - min) + min;
					const angle = Math.random() * TWO_PI;
					const baseRadius = Math.random() * 2 + 1;
					particles[i] = {
						x: Math.random() * w,
						y: Math.random() * h,
						vx: Math.cos(angle) * v,
						vy: Math.sin(angle) * v,
						baseRadius,
						radius: baseRadius,
						colorIndex: Math.floor(Math.random() * 3),
					};
				}
				particlesRef.current = particles;
			}

			measureRef.current = ({ width, height, dpr, bufferWidth, bufferHeight }) => {
				canvas!.width = bufferWidth;
				canvas!.height = bufferHeight;
				canvas!.style.width = `${width}px`;
				canvas!.style.height = `${height}px`;
				ctx!.setTransform(dpr, 0, 0, dpr, 0, 0);
				sizeRef.current = { w: width, h: height };
				initParticles();
			};

			function tick() {
				frame++;
				const p = propsRef.current;
				const { w, h } = sizeRef.current;
				const particles = particlesRef.current;
				const m = mouseRef.current;
				const animate = !p.paused;
				const maxSpeed = p.speed;
				const minSpeed = p.speed * 0.4;
				const t = frame * 0.033;

				ctx!.clearRect(0, 0, w, h);

				for (let i = 0; i < particles.length; i++) {
					const pt = particles[i];
					if (animate) {
						const cur = Math.sqrt(pt.vx * pt.vx + pt.vy * pt.vy);
						if (cur > 0) {
							const target = Math.max(minSpeed, Math.min(cur, maxSpeed));
							pt.vx = (pt.vx / cur) * target;
							pt.vy = (pt.vy / cur) * target;
						}

						if (p.cursorDistance > 0) {
							const dx = m.x - pt.x;
							const dy = m.y - pt.y;
							const dist = Math.sqrt(dx * dx + dy * dy);
							if (dist < p.cursorDistance && dist > 0) {
								const force = (p.cursorDistance - dist) / p.cursorDistance;
								pt.x -= (dx / dist) * force * p.repelForce;
								pt.y -= (dy / dist) * force * p.repelForce;
							}
						}

						pt.x += pt.vx;
						pt.y += pt.vy;

						if (pt.x < 0 || pt.x > w) pt.vx *= -1;
						if (pt.y < 0 || pt.y > h) pt.vy *= -1;
						if (pt.x < 0) pt.x = 0;
						if (pt.x > w) pt.x = w;
						if (pt.y < 0) pt.y = 0;
						if (pt.y > h) pt.y = h;

						pt.radius = pt.baseRadius + Math.sin(t + pt.x) * 0.5;
					} else {
						pt.radius = pt.baseRadius;
					}
				}

				const palette: Rgb[] =
					p.colors.length > 0
						? p.colors.map(hexToRgb)
						: [hexToRgb(DEFAULT_COLORS[0])];
				const colorOf = (pt: Particle) => palette[pt.colorIndex % palette.length];

				for (let i = 0; i < particles.length; i++) {
					const pt = particles[i];
					const [r, g, b] = colorOf(pt);
					ctx!.beginPath();
					ctx!.arc(pt.x, pt.y, Math.max(0.1, pt.radius), 0, TWO_PI);
					ctx!.fillStyle = `rgba(${r}, ${g}, ${b}, 0.85)`;
					if (p.glow > 0) {
						ctx!.shadowBlur = p.glow * 2.5;
						ctx!.shadowColor = `rgb(${r}, ${g}, ${b})`;
						ctx!.fill();
						ctx!.fill();
						ctx!.shadowBlur = 0;
					} else {
						ctx!.fill();
					}
				}

				const connect = p.connectDistance;
				ctx!.lineWidth = 1;
				for (let i = 0; i < particles.length; i++) {
					const pi = particles[i];
					const [ri, gi, bi] = colorOf(pi);

					if (p.cursorDistance > 0) {
						const mDx = m.x - pi.x;
						const mDy = m.y - pi.y;
						const mDist = Math.sqrt(mDx * mDx + mDy * mDy);
						if (mDist < p.cursorDistance) {
							const alpha = Math.min(
								1,
								(1 - mDist / p.cursorDistance) * p.lineOpacity * 1.6,
							);
							const grad = ctx!.createLinearGradient(pi.x, pi.y, m.x, m.y);
							grad.addColorStop(0, `rgba(${ri}, ${gi}, ${bi}, ${alpha})`);
							grad.addColorStop(
								1,
								`rgba(${lift(ri)}, ${lift(gi)}, ${lift(bi)}, ${alpha})`,
							);
							ctx!.beginPath();
							ctx!.moveTo(pi.x, pi.y);
							ctx!.lineTo(m.x, m.y);
							ctx!.strokeStyle = grad;
							ctx!.stroke();
						}
					}

					for (let j = i + 1; j < particles.length; j++) {
						const pj = particles[j];
						const dx = pi.x - pj.x;
						const dy = pi.y - pj.y;
						const distSq = dx * dx + dy * dy;
						if (distSq < connect * connect) {
							const alpha =
								(1 - Math.sqrt(distSq) / connect) * p.lineOpacity;
							ctx!.beginPath();
							ctx!.moveTo(pi.x, pi.y);
							ctx!.lineTo(pj.x, pj.y);
							if (pi.colorIndex === pj.colorIndex) {
								ctx!.strokeStyle = `rgba(${ri}, ${gi}, ${bi}, ${alpha})`;
							} else {
								const [rj, gj, bj] = colorOf(pj);
								const grad = ctx!.createLinearGradient(pi.x, pi.y, pj.x, pj.y);
								grad.addColorStop(0, `rgba(${ri}, ${gi}, ${bi}, ${alpha})`);
								grad.addColorStop(1, `rgba(${rj}, ${gj}, ${bj}, ${alpha})`);
								ctx!.strokeStyle = grad;
							}
							ctx!.stroke();
						}
					}
				}

			}
			drawRef.current = tick;

			function onPointerMove(e: PointerEvent) {
				const rect = canvas!.getBoundingClientRect();
				mouseRef.current.x = e.clientX - rect.left;
				mouseRef.current.y = e.clientY - rect.top;
			}
			function onPointerGone() {
				mouseRef.current.x = -1000;
				mouseRef.current.y = -1000;
			}
			function onPointerUp(e: PointerEvent) {
				if (e.pointerType !== "mouse") onPointerGone();
			}

			window.addEventListener("pointermove", onPointerMove, { passive: true });
			window.addEventListener("pointerup", onPointerUp, { passive: true });
			document.documentElement.addEventListener("pointerleave", onPointerGone);
			loop.resize();
			loop.start();

			rebuildRef.current = () => {
				if (sizeRef.current.w > 0) initParticles();
			};

			return () => {
				drawRef.current = null;
				measureRef.current = null;
				window.removeEventListener("pointermove", onPointerMove);
				window.removeEventListener("pointerup", onPointerUp);
				document.documentElement.removeEventListener(
					"pointerleave",
					onPointerGone,
				);
			};
			// eslint-disable-next-line react-hooks/exhaustive-deps
		}, []);

		useEffect(() => {
			rebuildRef.current?.();
		}, [density]);

		return (
			<div ref={containerRef} className="relative h-full w-full" {...rest}>
				<canvas
					ref={canvasRef}
					className="cursor-crosshair touch-none"
					style={{
						position: "absolute",
						inset: 0,
						width: "100%",
						height: "100%",
					}}
				/>
			</div>
		);
	},
);

Constellation.displayName = "Constellation";

export default Constellation;
```

### 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 |
| --- | --- | --- | --- |
| `density` | `number` | `1` | Particle density relative to area. Range 0.3–2.5. |
| `speed` | `number` | `0.8` | Top drift speed of particles. Range 0.1–3. |
| `connectDistance` | `number` | `120` | Max distance for particle-to-particle lines. Range 40–250 px. |
| `cursorDistance` | `number` | `150` | Cursor link + repel radius; 0 disables. Range 0–300 px. |
| `repelForce` | `number` | `2` | Push strength inside the cursor radius. Range 0–6. |
| `lineOpacity` | `number` | `0.5` | Opacity multiplier on connection lines. Range 0–1. |
| `glow` | `number` | `10` | Particle glow blur. Range 0–30. |
| `color1` | `string (hex)` | `"#a855f7"` | First particle color. |
| `color2` | `string (hex)` | `"#ff9207"` | Second particle color. |
| `color3` | `string (hex)` | `"#22d3ee"` | Third particle color — lines between mixed pairs blend as gradients. |

## Usage

```tsx
import Constellation from "@/components/registry/constellation/constellation";

<Constellation
  density={1}
  speed={0.8}
  connectDistance={120}
  cursorDistance={150}
  repelForce={2}
  lineOpacity={0.5}
  glow={10}
  color1="#a855f7"
  color2="#ff9207"
  color3="#22d3ee"
/>
```

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 runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The `touch-action: none` on the hit target is load-bearing — without it a finger drag scrolls the page instead of driving the effect. Do not strip it as a stray utility class.
- 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.
