# Integrate `Elastic` from Motion Garden

You are helping me add the **Elastic** 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:** Elastic
- **Category:** Power-User Systems
- **Summary:** Throw the top card and the speed you released it at carries into the spring — throw it far enough and it cycles to the back of the deck instead of coming home.
- **Reference:** https://motion-garden.netlify.app/components/elastic
- **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/elastic/elastic.tsx`

```tsx
"use client";

import { useEffect, useLayoutEffect, useState, type ReactNode } from "react";
import {
  animate,
  motion,
  useMotionValue,
  useTransform,
  type MotionValue,
  type PanInfo,
} from "motion/react";
import { cn } from "@/lib/utils";

const useIsomorphicLayoutEffect =
  typeof window === "undefined" ? useEffect : useLayoutEffect;

const PROJECTION = 0.16;

const FLIGHT = 0.6;

const slotOf = (depth: number) => ({
  scale: 1 - depth * 0.05,
  y: depth * 14,
  opacity: 1 - depth * 0.22,
});

type Flight = {
  item: number;
  fromX: number;
  fromY: number;
  outX: number;
  outY: number;
  tilt: number;
};

export interface ElasticProps {
  items?: ReactNode[];
  className?: string;
  stiffness?: number;
  damping?: number;
  mass?: number;
  bounds?: number;
  rubberBand?: number;
  flickPower?: number;
  cards?: number;
  throwThreshold?: number;
  reducedMotion?: boolean;
}

export default function Elastic({
  items = [],
  className,
  stiffness = 320,
  damping = 22,
  mass = 1,
  bounds = 140,
  rubberBand = 0.45,
  flickPower = 1,
  cards = 3,
  throwThreshold = 90,
  reducedMotion = false,
}: ElasticProps) {
  const x = useMotionValue(0);
  const y = useMotionValue(0);

  const [queue, setQueue] = useState<number[]>(() => items.map((_, i) => i));
  const [size, setSize] = useState(items.length);
  if (size !== items.length) {
    setSize(items.length);
    setQueue(items.map((_, i) => i));
  }

  const [flight, setFlight] = useState<Flight | null>(null);

  const rotate = useTransform(x, [-bounds, bounds], [-9, 9], { clamp: true });
  const trail = useTransform(x, [-bounds, bounds], [-10, 10], { clamp: true });

  const front = queue[0];

  useIsomorphicLayoutEffect(() => {
    x.jump(0);
    y.jump(0);
  }, [front, x, y]);

  const spring = reducedMotion
    ? { duration: 0.18, ease: [0.22, 1, 0.36, 1] as const }
    : { type: "spring" as const, stiffness, damping, mass };

  const settle = (info: PanInfo) => {
    const carry = (v: number) =>
      reducedMotion ? {} : { velocity: v * flickPower };
    animate(x, 0, { ...spring, ...carry(info.velocity.x) });
    animate(y, 0, { ...spring, ...carry(info.velocity.y) });
  };

  const visible = Math.max(1, Math.min(cards, queue.length));
  const last = slotOf(visible - 1);

  const release = (info: PanInfo) => {
    const dx = x.get() + info.velocity.x * PROJECTION;
    const dy = y.get() + info.velocity.y * PROJECTION;
    const reach = Math.hypot(dx, dy);
    const trigger = Math.min(throwThreshold, bounds * 0.9);

    if (queue.length < 2 || reach <= trigger) {
      settle(info);
      return;
    }

    const out = bounds + 200;
    if (!reducedMotion) {
      setFlight({
        item: front,
        fromX: x.get(),
        fromY: y.get(),
        outX: (dx / reach) * out,
        outY: (dy / reach) * out,
        tilt: rotate.get(),
      });
    }
    setQueue((q) => [...q.slice(1), q[0]]);
  };

  if (front === undefined) {
    return <div className={cn("relative", className)} />;
  }

  const behind = queue.slice(1, visible);

  return (
    <div
      className={cn(
        "relative flex select-none items-center justify-center",
        className,
      )}
    >
      {behind
        .map((item, i) => ({ item, depth: i + 1 }))
        .reverse()
        .map(({ item, depth }) => (
          <BackCard
            key={item}
            trail={trail}
            depth={depth}
            total={behind.length}
            still={reducedMotion}
            transition={spring}
          >
            {items[item]}
          </BackCard>
        ))}

      <motion.div
        key={front}
        className="relative z-10"
        initial={slotOf(1)}
        animate={slotOf(0)}
        transition={spring}
      >
        <motion.div
          drag
          dragConstraints={{
            left: -bounds,
            right: bounds,
            top: -bounds,
            bottom: bounds,
          }}
          dragElastic={rubberBand}
          dragMomentum={false}
          onDragEnd={(_, info) => release(info)}
          whileDrag={{ cursor: "grabbing" }}
          style={{ x, y, rotate: reducedMotion ? 0 : rotate }}
          className="cursor-grab touch-none will-change-transform"
        >
          {items[front]}
        </motion.div>
      </motion.div>

      {flight && (
        <motion.div
          key={`flight-${flight.item}`}
          aria-hidden
          className="pointer-events-none absolute z-20 will-change-transform"
          initial={{
            x: flight.fromX,
            y: flight.fromY,
            rotate: flight.tilt,
            scale: 1,
            opacity: 1,
          }}
          animate={{
            x: [flight.fromX, flight.outX, 0],
            y: [flight.fromY, flight.outY, last.y],
            rotate: [flight.tilt, flight.tilt * 1.5, 0],
            scale: [1, 1, last.scale],
            opacity: [1, 1, 0],
          }}
          transition={{ duration: FLIGHT, times: [0, 0.42, 1], ease: "easeInOut" }}
          onAnimationComplete={() => setFlight(null)}
        >
          {items[flight.item]}
        </motion.div>
      )}
    </div>
  );
}

