# Integrate `RadialMenu` from Motion Garden

You are helping me add the **RadialMenu** 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:** RadialMenu
- **Category:** Micro-interactions
- **Summary:** Press and hold anywhere and the options fan out from the point you pressed. Selection is resolved from the pointer's angle rather than by hit-testing the options, so every target is an infinite wedge — commit to a direction and you can throw the pointer as hard as you like and still land it.
- **Reference:** https://motion-garden.netlify.app/components/radial-menu
- **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-surface: var(--sg-surface);
  --color-panel: var(--sg-panel);
  --color-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink-dim: var(--sg-ink-dim);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-surface: #f9f9fb;
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink-dim: #545b64;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-surface: #0a0b0c;
  --sg-panel: #101215;
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink-dim: #bcc2c8;
  --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/radial-menu/radial-menu.tsx`

```tsx
"use client";

import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type ReactNode,
} from "react";
import { AnimatePresence, motion } from "motion/react";
import { cn } from "@/lib/utils";

export interface RadialMenuItem {
  key: string;
  label: string;
  icon?: ReactNode;
  onSelect?: () => void;
}

export interface RadialMenuProps {
  items?: RadialMenuItem[];
  children?: ReactNode;
  className?: string;
  radius?: number;
  startAngle?: number;
  sweep?: number;
  itemCount?: number;
  holdDelay?: number;
  stagger?: number;
  stiffness?: number;
  damping?: number;
  centerCancel?: number;
  accent?: string;
  reducedMotion?: boolean;
}

const TO_RAD = Math.PI / 180;

const OPTION_SIZE = 44;

function angleDelta(a: number, b: number): number {
  return ((((a - b) % 360) + 540) % 360) - 180;
}

