# Integrate `MarqueeVelocity` from Motion Garden

You are helping me add the **MarqueeVelocity** 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:** MarqueeVelocity
- **Category:** Text Animations
- **Summary:** A wrapping marquee whose drift speed and direction follow scroll velocity — fast scrolls whip the row along, upward scrolls reverse it.
- **Reference:** https://motion-garden.netlify.app/components/marquee-velocity
- **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 motion clsx tailwind-merge
```

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

```tsx
"use client";

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
  type RefObject,
} from "react";
import {
  motion,
  useAnimationFrame,
  useMotionValue,
  useScroll,
  useSpring,
  useTransform,
  useVelocity,
} from "motion/react";
import { cn } from "@/lib/utils";

export interface VelocityMapping {
  input: [number, number];
  output: [number, number];
}

export interface MarqueeVelocityProps {
  children: ReactNode;
  velocity?: number;
  damping?: number;
  stiffness?: number;
  numCopies?: number;
  velocityMapping?: VelocityMapping;
  scrollContainerRef?: RefObject<HTMLElement | null>;
  reducedMotion?: boolean;
  className?: string;
  containerClassName?: string;
  style?: CSSProperties;
}

function useElementWidth(ref: RefObject<HTMLElement | null>): number {
  const [width, setWidth] = useState(0);
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    const update = () => setWidth(el.getBoundingClientRect().width);
    update();
    const observer = new ResizeObserver(update);
    observer.observe(el);
    return () => observer.disconnect();
  }, [ref]);
  return width;
}

const DIRECTION_DEADZONE = 1;

function wrap(min: number, max: number, v: number): number {
  const range = max - min;
  return ((((v - min) % range) + range) % range) + min;
}

export default function MarqueeVelocity({
  children,
  velocity = 50,
  damping = 50,
  stiffness = 400,
  numCopies = 6,
  velocityMapping = { input: [0, 1000], output: [0, 5] },
  scrollContainerRef,
  reducedMotion = false,
  className,
  containerClassName,
  style,
}: MarqueeVelocityProps) {
  const [osReduced, setOsReduced] = useState(false);

  useEffect(() => {
    const query = window.matchMedia("(prefers-reduced-motion: reduce)");
    setOsReduced(query.matches);
    const onChange = (e: MediaQueryListEvent) => setOsReduced(e.matches);
    query.addEventListener("change", onChange);
    return () => query.removeEventListener("change", onChange);
  }, []);

  const reduce = osReduced || reducedMotion;

  const baseX = useMotionValue(0);
  const { scrollY } = useScroll(
    scrollContainerRef ? { container: scrollContainerRef } : {},
  );
  const scrollVelocity = useVelocity(scrollY);
  const smoothVelocity = useSpring(scrollVelocity, { damping, stiffness });
  const velocityFactor = useTransform(
    smoothVelocity,
    velocityMapping.input,
    velocityMapping.output,
    { clamp: false },
  );

  const wrapperRef = useRef<HTMLDivElement>(null);
  const wrapperWidth = useElementWidth(wrapperRef);
  const copyRef = useRef<HTMLSpanElement>(null);
  const copyWidth = useElementWidth(copyRef);

  const effectiveCopies =
    copyWidth > 0 && wrapperWidth > 0
      ? Math.max(numCopies, Math.ceil(wrapperWidth / copyWidth) + 2)
      : numCopies;

  const x = useTransform(baseX, (v) =>
    copyWidth === 0 ? "0px" : `${wrap(-copyWidth, 0, v)}px`,
  );

  const directionFactor = useRef(1);
  useAnimationFrame((_, delta) => {
    if (reduce) return;
    const raw = scrollVelocity.get();
    if (raw > DIRECTION_DEADZONE) directionFactor.current = 1;
    else if (raw < -DIRECTION_DEADZONE) directionFactor.current = -1;
    const boost = 1 + Math.abs(velocityFactor.get());
    const step = directionFactor.current * velocity * (delta / 1000) * boost;
    baseX.set(baseX.get() + step);
  });

  const copies = [];
  for (let i = 0; i < effectiveCopies; i++) {
    copies.push(
      <span
        key={i}
        ref={i === 0 ? copyRef : null}
        className="flex shrink-0 items-center"
      >
        {children}
      </span>,
    );
  }

  return (
    <div
      ref={wrapperRef}
      className={cn("relative overflow-hidden", containerClassName)}
      style={style}
    >
      <motion.div
        className={cn("flex items-center whitespace-nowrap", className)}
        style={{ x }}
      >
        {copies}
      </motion.div>
    </div>
  );
}
```

### 2. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `velocity` | `number` | `50` | Resting drift before scroll multiplies it. Positive moves the row right, negative moves it left, 0 leaves it still until you scroll. Range -200–200 px/s. |
| `damping` | `number` | `50` | Friction on the velocity spring. Low overshoots and rebounds once the scroll stops; high settles dead. Range 10–100. |
| `stiffness` | `number` | `400` | How hard the spring chases the current scroll speed. High tracks it instantly; low lags and keeps coasting, which reads as weight. Range 100–800. |
| `numCopies` | `number` | `6` | Minimum copies tiled into the loop. A floor, not a count — narrow content gets more so the wrap never sweeps a gap through. Range 2–12. |

## Usage

```tsx
import MarqueeVelocity from "@/components/registry/marquee-velocity/marquee-velocity";

<MarqueeVelocity
  velocity={50}
  damping={50}
  stiffness={400}
  numCopies={6}
/>
```

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`.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.

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