# Integrate `Segmented` from Motion Garden

You are helping me add the **Segmented** 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:** Segmented
- **Category:** Micro-interactions
- **Summary:** A segmented control whose indicator travels on a shared layout id and smears in the direction it is moving.
- **Reference:** https://motion-garden.netlify.app/components/segmented
- **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-dim: var(--sg-ink-dim);
  --color-accent: var(--sg-accent);
}

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

.dark {
  --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/segmented/segmented.tsx`

```tsx
"use client";

import { useEffect, useId, useRef, useState } from "react";
import {
  motion,
  useMotionValue,
  useSpring,
  useTransform,
  useVelocity,
} from "motion/react";
import { cn } from "@/lib/utils";

export type SegmentedIndicator = "solid" | "outline" | "underline";
export type SegmentedSizing = "auto" | "equal";
export type SegmentedDensity = "comfortable" | "compact";

export interface SegmentedItem {
  id: string;
  label: string;
}

export interface SegmentedProps {
  items?: SegmentedItem[];
  value?: string;
  defaultValue?: string;
  onValueChange?: (id: string) => void;
  indicator?: SegmentedIndicator;
  sizing?: SegmentedSizing;
  density?: SegmentedDensity;
  radius?: number;
  stiffness?: number;
  damping?: number;
  smear?: number;
  glow?: boolean;
  accentColor?: string;
  reducedMotion?: boolean;
  "aria-label"?: string;
  className?: string;
}

const SPEED_REF = 5.5;

export default function Segmented({
  items = [],
  value,
  defaultValue,
  onValueChange,
  indicator = "solid",
  sizing = "auto",
  density = "comfortable",
  radius = 8,
  stiffness = 520,
  damping = 34,
  smear = 0.5,
  glow = true,
  accentColor = "#a855f7",
  reducedMotion = false,
  "aria-label": ariaLabel = "View",
  className,
}: SegmentedProps) {
  const uid = useId();
  const [self, setSelf] = useState(defaultValue ?? items[0]?.id ?? "");
  const controlled = value !== undefined;
  const active = controlled ? value : self;
  const activeIndex = Math.max(
    0,
    items.findIndex((item) => item.id === active),
  );

  const compact = density === "compact";
  const bar = indicator === "underline";

  const position = useMotionValue(activeIndex);
  const settled = useSpring(position, { stiffness, damping });
  const velocity = useVelocity(settled);

  useEffect(() => {
    position.set(activeIndex);
  }, [activeIndex, position]);

  const stretch = useTransform(velocity, (v: number) =>
    reducedMotion ? 0 : Math.min(1, Math.abs(v) / SPEED_REF),
  );
  const scaleX = useTransform(stretch, (s: number) => 1 + smear * s * 0.35);
  const scaleY = useTransform(stretch, (s: number) => 1 - smear * s * 0.22);
  const originX = useTransform(velocity, (v: number) => (v > 0 ? 1 : 0));

  const listRef = useRef<HTMLDivElement>(null);

  const select = (id: string) => {
    if (!controlled) setSelf(id);
    onValueChange?.(id);
  };

  const onKeyDown = (event: React.KeyboardEvent) => {
    if (event.key !== "Home" && event.key !== "End") return;
    const next = event.key === "Home" ? items[0] : items[items.length - 1];
    if (!next) return;
    event.preventDefault();
    select(next.id);
    listRef.current
      ?.querySelectorAll<HTMLInputElement>('input[type="radio"]')
      ?.[event.key === "Home" ? 0 : items.length - 1]?.focus();
  };

  const layoutTransition = reducedMotion
    ? { duration: 0 }
    : { type: "spring" as const, stiffness, damping };

  return (
    <div
      ref={listRef}
      role="radiogroup"
      aria-label={ariaLabel}
      onKeyDown={onKeyDown}
      className={cn(
        "inline-flex select-none items-stretch border border-hairline bg-panel",
        compact ? "gap-0.5 p-0.5" : "gap-1 p-1",
        sizing === "equal" && "w-full",
        className,
      )}
      style={{ borderRadius: radius + (compact ? 2 : 4) }}
    >
      {items.map((item) => {
        const on = item.id === active;
        return (
          <label
            key={item.id}
            className={cn(
              "relative flex cursor-pointer items-center justify-center transition-colors",
              compact ? "px-2.5 py-1" : "px-3.5 py-1.5",
              sizing === "equal" ? "flex-1 basis-0" : "flex-none",
              !on && "hover:bg-raised/70",
            )}
            style={{ borderRadius: radius }}
          >
            <input
              type="radio"
              name={uid}
              value={item.id}
              checked={on}
              onChange={() => select(item.id)}
              className="peer absolute inset-0 size-full cursor-pointer opacity-0"
            />

            <span
              aria-hidden
              className="pointer-events-none absolute inset-0 peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-accent"
              style={{ borderRadius: radius }}
            />

            {on ? (
              <motion.span
                aria-hidden
                layoutId={`${uid}-indicator`}
                transition={layoutTransition}
                className={cn(
                  "pointer-events-none absolute",
                  bar ? "inset-x-1.5 bottom-0 h-[2px]" : "inset-0",
                )}
                style={{ borderRadius: bar ? 2 : radius }}
              >
                {glow ? (
                  <span
                    className="absolute -inset-1 rounded-[inherit] blur-md"
                    style={{ backgroundColor: accentColor, opacity: 0.28 }}
                  />
                ) : null}
                <motion.span
                  className="absolute inset-0 block rounded-[inherit]"
                  style={{
                    scaleX,
                    scaleY,
                    originX,
                    backgroundColor:
                      indicator === "outline"
                        ? `${accentColor}1f`
                        : accentColor,
                    border:
                      indicator === "outline"
                        ? `1.5px solid ${accentColor}`
                        : undefined,
                  }}
                />
              </motion.span>
            ) : null}

            <span
              className={cn(
                "relative z-10 font-display tracking-[0.12em] uppercase",
                compact ? "text-[10px]" : "text-[11px]",
                "transition-colors duration-200 [transition-delay:90ms]",
                on && indicator === "solid"
                  ? "text-on-accent"
                  : on
                    ? "text-accent"
                    : "text-ink-dim",
              )}
            >
              {item.label}
            </span>
          </label>
        );
      })}
    </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 |
| --- | --- | --- | --- |
| `indicator` | `"solid" | "outline" | "underline"` | `"solid"` | How the active segment is marked. All three are the same travelling element at different settings — the shared layout id does not change, so switching between them costs no extra animation code. |
| `sizing` | `"auto" | "equal"` | `"auto"` | Auto sizes each segment to its label, so the indicator resizes as well as travels — the half of the FLIP that equal-width tabs never show. Equal splits the row evenly and fills the container. |
| `density` | `"comfortable" | "compact"` | `"comfortable"` | Padding and type size. Compact is the toolbar setting; it shortens the travel too, which is why the smear reads more subtly there. |
| `radius` | `number` | `8` | Corner radius of the indicator and the segments. motion corrects the radius through the layout animation, so a rounded indicator does not go oval while it is resizing. Range 0–20 px. |
| `stiffness` | `number` | `520` | Spring tension on the travel. It also drives the proxy spring the deformation is read from, so the smear stays in phase with the movement at every setting rather than at the one it was tuned on. Range 120–900. |
| `damping` | `number` | `34` | Spring friction. Low lets the indicator ring past the segment and come back, which the smear follows in both directions; high arrives dead and barely deforms at all. Range 8–60. |
| `smear` | `number` | `0.5` | How hard the travel deforms the indicator. The stretch is along the direction of movement and anchored at the leading edge, so it trails behind rather than running ahead. Zero is a rigid box that slides. Range 0–1. |
| `glow` | `boolean` | `true` | Accent bloom under the indicator. It travels with the box and takes the same deformation, so it reads as light coming off the thing rather than a separate shape following it. |
| `accentColor` | `string (hex)` | `"#a855f7"` | The indicator, its bloom, and the label of the active segment when the indicator is not filling it. |

## Usage

```tsx
import Segmented from "@/components/registry/segmented/segmented";

<Segmented
  indicator="solid"
  sizing="auto"
  density="comfortable"
  radius={8}
  stiffness={520}
  damping={34}
  smear={0.5}
  glow={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`.
- `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.