export default function RadialMenu({
  items = [],
  children,
  className,
  radius = 96,
  startAngle = 180,
  sweep = 180,
  itemCount = 6,
  holdDelay = 220,
  stagger = 0.03,
  stiffness = 380,
  damping = 26,
  centerCancel = 28,
  accent = "#a855f7",
  reducedMotion = false,
}: RadialMenuProps) {
  const surface = useRef<HTMLDivElement>(null);
  const holdTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const [origin, setOrigin] = useState<{ x: number; y: number } | null>(null);
  const [hot, setHot] = useState<number | null>(null);

  const visible = items.slice(0, Math.max(1, itemCount));
  const count = visible.length;

  const step = sweep >= 359 ? sweep / count : sweep / Math.max(1, count - 1);

  const angleOf = useCallback(
    (index: number) => startAngle + step * index,
    [startAngle, step],
  );

  const clearHold = useCallback(() => {
    if (holdTimer.current !== null) {
      clearTimeout(holdTimer.current);
      holdTimer.current = null;
    }
  }, []);

  useEffect(() => clearHold, [clearHold]);

  const close = useCallback(() => {
    clearHold();
    setOrigin(null);
    setHot(null);
  }, [clearHold]);

  const commit = useCallback(
    (index: number | null) => {
      if (index !== null) visible[index]?.onSelect?.();
      close();
    },
    [visible, close],
  );

  const resolve = useCallback(
    (dx: number, dy: number): number | null => {
      if (Math.hypot(dx, dy) < centerCancel) return null;
      const pointing = Math.atan2(dy, dx) / TO_RAD;

      let best: number | null = null;
      let bestDelta = Infinity;
      for (let index = 0; index < count; index++) {
        const delta = Math.abs(angleDelta(pointing, angleOf(index)));
        if (delta < bestDelta) {
          bestDelta = delta;
          best = index;
        }
      }
      return best !== null && bestDelta <= step ? best : null;
    },
    [angleOf, centerCancel, count, step],
  );

  const localPoint = (event: { clientX: number; clientY: number }) => {
    const rect = surface.current?.getBoundingClientRect();
    if (!rect) return null;
    return { x: event.clientX - rect.left, y: event.clientY - rect.top };
  };

  return (
    <div
      ref={surface}
      tabIndex={0}
      role="button"
      aria-haspopup="menu"
      aria-expanded={origin !== null}
      className={cn(
        "relative touch-none overflow-hidden rounded-2xl border border-hairline bg-panel outline-none select-none",
        "focus-visible:border-accent",
        className,
      )}
      onPointerDown={(event) => {
        if (event.button !== 0 && event.pointerType === "mouse") return;
        const point = localPoint(event);
        if (!point) return;
        event.currentTarget.setPointerCapture(event.pointerId);
        clearHold();
        holdTimer.current = setTimeout(() => {
          holdTimer.current = null;
          setOrigin(point);
          setHot(null);
        }, holdDelay);
      }}
      onPointerMove={(event) => {
        if (!origin) return;
        const point = localPoint(event);
        if (!point) return;
        setHot(resolve(point.x - origin.x, point.y - origin.y));
      }}
      onPointerUp={() => {
        if (holdTimer.current !== null) {
          clearHold();
          return;
        }
        if (origin) commit(hot);
      }}
      onPointerCancel={close}
      onKeyDown={(event) => {
        if (event.key === "Escape") {
          close();
          return;
        }
        const commitKey = event.key === "Enter" || event.key === " ";
        if (!origin) {
          if (!commitKey) return;
          event.preventDefault();
          const rect = surface.current?.getBoundingClientRect();
          if (!rect) return;
          setOrigin({ x: rect.width / 2, y: rect.height / 2 });
          setHot(0);
          return;
        }
        if (commitKey) {
          event.preventDefault();
          commit(hot);
          return;
        }
        const forward = event.key === "ArrowRight" || event.key === "ArrowDown";
        const back = event.key === "ArrowLeft" || event.key === "ArrowUp";
        if (!forward && !back) return;
        event.preventDefault();
        setHot((current) => {
          const from = current ?? 0;
          return (from + (forward ? 1 : -1) + count) % count;
        });
      }}
    >
      {children}

      <AnimatePresence>
        {origin ? (
          <motion.div
            key="fan"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: reducedMotion ? 0 : 0.12 }}
            className="absolute inset-0 z-10 bg-surface/50 backdrop-blur-[2px]"
          >
            <span
              aria-hidden
              className="absolute rounded-full border border-dashed border-hairline"
              style={{
                left: origin.x - centerCancel,
                top: origin.y - centerCancel,
                width: centerCancel * 2,
                height: centerCancel * 2,
              }}
            />

            <div
              role="menu"
              aria-orientation="horizontal"
              className="absolute"
              style={{ left: origin.x, top: origin.y }}
            >
              {visible.map((item, index) => {
                const radians = angleOf(index) * TO_RAD;
                const active = hot === index;
                return (
                  <motion.button
                    key={item.key}
                    type="button"
                    role="menuitem"
                    tabIndex={-1}
                    aria-label={item.label}
                    aria-current={active ? "true" : undefined}
                    initial={{ x: 0, y: 0, scale: 0.3, opacity: 0 }}
                    animate={{
                      x: Math.cos(radians) * radius,
                      y: Math.sin(radians) * radius,
                      scale: active ? 1.18 : 1,
                      opacity: 1,
                    }}
                    exit={{ x: 0, y: 0, scale: 0.3, opacity: 0 }}
                    transition={
                      reducedMotion
                        ? { duration: 0 }
                        : {
                            type: "spring",
                            stiffness,
                            damping,
                            delay: index * stagger,
                          }
                    }
                    style={{
                      width: OPTION_SIZE,
                      height: OPTION_SIZE,
                      marginLeft: -OPTION_SIZE / 2,
                      marginTop: -OPTION_SIZE / 2,
                      borderColor: active ? accent : undefined,
                      color: active ? accent : undefined,
                    }}
                    className={cn(
                      "absolute flex items-center justify-center rounded-full border bg-raised text-ink-dim",
                      "[&_svg]:h-4 [&_svg]:w-4",
                      active ? "shadow-lg" : "border-hairline",
                    )}
                  >
                    {item.icon ?? (
                      <span className="font-display text-xs leading-none">
                        {item.label.charAt(0)}
                      </span>
                    )}
                  </motion.button>
                );
              })}
            </div>

            <span
              aria-live="polite"
              className="absolute -translate-x-1/2 -translate-y-1/2 font-display text-[10px] tracking-[0.2em] uppercase"
              style={{
                left: origin.x,
                top: origin.y,
                color: hot === null ? undefined : accent,
              }}
            >
              {hot === null ? "" : visible[hot]?.label}
            </span>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </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 |
| --- | --- | --- | --- |
| `radius` | `number` | `96` | How far the options sit from the press point. Only the drawing distance — selection is angular, so a wide radius costs nothing in accuracy and a tight one buys none. Range 48–200 px. |
| `startAngle` | `number` | `180` | Where the first option lands. 0 is right and 90 is down, following screen coordinates rather than the maths convention — the y axis on a page points the other way and pretending otherwise makes every later value read backwards. Range 0–359 °. |
| `sweep` | `number` | `180` | Total arc the options are spread across. At a full turn the last option would land on the first, so the spacing switches from end-to-end to evenly-around at 360 — the one place this component has two layout rules. Range 60–360 °. |
| `itemCount` | `number` | `6` | How many options to show. Past about seven the wedges get narrower than the flick they are meant to catch, which is the point at which a list would serve you better. Range 2–7. |
| `holdDelay` | `number` | `220` | How long the press has to be held before the fan opens. Releasing sooner is treated as a plain click on whatever is underneath, so the surface stays usable for its normal purpose. At 0 the menu opens on contact and that normal purpose is gone. Range 0–800 ms. |
| `stagger` | `number` | `0.03` | Delay between one option arriving and the next. Small values read as the fan unrolling; large ones make you wait for the option you already know you want. Range 0–0.12 s. |
| `stiffness` | `number` | `380` | How hard the options spring out to their positions. Range 100–900. |
| `damping` | `number` | `26` | How fast that spring settles. Low values overshoot the arc and snap back, which reads as the options being flung rather than placed. Range 8–60. |
| `centerCancel` | `number` | `28` | Radius of the dead zone around the press point. Release inside it and nothing commits. At 0 a press that never really moved still resolves to whichever option is nearest the jitter, and the menu picks something you never chose. Range 0–80 px. |
| `accent` | `string (hex)` | `"#a855f7"` | Highlight on the option the pointer is aimed at, and on the label echoing it back at the centre. |

## Usage

```tsx
import RadialMenu from "@/components/registry/radial-menu/radial-menu";

<RadialMenu
  radius={96}
  startAngle={180}
  sweep={180}
  itemCount={6}
  holdDelay={220}
  stagger={0.03}
  stiffness={380}
  damping={26}
  centerCancel={28}
  accent="#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.
