# Integrate `Crossing` from Motion Garden

You are helping me add the **Crossing** 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:** Crossing
- **Category:** Micro-interactions
- **Summary:** A gallery-to-detail crossing on the View Transitions API, where one element is the same object in both views.
- **Reference:** https://motion-garden.netlify.app/components/crossing
- **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 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-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-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
}

.dark {
  --sg-panel: #101215;
  --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/crossing/crossing.tsx`

```tsx
"use client";

import { useEffect, useId, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { cn } from "@/lib/utils";

export type CrossingEasing = "expressive" | "standard" | "linear";
export type CrossingExit = "fade" | "hold" | "slide";

export interface CrossingItem {
  id: string;
  title: string;
  meta: string;
  body: string;
  tone: string;
}

export interface CrossingProps {
  items?: CrossingItem[];
  duration?: number;
  easing?: CrossingEasing;
  shareTitle?: boolean;
  exit?: CrossingExit;
  radius?: number;
  viewTransition?: boolean;
  announce?: boolean;
  accentColor?: string;
  reducedMotion?: boolean;
  className?: string;
}

const EASING: Record<CrossingEasing, string> = {
  expressive: "cubic-bezier(0.22, 1, 0.36, 1)",
  standard: "cubic-bezier(0.4, 0, 0.2, 1)",
  linear: "linear",
};

function sheet(
  ns: string,
  duration: number,
  easing: string,
  exit: CrossingExit,
): string {
  const at = `:root[data-crossing="${ns}"]`;
  const group = (n: string) => `${at}::view-transition-group(${ns}-${n})`;
  const old = (n: string) => `${at}::view-transition-old(${ns}-${n})`;
  const fresh = (n: string) => `${at}::view-transition-new(${ns}-${n})`;
  const ms = (fraction: number) => `${Math.round(duration * fraction)}ms`;

  const heroExit =
    exit === "hold"
      ? `${old("hero")} { animation-name: none; opacity: 1; }`
      : exit === "slide"
        ? `${old("hero")} { animation-name: ${ns}-slide; }`
        : `${old("hero")} { animation-name: ${ns}-out; }`;

  const blend =
    exit === "fade"
      ? [old("body"), fresh("body"), old("title"), fresh("title")]
      : [
          old("body"),
          fresh("body"),
          old("title"),
          fresh("title"),
          old("hero"),
          fresh("hero"),
        ];

  return `
${at}::view-transition-old(root),
${at}::view-transition-new(root) { animation-duration: 0s; }

@keyframes ${ns}-out { to { opacity: 0; } }
@keyframes ${ns}-in { from { opacity: 0; transform: translateY(8px); } }
@keyframes ${ns}-fade { from { opacity: 0; } }
@keyframes ${ns}-slide { to { opacity: 0; transform: translateY(-12px); } }

${group("hero")}, ${group("title")}, ${group("body")} {
  animation-duration: ${duration}ms;
  animation-timing-function: ${easing};
  overflow: clip;
}

/* Both halves of every pair are pinned to the box their group is currently at.
   The UA default is a 100% inline size with an AUTO block size, which means a
   snapshot whose aspect ratio differs from its destination grows to whatever
   height that width implies — and the pseudo-elements live in the top layer,
   so nothing clips it. Measured: a 149x169 tile morphing to 470x124 drew its
   outgoing copy 532px tall, straight through the bottom of the panel and over
   the page beneath. Cover crops instead of overflowing; the title gets contain,
   because letterboxing text is the only way to keep it from being scaled to
   three times its size on the way across. */
${old("hero")}, ${fresh("hero")}, ${old("body")}, ${fresh("body")} {
  inline-size: 100%;
  block-size: 100%;
  object-fit: cover;
}
${old("title")}, ${fresh("title")} {
  inline-size: 100%;
  block-size: 100%;
  object-fit: contain;
  object-position: left center;
}

/* The browser blends the two halves of every pair with plus-lighter, which
   ADDS them. That is exactly right for its own cross-fade, where the two
   opacities always sum to one, and exactly wrong for anything else: hold the
   outgoing tile at full opacity and fade the incoming one in over it and the
   sum climbs toward two, so the gradient washes out to pastel and snaps back to
   its real colour the instant the transition ends. It reads as a brightness
   flash on every crossing and there is nothing in the component's own CSS to
   blame for it. Any timing that is not a symmetric cross-fade has to opt out. */
${blend.join(",\n")} {
  mix-blend-mode: normal;
}

${old("hero")}, ${fresh("hero")} {
  animation-duration: ${duration}ms;
  animation-timing-function: ${easing};
}
${heroExit}

/* The body and the title hand over rather than cross-fade. Run both halves at
   once over the whole duration — the browser default — and every word of the
   outgoing view sits at half opacity on top of every word of the incoming one
   for the length of the transition: two headings, two paragraphs, three ghost
   tiles behind a title. Separating them in time costs nothing and the
   double-exposure is simply gone. The gap is where the tile does its work. */
${old("body")} {
  animation-name: ${ns}-out;
  animation-duration: ${ms(0.4)};
  animation-timing-function: ease-out;
  animation-fill-mode: both;
}
${fresh("body")} {
  animation-name: ${ns}-in;
  animation-duration: ${ms(0.55)};
  animation-delay: ${ms(0.45)};
  animation-timing-function: ${easing};
  animation-fill-mode: both;
}
${old("title")} {
  animation-name: ${ns}-out;
  animation-duration: ${ms(0.3)};
  animation-fill-mode: both;
}
${fresh("title")} {
  animation-name: ${ns}-fade;
  animation-duration: ${ms(0.35)};
  animation-delay: ${ms(0.45)};
  animation-fill-mode: both;
}
`;
}

export default function Crossing({
  items = [],
  duration = 380,
  easing = "expressive",
  shareTitle = true,
  exit = "hold",
  radius = 12,
  viewTransition = true,
  announce = true,
  accentColor = "#a855f7",
  reducedMotion = false,
  className,
}: CrossingProps) {
  const ns = `sg${useId().replace(/[^a-zA-Z0-9]/g, "")}`;
  const [openId, setOpenId] = useState<string | null>(null);
  const [crossing, setCrossing] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [said, setSaid] = useState("");
  const backRef = useRef<HTMLButtonElement>(null);
  const rootRef = useRef<HTMLDivElement>(null);

  const open = items.find((item) => item.id === openId) ?? null;

  useEffect(() => {
    const root = document.documentElement;
    return () => root.removeAttribute("data-crossing");
  }, []);

  const cross = (nextId: string | null, id: string, label: string) => {
    setSaid(label);
    const commit = () => setOpenId(nextId);
    const root = document.documentElement;

    if (
      !viewTransition ||
      reducedMotion ||
      typeof document.startViewTransition !== "function"
    ) {
      setCrossing(id);
      commit();
      return;
    }

    flushSync(() => {
      setCrossing(id);
      setBusy(true);
    });
    root.setAttribute("data-crossing", ns);
    const transition = document.startViewTransition(() => {
      flushSync(commit);
    });
    const done = () => {
      root.removeAttribute("data-crossing");
      setBusy(false);
    };
    if (transition && transition.finished) {
      transition.finished.then(done, done);
    } else {
      done();
    }
  };

  useEffect(() => {
    if (openId) {
      backRef.current?.focus({ preventScroll: true });
      return;
    }
    if (!crossing) return;
    rootRef.current
      ?.querySelector<HTMLElement>(`[data-card="${crossing}"]`)
      ?.focus({ preventScroll: true });
  }, [openId, crossing]);

  const heroName = (id: string) =>
    crossing === id ? `${ns}-hero` : undefined;
  const titleName = (id: string) =>
    shareTitle && crossing === id ? `${ns}-title` : undefined;

  return (
    <>
      <style>{sheet(ns, duration, EASING[easing], exit)}</style>

      <div
        ref={rootRef}
        className={cn(
          "relative flex w-full flex-col overflow-hidden border border-hairline bg-panel p-5",
          className,
        )}
        style={{ borderRadius: radius }}
      >
        <div
          className="flex min-h-0 flex-1 flex-col"
          style={{ viewTransitionName: `${ns}-body` }}
        >
          <div className="mb-4 flex h-5 items-center">
            {open ? (
              <button
                ref={backRef}
                type="button"
                onClick={() => cross(null, open.id, "Back to the gallery")}
                className="inline-flex items-center gap-1.5 font-display text-[10px] tracking-[0.18em] text-ink-dim uppercase transition-colors hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2"
                style={{ outlineColor: accentColor }}
              >
                <svg
                  viewBox="0 0 24 24"
                  className="size-3"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth={3}
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  aria-hidden
                >
                  <path d="M15 5 8 12l7 7" />
                </svg>
                Back
              </button>
            ) : (
              <span className="font-display text-[10px] tracking-[0.18em] text-ink-mute uppercase">
                {items.length} areas
              </span>
            )}
          </div>

          {open ? (
            <div className="flex min-h-0 flex-1 flex-col">
              <div
                className="mb-4 w-full flex-1"
                style={{
                  background: open.tone,
                  borderRadius: radius - 3,
                  viewTransitionName: heroName(open.id),
                }}
              />

              <h3
                className="font-display text-[13px] tracking-[0.16em] text-ink uppercase"
                style={{ viewTransitionName: titleName(open.id) }}
              >
                {open.title}
              </h3>
              <p className="mt-2 font-sans text-[13px] leading-relaxed text-ink-dim">
                {open.body}
              </p>
            </div>
          ) : (
            <div className="grid min-h-0 flex-1 grid-cols-3 gap-3">
              {items.map((item) => (
                <button
                  key={item.id}
                  type="button"
                  data-card={item.id}
                  onClick={() =>
                    cross(item.id, item.id, `${item.title}, detail`)
                  }
                  className="group/card flex min-h-0 flex-col text-left focus-visible:outline-2 focus-visible:outline-offset-2"
                  style={{ borderRadius: radius - 3, outlineColor: accentColor }}
                >
                  <div
                    className="w-full flex-1 transition-transform duration-200 group-hover/card:-translate-y-0.5"
                    style={{
                      background: item.tone,
                      borderRadius: radius - 3,
                      viewTransitionName: heroName(item.id),
                      boxShadow:
                        crossing === item.id && !busy && !openId
                          ? `0 0 0 2px ${accentColor}`
                          : undefined,
                    }}
                  />
                  <p
                    className="mt-2 font-display text-[10px] tracking-[0.14em] text-ink uppercase"
                    style={{ viewTransitionName: titleName(item.id) }}
                  >
                    {item.title}
                  </p>
                  <p className="mt-0.5 font-sans text-[11px] text-ink-mute">
                    {item.meta}
                  </p>
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {announce ? (
        <span aria-live="polite" className="sr-only">
          {said}
        </span>
      ) : null}
    </>
  );
}
```

### 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 |
| --- | --- | --- | --- |
| `duration` | `number` | `380` | Length of the crossing. Applied to the shared elements and the view together through pseudo-element rules the component scopes to itself, so it never retimes a transition something else on the page is running. Range 120–1200 ms. |
| `easing` | `"expressive" | "standard" | "linear"` | `"expressive"` | Curve on the travel. Expressive arrives fast and settles; standard is the material curve; linear is there to show what the easing is worth, which on a morph is most of it. |
| `shareTitle` | `boolean` | `true` | Carry the title across as a second shared element. Off, only the tile travels and the title cross-fades with the rest — the clearest way to see what a shared element buys over a crossfade. |
| `exit` | `"hold" | "fade" | "slide"` | `"hold"` | What the outgoing copy of the tile does while the incoming one arrives. Hold keeps it opaque underneath and is the default: it is the only one with no instant where two gradients are both half there. Fade is the browser's own behaviour, kept so the difference is visible; slide sends the old one off as the new lands. |
| `radius` | `number` | `12` | Corner radius of the frame and, three px in, the tiles. Range 0–28 px. |
| `viewTransition` | `boolean` | `true` | Run the API at all. Off takes exactly the path an unsupported browser takes — the state update, bare — which is the only honest way to see the fallback. A view transition cannot be shortened, only skipped. |
| `announce` | `boolean` | `true` | Announce the destination in a live region. A view transition is invisible to assistive tech, so a crossing that says nothing is a dead end for anyone not watching the pixels. |
| `accentColor` | `string (hex)` | `"#a855f7"` | Focus ring, and the mark on the card you came back from — drawn only once the crossing has finished. Anything painted on the shared element while it is in flight is captured into the snapshot and travels across the frame with it. |

## Usage

```tsx
import Crossing from "@/components/registry/crossing/crossing";

<Crossing
  duration={380}
  easing="expressive"
  shareTitle={true}
  exit="hold"
  radius={12}
  viewTransition={true}
  announce={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.
