# Integrate `Tether` from Motion Garden

You are helping me add the **Tether** 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:** Tether
- **Category:** Micro-interactions
- **Summary:** A popover that grows out of the corner nearest its trigger, and moves that origin when it flips.
- **Reference:** https://motion-garden.netlify.app/components/tether
- **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);
}

:root {
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
}

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

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

```tsx
"use client";

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

export type TetherSide = "top" | "right" | "bottom" | "left";
export type TetherAlign = "start" | "center" | "end";
export type TetherOpenOn = "click" | "hover";

export interface TetherProps {
  trigger?: ReactNode;
  children?: ReactNode;
  side?: TetherSide;
  align?: TetherAlign;
  offset?: number;
  stiffness?: number;
  damping?: number;
  popScale?: number;
  arrow?: boolean;
  flip?: boolean;
  openOn?: TetherOpenOn;
  closeDelay?: number;
  radius?: number;
  accentColor?: string;
  reducedMotion?: boolean;
  className?: string;
  panelClassName?: string;
}

const OPPOSITE: Record<TetherSide, TetherSide> = {
  top: "bottom",
  bottom: "top",
  left: "right",
  right: "left",
};

function originFor(side: TetherSide, align: TetherAlign): string {
  const along =
    align === "start" ? "0%" : align === "end" ? "100%" : "50%";
  switch (side) {
    case "bottom":
      return `${along} 0%`;
    case "top":
      return `${along} 100%`;
    case "right":
      return `0% ${along}`;
    case "left":
      return `100% ${along}`;
  }
}

const NUDGE = 6;

const useIsoLayoutEffect =
  typeof window !== "undefined" ? useLayoutEffect : useEffect;

export default function Tether({
  trigger,
  children,
  side = "bottom",
  align = "center",
  offset = 10,
  stiffness = 520,
  damping = 26,
  popScale = 0.86,
  arrow = true,
  flip = true,
  openOn = "click",
  closeDelay = 140,
  radius = 10,
  accentColor = "#a855f7",
  reducedMotion = false,
  className,
  panelClassName,
}: TetherProps) {
  const uid = useId();
  const [open, setOpen] = useState(false);
  const [flipped, setFlipped] = useState(false);
  const [lastSide, setLastSide] = useState(side);
  if (lastSide !== side) {
    setLastSide(side);
    setFlipped(false);
  }
  const resolved = flipped ? OPPOSITE[side] : side;

  const rootRef = useRef<HTMLDivElement>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const panelRef = useRef<HTMLDivElement>(null);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const openedBy = useRef<TetherOpenOn>("click");

  const clearClose = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = null;
  };

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

  const place = useCallback(() => {
    const triggerEl = triggerRef.current;
    const panel = panelRef.current;
    if (!triggerEl || !panel) return;
    if (!flip) {
      setFlipped(false);
      return;
    }
    const box = triggerEl.getBoundingClientRect();
    const w = panel.offsetWidth + offset;
    const h = panel.offsetHeight + offset;
    const room = {
      top: box.top,
      bottom: window.innerHeight - box.bottom,
      left: box.left,
      right: window.innerWidth - box.right,
    };
    const need = side === "top" || side === "bottom" ? h : w;
    setFlipped(room[side] < need && room[OPPOSITE[side]] >= need);
  }, [flip, offset, side]);

  useIsoLayoutEffect(() => {
    if (!open) return;
    place();
  }, [open, place]);

  useEffect(() => {
    if (!open) return;
    const onScrollOrResize = () => place();
    window.addEventListener("resize", onScrollOrResize);
    window.addEventListener("scroll", onScrollOrResize, true);
    return () => {
      window.removeEventListener("resize", onScrollOrResize);
      window.removeEventListener("scroll", onScrollOrResize, true);
    };
  }, [open, place]);

  useEffect(() => {
    if (!open) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key !== "Escape") return;
      setOpen(false);
      triggerRef.current?.focus();
    };
    const onDown = (event: PointerEvent) => {
      if (rootRef.current?.contains(event.target as Node)) return;
      setOpen(false);
    };
    document.addEventListener("keydown", onKey);
    document.addEventListener("pointerdown", onDown);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.removeEventListener("pointerdown", onDown);
    };
  }, [open]);

  useEffect(() => {
    if (open && openedBy.current === "click") {
      panelRef.current?.focus({ preventScroll: true });
    }
  }, [open]);

  const vertical = resolved === "top" || resolved === "bottom";
  const nudge = reducedMotion ? 0 : NUDGE;
  const from = {
    x: resolved === "left" ? nudge : resolved === "right" ? -nudge : 0,
    y: resolved === "top" ? nudge : resolved === "bottom" ? -nudge : 0,
  };

  const hover = openOn === "hover";

  return (
    <div
      ref={rootRef}
      className={cn("relative inline-block", className)}
      onPointerEnter={
        hover
          ? () => {
              clearClose();
              openedBy.current = "hover";
              setOpen(true);
            }
          : undefined
      }
      onPointerLeave={
        hover
          ? () => {
              clearClose();
              closeTimer.current = setTimeout(() => {
                if (rootRef.current?.contains(document.activeElement)) return;
                setOpen(false);
              }, Math.max(0, closeDelay));
            }
          : undefined
      }
    >
      <button
        ref={triggerRef}
        type="button"
        aria-expanded={open}
        aria-haspopup="dialog"
        aria-controls={open ? `${uid}-panel` : undefined}
        aria-describedby={open ? `${uid}-panel` : undefined}
        onClick={() => {
          if (hover) return;
          openedBy.current = "click";
          setOpen((v) => !v);
        }}
        onFocus={
          hover
            ? () => {
                clearClose();
                openedBy.current = "hover";
                setOpen(true);
              }
            : undefined
        }
        className="rounded-md border border-hairline bg-raised px-4 py-2 font-display text-[11px] tracking-[0.14em] text-ink uppercase transition-colors hover:bg-raised/70"
        style={{ boxShadow: open ? `inset 0 0 0 1px ${accentColor}` : undefined }}
      >
        {trigger}
      </button>

      <AnimatePresence>
        {open ? (
          <div
            key="tether-panel"
            className={cn(
              "absolute z-50",
              resolved === "bottom" && "top-full",
              resolved === "top" && "bottom-full",
              resolved === "right" && "left-full",
              resolved === "left" && "right-full",
              vertical && align === "start" && "left-0",
              vertical && align === "end" && "right-0",
              vertical && align === "center" && "left-1/2 -translate-x-1/2",
              !vertical && align === "start" && "top-0",
              !vertical && align === "end" && "bottom-0",
              !vertical && align === "center" && "top-1/2 -translate-y-1/2",
            )}
            style={{
              paddingTop: resolved === "bottom" ? offset : undefined,
              paddingBottom: resolved === "top" ? offset : undefined,
              paddingLeft: resolved === "right" ? offset : undefined,
              paddingRight: resolved === "left" ? offset : undefined,
            }}
          >
            <motion.div
              ref={panelRef}
              id={`${uid}-panel`}
              role="dialog"
              aria-label="More"
              tabIndex={-1}
              initial={
                reducedMotion ? false : { opacity: 0, scale: popScale, ...from }
              }
              animate={{ opacity: 1, scale: 1, x: 0, y: 0 }}
              exit={{ opacity: 0, scale: popScale, ...from }}
              transition={
                reducedMotion
                  ? { duration: 0 }
                  : { type: "spring", stiffness, damping }
              }
              style={{
                transformOrigin: originFor(resolved, align),
                borderRadius: radius,
              }}
              className={cn(
                "relative border border-hairline bg-panel shadow-xl outline-none",
                panelClassName,
              )}
            >
              <span
                aria-hidden
                className={cn(
                  "pointer-events-none absolute rounded-[inherit]",
                  resolved === "bottom" && "inset-x-0 top-0 h-0.5",
                  resolved === "top" && "inset-x-0 bottom-0 h-0.5",
                  resolved === "right" && "inset-y-0 left-0 w-0.5",
                  resolved === "left" && "inset-y-0 right-0 w-0.5",
                )}
                style={{ backgroundColor: accentColor }}
              />

              {arrow ? (
                <span
                  aria-hidden
                  className={cn(
                    "pointer-events-none absolute size-2 rotate-45",
                    resolved === "bottom" && "-top-1",
                    resolved === "top" && "-bottom-1",
                    resolved === "right" && "-left-1",
                    resolved === "left" && "-right-1",
                    vertical && align === "start" && "left-3.5",
                    vertical && align === "end" && "right-3.5",
                    vertical && align === "center" && "left-1/2 -ml-1",
                    !vertical && align === "start" && "top-3.5",
                    !vertical && align === "end" && "bottom-3.5",
                    !vertical && align === "center" && "top-1/2 -mt-1",
                  )}
                  style={{ backgroundColor: accentColor }}
                />
              ) : null}

              {children}
            </motion.div>
          </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 |
| --- | --- | --- | --- |
| `side` | `"top" | "right" | "bottom" | "left"` | `"bottom"` | Preferred side. The transform origin is derived from the side the panel actually resolved to, never this one — a flip that keeps the requested origin grows the panel away from the trigger it just moved to. |
| `align` | `"start" | "center" | "end"` | `"center"` | Where the panel sits along that side. It moves the origin and the caret together, so a start-aligned panel below the trigger grows down and to the right out of the button's left corner. |
| `offset` | `number` | `10` | Gap between trigger and panel. Padding rather than margin: a pointer crossing the gap on its way into a hover-opened panel never leaves the component, so the panel does not close under the cursor. Range 0–32 px. |
| `stiffness` | `number` | `520` | Spring tension on the pop. High enough to feel like the panel is already there by the time the eye arrives. Range 120–900. |
| `damping` | `number` | `26` | Spring friction. A little overshoot is the pop; too little and the panel wobbles, which on a menu reads as unresponsive rather than lively. Range 8–60. |
| `popScale` | `number` | `0.86` | Size the panel grows from. At 1 the origin work is invisible and the entrance is a plain fade — worth setting once to see what the rest of the component is buying. Range 0.3–1. |
| `arrow` | `boolean` | `true` | Caret on the tethered edge. It sits where the panel is anchored, so it stays pointing at the trigger through a side change without any repositioning code. |
| `flip` | `boolean` | `true` | Move to the opposite side when the preferred one would overflow the viewport. The fit test reads the panel's layout box rather than its bounding rect, because the rect carries the entrance scale and would decide using a box smaller than the one about to be there. |
| `openOn` | `"click" | "hover"` | `"click"` | What opens the panel. Click also moves focus into it; hover deliberately does not, and answers focus on the trigger instead so the keyboard is not locked out of a pointer-only affordance. |
| `closeDelay` | `number` | `140` | Grace period before a hover-opened panel closes. The timer also refuses to fire while focus is still inside, so a pointer wandering off cannot destroy the element someone is tabbing through. Range 0–800 ms. Ignored while `openOn` is `click`. |
| `radius` | `number` | `10` | Panel corner radius. Range 0–20 px. |
| `accentColor` | `string (hex)` | `"#a855f7"` | The rule on the tethered edge and the caret. Both move with a flip, so the panel keeps pointing back at its origin on whichever side it ended up. |

## Usage

```tsx
import Tether from "@/components/registry/tether/tether";

<Tether
  side="bottom"
  align="center"
  offset={10}
  stiffness={520}
  damping={26}
  popScale={0.86}
  arrow={true}
  flip={true}
  openOn="click"
  closeDelay={140}
  radius={10}
  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.
