# Integrate `Reorder` from Motion Garden

You are helping me add the **Reorder** 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:** Reorder
- **Category:** Micro-interactions
- **Summary:** A sortable list that answers to a finger and to a keyboard equally. Grab a row, and the rest step aside to make the space.
- **Reference:** https://motion-garden.netlify.app/components/reorder
- **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
```

## 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;
}

@theme inline {
  --color-panel: var(--sg-panel);
  --color-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-panel: #101215;
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
}
```

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

```tsx
"use client";

import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import { Reorder as MotionReorder, useDragControls } from "motion/react";
import { cn } from "@/lib/utils";

export interface ReorderItemData {
  id: string;
  label: string;
  meta?: string;
}

export interface ReorderProps {
  items?: ReorderItemData[];
  onReorder?: (next: ReorderItemData[]) => void;
  axis?: "y" | "x";
  stiffness?: number;
  damping?: number;
  handle?: boolean;
  lift?: number;
  liftShadow?: number;
  gap?: number;
  radius?: number;
  density?: "comfortable" | "compact";
  showIndex?: boolean;
  accentColor?: string;
  reducedMotion?: boolean;
  className?: string;
}

const move = <T,>(list: T[], from: number, to: number): T[] => {
  const next = list.slice();
  const [row] = next.splice(from, 1);
  next.splice(to, 0, row);
  return next;
};

export default function Reorder({
  items = [],
  onReorder,
  axis = "y",
  stiffness = 520,
  damping = 38,
  handle = true,
  lift = 1.03,
  liftShadow = 0.35,
  gap = 8,
  radius = 8,
  density = "comfortable",
  showIndex = true,
  accentColor = "#a855f7",
  reducedMotion = false,
  className,
}: ReorderProps) {
  const [grabbed, setGrabbed] = useState<string | null>(null);
  const originRef = useRef<ReorderItemData[] | null>(null);
  const [message, setMessage] = useState("");

  const [roving, setRoving] = useState(0);
  const focusWanted = useRef<string | null>(null);
  const gripRefs = useRef(new Map<string, HTMLButtonElement>());

  const index = (id: string) => items.findIndex((item) => item.id === id);

  useEffect(() => {
    const id = focusWanted.current;
    if (!id) return;
    focusWanted.current = null;
    gripRefs.current.get(id)?.focus({ preventScroll: true });
  }, [items]);

  const commit = (next: ReorderItemData[], id: string) => {
    focusWanted.current = id;
    setRoving(next.findIndex((item) => item.id === id));
    onReorder?.(next);
  };

  const step = (id: string, delta: number) => {
    const from = index(id);
    const to = Math.min(items.length - 1, Math.max(0, from + delta));
    if (from < 0 || to === from) return;
    commit(move(items, from, to), id);
    setMessage(`Moved to position ${to + 1} of ${items.length}`);
  };

  const jump = (id: string, edge: "start" | "end") => {
    const from = index(id);
    const to = edge === "start" ? 0 : items.length - 1;
    if (from < 0 || to === from) return;
    commit(move(items, from, to), id);
    setMessage(`Moved to position ${to + 1} of ${items.length}`);
  };

  const grab = (id: string) => {
    originRef.current = items;
    setGrabbed(id);
    setMessage(`${label(items, id)}, grabbed. Position ${index(id) + 1} of ${items.length}.`);
  };

  const drop = (id: string) => {
    originRef.current = null;
    setGrabbed(null);
    setMessage(`Dropped at position ${index(id) + 1} of ${items.length}`);
  };

  const cancel = (id: string) => {
    const origin = originRef.current;
    originRef.current = null;
    setGrabbed(null);
    if (origin) {
      const back = origin.findIndex((item) => item.id === id);
      commit(origin, id);
      setMessage(`Cancelled, returned to position ${back + 1} of ${items.length}`);
      return;
    }
    setMessage("Cancelled");
  };

  const [prevKey, nextKey] =
    axis === "y" ? ["ArrowUp", "ArrowDown"] : ["ArrowLeft", "ArrowRight"];

  const onKeyDown = (event: KeyboardEvent, id: string) => {
    const held = grabbed === id;

    if (event.key === " " || event.key === "Enter") {
      event.preventDefault();
      if (held) drop(id);
      else grab(id);
      return;
    }
    if (event.key === "Escape" && held) {
      event.preventDefault();
      cancel(id);
      return;
    }
    if (event.key === "Tab" && held) {
      event.preventDefault();
      return;
    }
    if (event.key === prevKey || event.key === nextKey) {
      event.preventDefault();
      const delta = event.key === nextKey ? 1 : -1;
      if (held) {
        step(id, delta);
        return;
      }
      const to = Math.min(items.length - 1, Math.max(0, index(id) + delta));
      setRoving(to);
      gripRefs.current.get(items[to]?.id ?? "")?.focus({ preventScroll: true });
      return;
    }
    if (event.key === "Home" || event.key === "End") {
      event.preventDefault();
      const edge = event.key === "Home" ? "start" : "end";
      if (held) {
        jump(id, edge);
        return;
      }
      const to = edge === "start" ? 0 : items.length - 1;
      setRoving(to);
      gripRefs.current.get(items[to]?.id ?? "")?.focus({ preventScroll: true });
    }
  };

  return (
    <div className={cn("w-full", className)}>
      <MotionReorder.Group
        axis={axis}
        values={items}
        onReorder={(next: ReorderItemData[]) => onReorder?.(next)}
        className={cn("flex list-none", axis === "y" ? "flex-col" : "flex-row")}
        style={{ gap }}
      >
        {items.map((item, i) => (
          <Row
            key={item.id}
            item={item}
            position={i}
            total={items.length}
            axis={axis}
            stiffness={stiffness}
            damping={damping}
            handle={handle}
            lift={lift}
            liftShadow={liftShadow}
            radius={radius}
            density={density}
            showIndex={showIndex}
            accentColor={accentColor}
            reducedMotion={reducedMotion}
            grabbed={grabbed === item.id}
            tabbable={roving === i || (roving >= items.length && i === 0)}
            registerGrip={(node) => {
              if (node) gripRefs.current.set(item.id, node);
              else gripRefs.current.delete(item.id);
            }}
            onGripFocus={() => setRoving(i)}
            onKeyDown={(event) => onKeyDown(event, item.id)}
          />
        ))}
      </MotionReorder.Group>

      <p aria-live="assertive" aria-atomic className="sr-only">
        {message}
      </p>
    </div>
  );
}

function label(items: ReorderItemData[], id: string): string {
  return items.find((item) => item.id === id)?.label ?? "Row";
}

function Row({
  item,
  position,
  total,
  axis,
  stiffness,
  damping,
  handle,
  lift,
  liftShadow,
  radius,
  density,
  showIndex,
  accentColor,
  reducedMotion,
  grabbed,
  tabbable,
  registerGrip,
  onGripFocus,
  onKeyDown,
}: {
  item: ReorderItemData;
  position: number;
  total: number;
  axis: "y" | "x";
  stiffness: number;
  damping: number;
  handle: boolean;
  lift: number;
  liftShadow: number;
  radius: number;
  density: "comfortable" | "compact";
  showIndex: boolean;
  accentColor: string;
  reducedMotion: boolean;
  grabbed: boolean;
  tabbable: boolean;
  registerGrip: (node: HTMLButtonElement | null) => void;
  onGripFocus: () => void;
  onKeyDown: (event: KeyboardEvent) => void;
}) {
  const controls = useDragControls();

  return (
    <MotionReorder.Item
      value={item}
      layout="position"
      dragListener={!handle}
      dragControls={controls}
      transition={
        reducedMotion
          ? { duration: 0 }
          : { type: "spring", stiffness, damping }
      }
      whileDrag={
        reducedMotion
          ? undefined
          : {
              scale: lift,
              boxShadow: `0 ${Math.round(liftShadow * 26)}px ${Math.round(liftShadow * 44)}px rgb(0 0 0 / ${liftShadow})`,
            }
      }
      className={cn(
        "flex items-center gap-3 border border-hairline bg-panel select-none",
        density === "compact" ? "px-3 py-2" : "px-4 py-3",
        axis === "x" && "min-w-0 flex-1",
        !handle && "cursor-grab active:cursor-grabbing",
      )}
      style={{
        borderRadius: radius,
        outline: grabbed ? `2px solid ${accentColor}` : undefined,
        outlineOffset: 2,
      }}
    >
      <button
        ref={registerGrip}
        type="button"
        className="touch-none grid size-7 shrink-0 cursor-grab place-items-center rounded-md border border-hairline text-ink-mute transition-colors outline-none hover:bg-raised hover:text-ink focus-visible:ring-2 focus-visible:ring-accent active:cursor-grabbing"
        style={grabbed ? { color: accentColor, borderColor: accentColor } : undefined}
        aria-roledescription="sortable"
        aria-pressed={grabbed}
        aria-label={`Reorder ${item.label}. Position ${position + 1} of ${total}. Press space to pick up.`}
        tabIndex={tabbable ? 0 : -1}
        onFocus={onGripFocus}
        onKeyDown={onKeyDown}
        onPointerDown={(event) => {
          if (handle) controls.start(event);
        }}
      >
        <svg viewBox="0 0 24 24" className="size-3.5" aria-hidden>
          <path
            d="M9 6h.01M15 6h.01M9 12h.01M15 12h.01M9 18h.01M15 18h.01"
            fill="none"
            stroke="currentColor"
            strokeWidth="3"
            strokeLinecap="round"
          />
        </svg>
      </button>

      {showIndex ? (
        <span className="w-5 shrink-0 text-right font-display text-[11px] tabular-nums text-ink-mute">
          {position + 1}
        </span>
      ) : null}

      <span className="min-w-0 flex-1">
        <span className="block truncate font-display text-[12px] tracking-[0.12em] text-ink uppercase">
          {item.label}
        </span>
        {item.meta ? (
          <span className="mt-0.5 block truncate font-sans text-[12px] text-ink-mute">
            {item.meta}
          </span>
        ) : null}
      </span>
    </MotionReorder.Item>
  );
}
```