function BackCard({
  children,
  trail,
  depth,
  total,
  still,
  transition,
}: {
  children: ReactNode;
  trail: MotionValue<number>;
  depth: number;
  total: number;
  still: boolean;
  transition: object;
}) {
  const factor = 1 - depth / (total + 1);
  const x = useTransform(trail, (t) => t * factor);
  const slot = slotOf(depth);

  return (
    <motion.div
      aria-hidden
      className="absolute will-change-transform"
      style={{ x: still ? 0 : x }}
      initial={{ ...slot, opacity: 0 }}
      animate={slot}
      transition={transition}
    >
      {children}
    </motion.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 |
| --- | --- | --- | --- |
| `stiffness` | `number` | `320` | How strongly the spring pulls home. Higher is snappier. Range 60–800. |
| `damping` | `number` | `22` | How fast it settles. Lower overshoots and oscillates. Range 5–60. |
| `mass` | `number` | `1` | How heavy the card feels. More mass is more sluggish. Range 0.2–4. |
| `bounds` | `number` | `140` | How far the card may travel from home. Range 40–400 px. |
| `rubberBand` | `number` | `0.45` | Give past the bounds, hard wall → loose. Range 0–1. |
| `flickPower` | `number` | `1` | Multiplier on the release velocity handed to the spring. Range 0.2–3 ×. |
| `cards` | `number` | `3` | How many cards in the stack. Range 1–5. |
| `throwThreshold` | `number` | `90` | Throw distance past which the card cycles to the back instead of springing home. Capped at 90% of bounds so it stays reachable. Range 20–260 px. |

## Usage

```tsx
import Elastic from "@/components/registry/elastic/elastic";

<Elastic
  stiffness={320}
  damping={22}
  mass={1}
  bounds={140}
  rubberBand={0.45}
  flickPower={1}
  cards={3}
  throwThreshold={90}
/>
```

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