# Integrate `GrowDialog` from Motion Garden

You are helping me add the **GrowDialog** 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:** GrowDialog
- **Category:** Micro-interactions
- **Summary:** A dialog that grows out of the clicked element and shrinks back into it, entirely inside a portal — never behind page content.
- **Reference:** https://motion-garden.netlify.app/components/grow-dialog
- **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 lucide-react 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-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
}

:root {
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
}

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

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

```tsx
"use client";

import {
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
} from "react";
import {
  AnimatePresence,
  MotionConfig,
  motion,
  useReducedMotion,
  type Transition,
} from "motion/react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";

const FOCUSABLE_SELECTOR =
  'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';

export interface GrowPanelProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  originRect?: DOMRect | null;
  originMaxWidth?: number;
  stiffness?: number;
  damping?: number;
  radius?: number;
  blurBackdrop?: boolean;
  autoFocus?: boolean;
  backdropClassName?: string;
  style?: CSSProperties;
  onAnimationComplete?: () => void;
  className?: string;
  children: ReactNode;
  reducedMotion?: boolean;
  role?: "dialog" | "alertdialog";
  "aria-label"?: string;
  "aria-describedby"?: string;
}

export function GrowPanel({
  open,
  onOpenChange,
  originRect,
  originMaxWidth,
  stiffness = 320,
  damping = 34,
  radius = 16,
  blurBackdrop = true,
  autoFocus = true,
  backdropClassName,
  style,
  onAnimationComplete,
  className,
  children,
  reducedMotion = false,
  role = "dialog",
  "aria-label": ariaLabel,
  "aria-describedby": ariaDescribedby,
}: GrowPanelProps) {
  const [mounted, setMounted] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const openerRef = useRef<HTMLElement | null>(null);

  useEffect(() => {
    setMounted(true);
    return () => setMounted(false);
  }, []);

  useEffect(() => {
    if (open) openerRef.current = document.activeElement as HTMLElement | null;
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        const dialogs = document.querySelectorAll(
          '[role="dialog"][aria-modal="true"]',
        );
        if (Array.from(dialogs).some((node) => node !== containerRef.current)) {
          return;
        }
        event.preventDefault();
        onOpenChange(false);
        return;
      }
      if (event.key !== "Tab") return;
      const focusables =
        containerRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);
      if (!focusables || focusables.length === 0) return;
      const first = focusables[0];
      const last = focusables[focusables.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [open, onOpenChange]);

  useEffect(() => {
    if (!open) return;
    document.body.classList.add("overflow-hidden");
    if (autoFocus) {
      containerRef.current
        ?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)?.[0]
        ?.focus();
    }
    return () => document.body.classList.remove("overflow-hidden");
  }, [open, autoFocus]);

  useEffect(() => {
    if (!open) openerRef.current?.focus?.();
  }, [open]);

  const transition = useMemo<Transition>(
    () => ({ type: "spring", stiffness, damping, mass: 0.8 }),
    [stiffness, damping],
  );

  const growFrom = useMemo(() => {
    if (!originRect || reducedMotion || typeof window === "undefined")
      return null;
    const vw = window.innerWidth;
    const vh = window.innerHeight;
    const panelW = Math.min(originMaxWidth ?? 448, vw - 32);
    const x = originRect.left + originRect.width / 2 - vw / 2;
    const y = originRect.top + originRect.height / 2 - vh / 2;
    const scale = Math.min(0.9, Math.max(0.1, originRect.width / panelW));
    return { opacity: 0, x, y, scale };
  }, [originRect, reducedMotion, originMaxWidth]);

  if (!mounted) return null;

  const fade = {
    initial: { opacity: 0, scale: 0.96 },
    animate: { opacity: 1, scale: 1 },
    exit: { opacity: 0, scale: 0.96 },
  };

  return createPortal(
    <MotionConfig transition={reducedMotion ? { duration: 0 } : transition}>
      <AnimatePresence initial={false} mode="sync">
        {open && (
          <>
            <motion.div
              key="grow-backdrop"
              className={cn(
                "fixed inset-0 z-40 h-full w-full",
                backdropClassName ??
                  cn(
                    "bg-white/40 dark:bg-black/50",
                    blurBackdrop && "backdrop-blur-xs",
                  ),
              )}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => onOpenChange(false)}
            />
            <div className="pointer-events-none fixed inset-0 z-50 flex items-center justify-center p-4">
              <motion.div
                ref={containerRef}
                initial={growFrom ?? fade.initial}
                animate={
                  growFrom ? { opacity: 1, x: 0, y: 0, scale: 1 } : fade.animate
                }
                exit={growFrom ?? fade.exit}
                style={{ borderRadius: radius, ...style }}
                onAnimationComplete={onAnimationComplete}
                role={role}
                aria-modal="true"
                aria-label={ariaLabel}
                aria-describedby={ariaDescribedby}
                className={cn("pointer-events-auto overflow-hidden", className)}
              >
                {children}
              </motion.div>
            </div>
          </>
        )}
      </AnimatePresence>
    </MotionConfig>,
    document.body,
  );
}

export interface GrowDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  title: string;
  description?: ReactNode;
  children: ReactNode;
  className?: string;
  originRect?: DOMRect | null;
  originMaxWidth?: number;
  stiffness?: number;
  damping?: number;
  radius?: number;
  blurBackdrop?: boolean;
  autoFocus?: boolean;
  reducedMotion?: boolean;
  role?: "dialog" | "alertdialog";
}

export default function GrowDialog({
  open,
  onOpenChange,
  title,
  description,
  children,
  className,
  originRect,
  originMaxWidth,
  stiffness = 320,
  damping = 34,
  radius = 16,
  blurBackdrop = true,
  autoFocus = true,
  reducedMotion,
  role = "dialog",
}: GrowDialogProps) {
  const osReduce = useReducedMotion();
  const reduce = Boolean(osReduce) || Boolean(reducedMotion);
  const descId = useId();

  return (
    <GrowPanel
      open={open}
      onOpenChange={onOpenChange}
      originRect={originRect}
      originMaxWidth={originMaxWidth}
      stiffness={stiffness}
      damping={damping}
      radius={radius}
      blurBackdrop={blurBackdrop}
      autoFocus={autoFocus}
      reducedMotion={reduce}
      role={role}
      aria-label={title}
      aria-describedby={description ? descId : undefined}
      className={cn(
        "flex max-h-[85svh] w-full max-w-sm flex-col overflow-hidden border border-hairline bg-panel shadow-2xl",
        className,
      )}
    >
      <motion.div
        className="flex min-h-0 flex-1 flex-col"
        initial={reduce ? false : { opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={reduce ? undefined : { duration: 0.18, delay: 0.12 }}
      >
        <div className="flex items-start justify-between gap-3 px-5 pt-4 pb-3">
          <div className="flex flex-col gap-1">
            <h2 className="font-display text-sm text-ink">{title}</h2>
            {description && (
              <p id={descId} className="font-sans text-xs leading-relaxed text-ink-mute">
                {description}
              </p>
            )}
          </div>
          <button
            type="button"
            onClick={() => onOpenChange(false)}
            className="-mt-0.5 -mr-1.5 rounded-md p-1.5 text-ink-dim transition-colors hover:bg-raised hover:text-ink"
            aria-label="Close dialog"
          >
            <X className="size-4" />
          </button>
        </div>
        {children}
      </motion.div>
    </GrowPanel>
  );
}
```

### 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` | Spring stiffness of the grow. Range 100–600. |
| `damping` | `number` | `34` | Spring damping — lower rings longer. Range 10–60. |
| `radius` | `number` | `16` | Panel corner radius. Range 0–32 px. |
| `blurBackdrop` | `boolean` | `true` | Frosted blur on the backdrop scrim. |
| `autoFocus` | `boolean` | `true` | Focus the first focusable element on open. |

## Usage

```tsx
import GrowDialog from "@/components/registry/grow-dialog/grow-dialog";

<GrowDialog
  stiffness={320}
  damping={34}
  radius={16}
  blurBackdrop={true}
  autoFocus={true}
/>
```

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.
