# Integrate `Ribbons` from Motion Garden

You are helping me add the **Ribbons** 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:** Ribbons
- **Category:** Backgrounds
- **Summary:** Flowing translucent ribbons drifting across a canvas.
- **Reference:** https://motion-garden.netlify.app/components/ribbons
- **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
# Ribbons 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/ribbons/ribbons.tsx`

```tsx
'use client'

import React, { useEffect, useRef } from 'react'
import { useAnimationLoop, type Metrics } from '@/hooks/use-animation-loop'

interface RibbonsOptions {
  colorSaturation: string
  colorBrightness: string
  colorAlpha: number
  colorCycleSpeed: number
  verticalPosition: 'top' | 'middle' | 'bottom' | 'random'
  horizontalSpeed: number
  ribbonCount: number
  strokeSize: number
  parallaxAmount: number
  animateSections: boolean
  color?: string
  paused?: boolean
}

interface Point {
  x: number
  y: number
}

interface RibbonSection {
  point1: Point
  point2: Point
  point3: Point
  color: number | string
  delay: number
  dir: 'left' | 'right'
  alpha: number
  phase: number
}

const Ribbons: React.FC<RibbonsOptions> = (options) => {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)
  const optionsRef = useRef(options)
  useEffect(() => {
    optionsRef.current = options
  })

  const drawRef = useRef<(() => void | false) | null>(null)
  const measureRef = useRef<((m: Metrics) => void) | null>(null)

  const loop = useAnimationLoop({
    target: containerRef,
    halted: options.paused ?? false,
    dpr: 1,
    onResize: (metrics) => measureRef.current?.(metrics),
    onFrame: () => (drawRef.current ? drawRef.current() : false),
  })
  const ribbonsRef = useRef<RibbonSection[][]>([])

  useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return

    const context = canvas.getContext('2d')
    if (!context) return

    let width = 0
    let height = 0
    let scroll = 0
    let rafId = 0
    const ribbons = ribbonsRef.current

    const random = (min: number, max: number): number => {
      return Math.random() * (max - min) + min
    }

    const screenInfo = (): {
      width: number
      height: number
      scrolly: number
    } => {
      const w = window
      const d = document.documentElement
      const b = document.body
      return {
        width: w.innerWidth || d.clientWidth || b.clientWidth,
        height: w.innerHeight || d.clientHeight || b.clientHeight,
        scrolly: w.scrollY || d.scrollTop || b.scrollTop,
      }
    }

    const createPoint = (x: number, y: number): Point => ({ x, y })

    const addRibbon = () => {
      const dir = Math.round(random(1, 9)) > 5 ? 'right' : 'left'
      const stop = 1000
      const hide = 200
      const min = 0 - hide
      const max = width + hide
      const startx = dir === 'right' ? min : max
      let starty = Math.round(random(0, height))

      if (/^(top|min)$/i.test(options.verticalPosition)) {
        starty = 0 + hide
      } else if (/^(middle|center)$/i.test(options.verticalPosition)) {
        starty = height / 2
      } else if (/^(bottom|max)$/i.test(options.verticalPosition)) {
        starty = height - hide
      }

      const ribbon: RibbonSection[] = []
      let point1 = createPoint(startx, starty)
      let point2 = createPoint(startx, starty)

      const color = options.color || Math.round(random(35, 40))
      let delay = 0

      for (let i = 0; i < stop; i++) {
        const movex = Math.round(random(-0.2, 0.8) * options.horizontalSpeed)
        const movey = Math.round(random(-0.5, 0.5) * (height * 0.25))

        const point3 = createPoint(
          point2.x + (dir === 'right' ? movex : -movex),
          point2.y + movey
        )

        if (
          (dir === 'right' && point2.x >= max) ||
          (dir === 'left' && point2.x <= min)
        ) {
          break
        }

        ribbon.push({
          point1: createPoint(point1.x, point1.y),
          point2: createPoint(point2.x, point2.y),
          point3,
          color,
          delay,
          dir,
          alpha: 0,
          phase: 0,
        })

        point1 = createPoint(point2.x, point2.y)
        point2 = createPoint(point3.x, point3.y)

        delay += 4
      }

      ribbons.push(ribbon)
    }

    const drawRibbonSection = (section: RibbonSection): boolean => {
      if (section.phase >= 1 && section.alpha <= 0) {
        return true
      }

      if (section.delay <= 0) {
        section.phase += 0.02
        section.alpha = Math.sin(section.phase) * 1
        section.alpha = Math.max(0, Math.min(section.alpha, 1))

        if (options.animateSections) {
          const mod = Math.sin(1 + (section.phase * Math.PI) / 2) * 0.1

          if (section.dir === 'right') {
            section.point1.x += mod
            section.point2.x += mod
            section.point3.x += mod
          } else {
            section.point1.x -= mod
            section.point2.x -= mod
            section.point3.x -= mod
          }

          section.point1.y += mod
          section.point2.y += mod
          section.point3.y += mod
        }
      } else {
        section.delay -= 0.5
      }

      let c: string
      if (typeof section.color === 'string') {
        c = `${section.color}${Math.round(section.alpha * 255)
          .toString(16)
          .padStart(2, '0')}`
      } else {
        c = `hsla(${section.color}, ${options.colorSaturation}, ${options.colorBrightness}, ${section.alpha})`
      }

      context.save()

      if (options.parallaxAmount !== 0) {
        context.translate(0, scroll * options.parallaxAmount)
      }

      context.beginPath()
      context.moveTo(section.point1.x, section.point1.y)
      context.lineTo(section.point2.x, section.point2.y)
      context.lineTo(section.point3.x, section.point3.y)
      context.fillStyle = c
      context.fill()

      if (options.strokeSize > 0) {
        context.lineWidth = options.strokeSize
        context.strokeStyle = c
        context.lineCap = 'round'
        context.stroke()
      }

      context.restore()

      return false
    }

    const onDraw = () => {
      for (let i = 0; i < ribbons.length; i++) {
        if (!ribbons[i]) {
          ribbons.splice(i, 1)
          i--
        }
      }

      context.clearRect(0, 0, width, height)

      for (let i = 0; i < ribbons.length; i++) {
        const ribbon = ribbons[i]
        if (ribbon) {
          for (let j = 0; j < ribbon.length; j++) {
            if (drawRibbonSection(ribbon[j])) {
              ribbon.splice(j, 1)
              j--
            }
          }

          if (ribbon.length === 0) {
            // @ts-expect-error slot is tombstoned with null and compacted by the filter below
            ribbons[i] = null
          }
        }
      }

      if (ribbons.filter(Boolean).length < optionsRef.current.ribbonCount) {
        addRibbon()
      }

      if (optionsRef.current.paused) return false
    }
    drawRef.current = onDraw

    measureRef.current = ({ width: w, height: h }) => {
      width = w
      height = h
      canvas.width = w
      canvas.height = h
      context.globalAlpha = optionsRef.current.colorAlpha
    }

    const onScroll = () => {
      scroll = screenInfo().scrolly
    }

    window.addEventListener('scroll', onScroll)
    loop.resize()
    loop.start()

    return () => {
      drawRef.current = null
      measureRef.current = null
      window.removeEventListener('scroll', onScroll)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <div ref={containerRef} className="absolute inset-0">
      <canvas ref={canvasRef} className="absolute inset-0 block h-full w-full" />
    </div>
  )
}

export default Ribbons
```

### 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 |
| --- | --- | --- | --- |
| `color` | `string (hex)` | `"#0037ff"` | Ribbon color. |
| `colorAlpha` | `number` | `0.7` | Ribbon opacity. Range 0–1. |
| `ribbonCount` | `number` | `4` | Number of ribbons on screen. Range 1–12. |
| `strokeSize` | `number` | `1` | Outline thickness. Range 0–20 px. |
| `horizontalSpeed` | `number` | `200` | Drift speed across the canvas. Range 10–300. |
| `parallaxAmount` | `number` | `-0.2` | Scroll parallax factor. Range -1–1. |
| `verticalPosition` | `"top" | "middle" | "bottom" | "random"` | `"random"` | Where ribbons spawn vertically. |
| `animateSections` | `boolean` | `false` | Wiggle ribbon segments over time. |

## Usage

```tsx
import Ribbons from "@/components/registry/ribbons/ribbons";

<Ribbons
  color="#0037ff"
  colorAlpha={0.7}
  ribbonCount={4}
  strokeSize={1}
  horizontalSpeed={200}
  parallaxAmount={-0.2}
  verticalPosition="random"
  animateSections={false}
/>
```

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