### 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 |
| --- | --- | --- | --- |
| `axis` | `"y" | "x"` | `"y"` | Which way the list runs, and which arrow keys move a row. |
| `stiffness` | `number` | `520` | Spring tension as the displaced rows close up. This is the only motion in the component that is not under your finger, so it is the one that decides whether the list feels attached to the drag. Range 120–900. |
| `damping` | `number` | `38` | Spring friction on the same. Range 8–60. |
| `handle` | `boolean` | `true` | Restrict the drag to the grip. Off makes the whole row the surface, which is quicker to hit and costs you text selection and a scroll gesture that starts on a row. |
| `lift` | `number` | `1.03` | Scale of a row while it is off the ground. Past about 1.06 the row stops reading as lifted and starts reading as a different row. Range 1–1.15. |
| `liftShadow` | `number` | `0.35` | Shadow cast under a lifted row. Range 0–1. |
| `gap` | `number` | `8` | Space between rows. Range 0–24 px. |
| `radius` | `number` | `8` | Row corner radius. Range 0–20 px. |
| `density` | `"comfortable" | "compact"` | `"comfortable"` | Row padding. |
| `showIndex` | `boolean` | `true` | Print the position of each row. Worth leaving on wherever the order is the data rather than a preference — it is the only on-screen confirmation that a keyboard move landed where the announcement said it did. |
| `accentColor` | `string (hex)` | `"#a855f7"` | Grip tint, and the outline on a row the keyboard is carrying. A pointer drag shows itself by moving; a keyboard grab has to be drawn. |

## Usage

```tsx
import Reorder from "@/components/registry/reorder/reorder";

<Reorder
  axis="y"
  stiffness={520}
  damping={38}
  handle={true}
  lift={1.03}
  liftShadow={0.35}
  gap={8}
  radius={8}
  density="comfortable"
  showIndex={true}
  accentColor="#a855f7"
/>
```

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