# Integrate `InlineEdit` from Motion Garden

You are helping me add the **InlineEdit** 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:** InlineEdit
- **Category:** Micro-interactions
- **Summary:** Text that becomes its own input with nothing moving. One padded box, two contents, sized in CSS.
- **Reference:** https://motion-garden.netlify.app/components/inline-edit
- **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 inline {
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
}

:root {
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
}

.dark {
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-dim: #bcc2c8;
  --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.

## 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/inline-edit/inline-edit.tsx`

```tsx
"use client";

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

export type InlineEditCommitOn = "blur" | "explicit";
export type InlineEditUnderline = "dotted" | "solid" | "none";

export interface InlineEditProps {
  value?: string;
  defaultValue?: string;
  onValueChange?: (value: string) => void;
  label?: string;
  placeholder?: string;
  commitOn?: InlineEditCommitOn;
  stiffness?: number;
  damping?: number;
  underline?: InlineEditUnderline;
  padX?: number;
  padY?: number;
  radius?: number;
  selectOnEdit?: boolean;
  allowEmpty?: boolean;
  showPencil?: boolean;
  multiline?: boolean;
  accentColor?: string;
  reducedMotion?: boolean;
  className?: string;
}

export default function InlineEdit({
  value,
  defaultValue = "",
  onValueChange,
  label = "Value",
  placeholder = "Empty",
  commitOn = "blur",
  stiffness = 460,
  damping = 32,
  underline = "dotted",
  padX = 8,
  padY = 5,
  radius = 6,
  selectOnEdit = true,
  allowEmpty = false,
  showPencil = true,
  multiline = false,
  accentColor = "#a855f7",
  reducedMotion = false,
  className,
}: InlineEditProps) {
  const controlled = value !== undefined;
  const [self, setSelf] = useState(defaultValue);
  const committed = controlled ? value : self;

  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(committed);

  const rootRef = useRef<HTMLSpanElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const fieldRef = useRef<HTMLInputElement & HTMLTextAreaElement>(null);
  const handBack = useRef(false);

  useEffect(() => {
    if (!editing) return;
    const field = fieldRef.current;
    if (!field) return;
    field.focus({ preventScroll: true });
    if (selectOnEdit) field.select();
  }, [editing, selectOnEdit]);

  useEffect(() => {
    if (editing || !handBack.current) return;
    handBack.current = false;
    buttonRef.current?.focus({ preventScroll: true });
  }, [editing]);

  const begin = () => {
    setDraft(committed);
    setEditing(true);
  };

  const finish = (next: string) => {
    if (!controlled) setSelf(next);
    onValueChange?.(next);
    setEditing(false);
  };

  const commit = (refocus = false) => {
    handBack.current = refocus;
    const next = draft.trim();
    finish(!next && !allowEmpty ? committed : draft);
  };

  const cancel = (refocus = false) => {
    handBack.current = refocus;
    setDraft(committed);
    setEditing(false);
  };

  const box = {
    paddingLeft: padX,
    paddingRight: padX,
    paddingTop: padY,
    paddingBottom: padY,
    borderRadius: radius,
  };
  const type = cn(
    "font-sans text-[15px] leading-normal",
    multiline ? "whitespace-pre-wrap" : "whitespace-pre",
  );

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

  return (
    <span
      ref={rootRef}
      className={cn("group/edit relative inline-block", className)}
    >
      <motion.span
        className="block border border-solid"
        style={box}
        initial={false}
        animate={{
          backgroundColor: editing ? `${accentColor}14` : `${accentColor}00`,
          borderColor: editing ? accentColor : `${accentColor}00`,
          boxShadow: editing
            ? `0 0 0 3px ${accentColor}26`
            : `0 0 0 0px ${accentColor}00`,
        }}
        transition={spring}
      >
        {editing ? (
          <span className="grid *:col-1 *:row-1">
            <span aria-hidden className={cn(type, "invisible wrap-break-word")}>
              {draft.endsWith("\n") ? `${draft} ` : draft || "​"}
            </span>
            {multiline ? (
              <textarea
                ref={fieldRef}
                rows={1}
                cols={1}
                value={draft}
                placeholder={placeholder}
                aria-label={label}
                onChange={(event) => setDraft(event.target.value)}
                onKeyDown={(event) => {
                  if (event.key === "Escape") {
                    event.stopPropagation();
                    cancel(true);
                  }
                  if (event.key === "Enter" && (event.metaKey || event.ctrlKey))
                    commit(true);
                }}
                onBlur={(event) => {
                  if (rootRef.current?.contains(event.relatedTarget)) return;
                  if (commitOn === "blur") commit();
                  else cancel();
                }}
                className={cn(
                  type,
                  "h-0 min-h-full w-0 min-w-full resize-none overflow-hidden bg-transparent text-ink outline-none placeholder:text-ink-mute/70",
                )}
              />
            ) : (
              <input
                ref={fieldRef}
                type="text"
                size={1}
                value={draft}
                placeholder={placeholder}
                aria-label={label}
                onChange={(event) => setDraft(event.target.value)}
                onKeyDown={(event) => {
                  if (event.key === "Escape") {
                    event.stopPropagation();
                    cancel(true);
                  }
                  if (event.key === "Enter") {
                    event.preventDefault();
                    commit(true);
                  }
                }}
                onBlur={(event) => {
                  if (rootRef.current?.contains(event.relatedTarget)) return;
                  if (commitOn === "blur") commit();
                  else cancel();
                }}
                className={cn(
                  type,
                  "w-0 min-w-full bg-transparent text-ink outline-none placeholder:text-ink-mute/70",
                )}
              />
            )}
          </span>
        ) : (
          <button
            ref={buttonRef}
            type="button"
            onClick={begin}
            aria-label={`${label}: ${committed || placeholder}`}
            className={cn(
              type,
              "block w-full cursor-text text-left text-ink outline-none",
              "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent",
              !multiline && "overflow-hidden text-ellipsis",
              !committed && "text-ink-mute",
            )}
            style={{
              textDecorationLine: underline === "none" ? "none" : "underline",
              textDecorationStyle:
                underline === "dotted" ? "dotted" : ("solid" as const),
              textDecorationColor: `${accentColor}66`,
              textUnderlineOffset: 4,
            }}
          >
            {committed || placeholder}
          </button>
        )}
      </motion.span>

      {showPencil && !editing ? (
        <span
          aria-hidden
          className="pointer-events-none absolute top-1/2 -right-6 -translate-y-1/2 text-ink-mute opacity-0 transition-opacity duration-150 group-focus-within/edit:opacity-100 group-hover/edit:opacity-100"
        >
          <svg
            viewBox="0 0 24 24"
            className="size-3.5"
            fill="none"
            stroke="currentColor"
            strokeWidth={2}
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M12 20h9" />
            <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />
          </svg>
        </span>
      ) : null}

      {editing && commitOn === "explicit" ? (
        <span className="absolute top-1/2 -right-13 flex -translate-y-1/2 gap-1">
          <button
            type="button"
            onMouseDown={(event) => event.preventDefault()}
            onClick={() => commit(true)}
            aria-label="Save"
            className="rounded-sm border border-hairline p-1 text-ink-dim transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent"
          >
            <svg
              viewBox="0 0 24 24"
              className="size-3"
              fill="none"
              stroke="currentColor"
              strokeWidth={3}
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M4 12.5 9.5 18 20 6.5" />
            </svg>
          </button>
          <button
            type="button"
            onMouseDown={(event) => event.preventDefault()}
            onClick={() => cancel(true)}
            aria-label="Cancel"
            className="rounded-sm border border-hairline p-1 text-ink-dim transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent"
          >
            <svg
              viewBox="0 0 24 24"
              className="size-3"
              fill="none"
              stroke="currentColor"
              strokeWidth={3}
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M5 5 19 19M19 5 5 19" />
            </svg>
          </button>
        </span>
      ) : null}
    </span>
  );
}
```

### 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 |
| --- | --- | --- | --- |
| `commitOn` | `"blur" | "explicit"` | `"blur"` | Blur commits when focus leaves. Explicit grows a confirm and a cancel outside the box and treats losing focus as a cancel. Both are defensible, which is why it is a prop rather than a decision. |
| `stiffness` | `number` | `460` | Spring tension on the border, wash and ring arriving. This is the only thing that animates — everything else is already exactly where it will be. Range 120–900. |
| `damping` | `number` | `32` | Spring friction on the same. Low overshoots the colour, which on a border reads as a flash rather than as bounce. Range 8–60. |
| `underline` | `"dotted" | "solid" | "none"` | `"dotted"` | How the display state says it is editable. A text decoration rather than a border, because a border would have to be reserved in the editing state too — and none is the honest option for a row that already announces itself some other way. |
| `padX` | `number` | `8` | Horizontal padding. Shared by both states by construction: it lives on the shell, which never unmounts, so the two contents cannot disagree about it. Range 0–24 px. |
| `padY` | `number` | `5` | Vertical padding. The one that shifts every row below it when an inline editor gets this wrong. Range 0–16 px. |
| `radius` | `number` | `6` | Corner radius of the shell. Range 0–16 px. |
| `selectOnEdit` | `boolean` | `true` | Select the whole value on entering edit, so typing replaces it. Off puts the caret where the click landed, which is the right behaviour for a long value being amended rather than renamed. |
| `allowEmpty` | `boolean` | `false` | Accept an empty commit. Off puts the previous value back, on the grounds that a blank field is a mis-click far more often than an intention. |
| `showPencil` | `boolean` | `true` | Pencil on hover and keyboard focus. Absolutely positioned outside the shell — anything rendered inside it changes the width of the box the component exists to hold still. |
| `multiline` | `boolean` | `false` | A textarea that grows by line instead of a single-line field. The growth is the same CSS trick either way: an invisible copy of the draft sized in the same grid cell, so nothing is measured in JavaScript. |
| `accentColor` | `string (hex)` | `"#a855f7"` | The border, wash and ring of the editing state, and the underline of the display state. Expected as a 6-digit hex: the transparent variants are built by suffix so the fade runs on one interpolation rather than between two colours. |

## Usage

```tsx
import InlineEdit from "@/components/registry/inline-edit/inline-edit";

<InlineEdit
  commitOn="blur"
  stiffness={460}
  damping={32}
  underline="dotted"
  padX={8}
  padY={5}
  radius={6}
  selectOnEdit={true}
  allowEmpty={false}
  showPencil={true}
  multiline={false}
  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.
