# Animated Image Cropper for UI SDK (/docs/components/image-cropper)

The selection springs to a new ratio, handles grow while you drag and the zoom settles on a spring.

```tsx title="example.tsx"
import * as React from "react"

import {
  createImageCropperController,
  ImageCropper,
  ImageCropperFlip,
  ImageCropperGrid,
  ImageCropperHandle,
  ImageCropperImage,
  ImageCropperRotate,
  ImageCropperSelection,
  ImageCropperViewport,
  ImageCropperZoom,
  type ImageCrop,
} from "@/components/keyframery/image-cropper"

const photo = "/demo/lake.jpg"

const ratios = [
  { id: "free", label: "Free", value: undefined },
  { id: "square", label: "1:1", value: 1 },
  { id: "wide", label: "16:9", value: 16 / 9 },
] as const

const handles = ["nw", "n", "ne", "e", "se", "s", "sw", "w"] as const

const well =
  "bg-muted shadow-[inset_0_1px_2px_rgb(0_0_0/0.07),inset_0_0_0_1px_rgb(0_0_0/0.035)] dark:shadow-[inset_0_1px_2px_rgb(0_0_0/0.5),inset_0_0_0_1px_rgb(255_255_255/0.04)]"
const keySurface =
  "bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_1px_rgb(0_0_0/0.05),0_3px_6px_-2px_rgb(0_0_0/0.1)] dark:bg-accent dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07),inset_0_1px_0_rgb(255_255_255/0.08),0_2px_6px_-1px_rgb(0_0_0/0.6)]"
const ghost =
  "grid size-7 shrink-0 place-items-center rounded-[8px] text-muted-foreground outline-none transition-[scale,color] duration-[calc(200ms*var(--kf-speed,1))] ease-pop hover:text-foreground active:scale-[0.9] focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none"

function Icon({ d }: { d: string }) {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden className="size-4">
      <path d={d} />
    </svg>
  )
}

export default function ImageCropperDemo() {
  const [controller] = React.useState(() => createImageCropperController())
  const [ratio, setRatio] = React.useState<(typeof ratios)[number]["id"]>("free")
  const [crop, setCrop] = React.useState<ImageCrop>()
  const [hovered, setHovered] = React.useState<string | null>(null)
  const aspectRatio = ratios.find((r) => r.id === ratio)?.value

  const zoomBy = (step: number) => controller.setZoom(Math.min(3, Math.max(1, controller.getZoom() + step)))

  return (
    <div className="w-[420px]">
      <div className="mb-3 flex items-center justify-between">
        <div>
          <h3 className="text-[15px] font-semibold tracking-tight">Cover photo</h3>
          <p className="mt-1 text-[12px] text-muted-foreground tabular-nums">
            {crop ? `${Math.round(crop.width ?? 0)} × ${Math.round(crop.height ?? 0)} px` : "Loading…"}
          </p>
        </div>
        <div className={`flex gap-0.5 rounded-[11px] p-0.5 ${well}`}>
          {ratios.map((r) => (
            <button
              key={r.id}
              type="button"
              data-ratio={r.id}
              aria-pressed={ratio === r.id}
              onClick={() => setRatio(r.id)}
              className={[
                "h-7 rounded-[9px] px-2.5 text-[12px] leading-none font-medium tabular-nums outline-none transition-[color,scale] duration-[calc(150ms*var(--kf-speed,1))] ease-house active:scale-[0.96] focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none",
                ratio === r.id ? `${keySurface} text-foreground` : "text-muted-foreground hover:text-foreground",
              ].join(" ")}
            >
              {r.label}
            </button>
          ))}
        </div>
      </div>

      <ImageCropper
        aria-label="Cover photo"
        src={photo}
        aspectRatio={aspectRatio}
        minWidth={120}
        minHeight={120}
        maxZoom={3}
        controller={controller}
        onCropChange={(next) => setCrop(next)}
      >
        <ImageCropperViewport>
          <ImageCropperImage alt="A wooden jetty on a mountain lake" />
          <ImageCropperSelection>
            <ImageCropperGrid />
            {handles.map((position) => (
              <ImageCropperHandle
                key={position}
                position={position}
                data-hovered={hovered === position || undefined}
                onPointerEnter={() => setHovered(position)}
                onPointerLeave={() => setHovered(null)}
              />
            ))}
          </ImageCropperSelection>
        </ImageCropperViewport>

        <div className="flex items-center gap-2">
          <button type="button" data-zoom="out" aria-label="Zoom out" onClick={() => zoomBy(-0.5)} className={ghost}>
            <Icon d="M4 8h8" />
          </button>
          <ImageCropperZoom className="flex-1" />
          <button type="button" data-zoom="in" aria-label="Zoom in" onClick={() => zoomBy(0.5)} className={ghost}>
            <Icon d="M8 4v8M4 8h8" />
          </button>
          <span className="mx-1 h-5 w-px bg-border" aria-hidden />
          <ImageCropperRotate aria-label="Rotate">
            <Icon d="M13 8a5 5 0 1 1-1.5-3.55M13 2.5v2.5h-2.5" />
          </ImageCropperRotate>
          <ImageCropperFlip aria-label="Flip">
            <Icon d="M8 2v12M5.5 4.5 2.5 11.5h3zM10.5 4.5l3 7h-3z" />
          </ImageCropperFlip>
        </div>
      </ImageCropper>
    </div>
  )
}
```

## Installation [#installation]

```bash
npx shadcn@latest add @keyframery/image-cropper
```

This adds `components/keyframery/image-cropper.tsx` and its primitive, `components/keyframery/primitives/image-cropper.tsx`, to your project, and installs `@ui-sdk/react`. The motion tokens are added to your global CSS the first time you install a component.

## Usage [#usage]

```tsx
import {
  ImageCropper,
  ImageCropperFlip,
  ImageCropperGrid,
  ImageCropperHandle,
  ImageCropperImage,
  ImageCropperRotate,
  ImageCropperSelection,
  ImageCropperViewport,
  ImageCropperZoom,
} from "@/components/keyframery/image-cropper"
```

The parts and props are the same as UI SDK's Image Cropper. For every prop, see the [UI SDK image cropper reference](https://ui-sdk.dev/docs/components/image-cropper).

## What moves [#what-moves]

| Move       | What you see                                                                                                      |
| ---------- | ----------------------------------------------------------------------------------------------------------------- |
| **Spring** | The selection springs to a new box when the ratio or zoom changes, and follows the pointer exactly while dragged. |
| **Pop**    | Handles grow when you reach for them.                                                                             |
| **Fade**   | The area outside the crop dims, and lightens while you drag.                                                      |

Timing and springiness follow the [motion style](/docs/motion-styles) you set, so this component moves like the rest of your app.

## Swap the import [#swap-the-import]

Already using UI SDK's image cropper with your own styles? Keep your markup and change one line. The primitive adds motion and nothing else.

```tsx
// Before
import { … } from "@ui-sdk/react/image-cropper"

// After: same parts, same props, now animated
import { … } from "@/components/keyframery/primitives/image-cropper"
```

## Parts [#parts]

The finished component exports 9 parts:

`ImageCropper`, `ImageCropperFlip`, `ImageCropperGrid`, `ImageCropperHandle`, `ImageCropperImage`, `ImageCropperRotate`, `ImageCropperSelection`, `ImageCropperViewport`, `ImageCropperZoom`

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. With reduced motion turned on, nothing in the image cropper moves: changes happen at once or with a short fade. More in [Accessibility](/docs/accessibility).

## Source [#source]

The code that lands in your project. It is yours to change.

**components/keyframery/image-cropper.tsx**

```tsx
"use client"

/* Styled image cropper: the animated primitive plus the Keyframery look. */

import * as React from "react"

import {
  ImageCropper as ImageCropperPrimitive,
  ImageCropperFlip as ImageCropperFlipPrimitive,
  ImageCropperGrid as ImageCropperGridPrimitive,
  ImageCropperHandle as ImageCropperHandlePrimitive,
  ImageCropperImage as ImageCropperImagePrimitive,
  ImageCropperRotate as ImageCropperRotatePrimitive,
  ImageCropperSelection as ImageCropperSelectionPrimitive,
  ImageCropperViewport as ImageCropperViewportPrimitive,
  ImageCropperZoom as ImageCropperZoomPrimitive,
} from "@/components/keyframery/primitives/image-cropper"
import { cn } from "@/lib/utils"

export { createImageCropperController, type ImageCrop } from "@/components/keyframery/primitives/image-cropper"

function ImageCropper({ className, ...props }: React.ComponentProps<typeof ImageCropperPrimitive>) {
  return (
    <ImageCropperPrimitive
      className={cn("flex flex-col gap-3 data-disabled:opacity-60", className as string)}
      {...props}
    />
  )
}

/* A dark well the photo sits in, sized to the photo, with room around it for the handles. Dark in
   both themes, like a photo editor: the dim outside the crop then reads as one canvas. */
function ImageCropperViewport({ className, ...props }: React.ComponentProps<typeof ImageCropperViewportPrimitive>) {
  return (
    <ImageCropperViewportPrimitive
      className={cn(
        "box-border w-full rounded-[14px] bg-[oklch(0.24_0_0)] p-2.5 aspect-(--image-cropper-aspect-ratio,4/3) dark:bg-muted",
        "shadow-[inset_0_1px_2px_rgb(0_0_0/0.3),inset_0_0_0_1px_rgb(0_0_0/0.1)]",
        "dark:shadow-[inset_0_1px_2px_rgb(0_0_0/0.5),inset_0_0_0_1px_rgb(255_255_255/0.04)]",
        className as string,
      )}
      {...props}
    />
  )
}

function ImageCropperImage({ className, ...props }: React.ComponentProps<typeof ImageCropperImagePrimitive>) {
  return <ImageCropperImagePrimitive className={cn("rounded-[3px]", className as string)} {...props} />
}

/* A white hairline around the crop, and a dimmed photo outside it that lightens while you drag. */
function ImageCropperSelection({ className, ...props }: React.ComponentProps<typeof ImageCropperSelectionPrimitive>) {
  return (
    <ImageCropperSelectionPrimitive
      className={cn(
        "outline-none data-[shape=circle]:rounded-full",
        "shadow-[0_0_0_1.5px_rgb(255_255_255/0.95),0_0_0_9999px_rgb(0_0_0/0.52)]",
        "data-dragging:shadow-[0_0_0_1.5px_rgb(255_255_255/0.95),0_0_0_9999px_rgb(0_0_0/0.3)]",
        "starting:shadow-[0_0_0_1.5px_rgb(255_255_255/0),0_0_0_9999px_rgb(0_0_0/0)]",
        "focus-visible:shadow-[0_0_0_2px_var(--ring),0_0_0_9999px_rgb(0_0_0/0.52)]",
        className as string,
      )}
      {...props}
    />
  )
}

/* Lines in thirds. */
function ImageCropperGrid({ className, ...props }: React.ComponentProps<typeof ImageCropperGridPrimitive>) {
  return (
    <ImageCropperGridPrimitive
      className={cn(
        "before:absolute before:inset-y-0 before:left-1/3 before:right-1/3 before:border-x before:border-white/50 before:content-['']",
        "after:absolute after:inset-x-0 after:top-1/3 after:bottom-1/3 after:border-y after:border-white/50 after:content-['']",
        className as string,
      )}
      {...props}
    />
  )
}

/* White dots on the corners and short bars on the edges, with a larger invisible grip around each. */
function ImageCropperHandle({ className, ...props }: React.ComponentProps<typeof ImageCropperHandlePrimitive>) {
  return (
    <ImageCropperHandlePrimitive
      className={cn(
        "absolute z-10 -translate-1/2 rounded-full bg-white outline-none",
        "shadow-[0_0_0_1px_rgb(0_0_0/0.18),0_1px_3px_rgb(0_0_0/0.35)]",
        "before:absolute before:-inset-2.5 before:content-['']",
        "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-white",
        "data-[position=nw]:top-0 data-[position=nw]:left-0 data-[position=ne]:top-0 data-[position=ne]:left-full",
        "data-[position=sw]:top-full data-[position=sw]:left-0 data-[position=se]:top-full data-[position=se]:left-full",
        "data-[position=n]:top-0 data-[position=n]:left-1/2 data-[position=s]:top-full data-[position=s]:left-1/2",
        "data-[position=w]:top-1/2 data-[position=w]:left-0 data-[position=e]:top-1/2 data-[position=e]:left-full",
        "data-[position=ne]:size-3 data-[position=nw]:size-3 data-[position=se]:size-3 data-[position=sw]:size-3",
        "data-[position=n]:h-1.5 data-[position=n]:w-5 data-[position=s]:h-1.5 data-[position=s]:w-5",
        "data-[position=e]:h-5 data-[position=e]:w-1.5 data-[position=w]:h-5 data-[position=w]:w-1.5",
        className as string,
      )}
      {...props}
    />
  )
}

/* A thin range: a pill well with a round key for a thumb. */
function ImageCropperZoom({ className, ...props }: React.ComponentProps<typeof ImageCropperZoomPrimitive>) {
  return (
    <ImageCropperZoomPrimitive
      className={cn(
        "h-5 w-full cursor-pointer appearance-none bg-transparent outline-none disabled:cursor-not-allowed",
        "[&::-webkit-slider-runnable-track]:h-1.5 [&::-webkit-slider-runnable-track]:rounded-full [&::-webkit-slider-runnable-track]:bg-muted",
        "[&::-webkit-slider-runnable-track]:shadow-[inset_0_1px_1px_rgb(0_0_0/0.08),inset_0_0_0_1px_rgb(0_0_0/0.04)] dark:[&::-webkit-slider-runnable-track]:bg-accent",
        "[&::-webkit-slider-thumb]:-mt-[5px] [&::-webkit-slider-thumb]:size-4 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-background",
        "[&::-webkit-slider-thumb]:shadow-[0_0_0_1px_rgb(0_0_0/0.1),0_1px_1px_rgb(0_0_0/0.06),0_2px_5px_-1px_rgb(0_0_0/0.16)]",
        "[&::-webkit-slider-thumb]:transition-[scale] [&::-webkit-slider-thumb]:duration-[calc(300ms*var(--kf-speed,1))] [&::-webkit-slider-thumb]:ease-pop active:[&::-webkit-slider-thumb]:scale-125",
        "dark:[&::-webkit-slider-thumb]:bg-foreground",
        "[&::-moz-range-track]:h-1.5 [&::-moz-range-track]:rounded-full [&::-moz-range-track]:bg-muted",
        "[&::-moz-range-thumb]:size-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-background",
        "focus-visible:[&::-webkit-slider-thumb]:ring-2 focus-visible:[&::-webkit-slider-thumb]:ring-ring focus-visible:[&::-webkit-slider-thumb]:ring-offset-2 focus-visible:[&::-webkit-slider-thumb]:ring-offset-background",
        "motion-reduce:[&::-webkit-slider-thumb]:transition-none",
        className as string,
      )}
      {...props}
    />
  )
}

const keyButton = cn(
  "inline-flex h-8 shrink-0 items-center justify-center gap-1.5 rounded-[9px] px-2.5 text-[13px] leading-none font-medium outline-none",
  "bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_1px_rgb(0_0_0/0.05),0_3px_6px_-2px_rgb(0_0_0/0.1)]",
  "dark:bg-accent dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07),inset_0_1px_0_rgb(255_255_255/0.08),0_2px_6px_-1px_rgb(0_0_0/0.6)]",
  "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
  "disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0",
)

function ImageCropperRotate({ className, ...props }: React.ComponentProps<typeof ImageCropperRotatePrimitive>) {
  return <ImageCropperRotatePrimitive className={cn(keyButton, className as string)} {...props} />
}

function ImageCropperFlip({ className, ...props }: React.ComponentProps<typeof ImageCropperFlipPrimitive>) {
  return <ImageCropperFlipPrimitive className={cn(keyButton, className as string)} {...props} />
}

export {
  ImageCropper,
  ImageCropperFlip,
  ImageCropperGrid,
  ImageCropperHandle,
  ImageCropperImage,
  ImageCropperRotate,
  ImageCropperSelection,
  ImageCropperViewport,
  ImageCropperZoom,
}
```

**components/keyframery/primitives/image-cropper.tsx**

```tsx
"use client"

/* Animated drop-in for `@ui-sdk/react/image-cropper`: same parts, same props. Swap the import and keep
   your code. This file adds motion only. Colours, radii, shadows and spacing stay yours. */

import {
  ImageCropper as ImageCropperPart,
  ImageCropperFlip as ImageCropperFlipPart,
  ImageCropperGrid as ImageCropperGridPart,
  ImageCropperHandle as ImageCropperHandlePart,
  ImageCropperImage as ImageCropperImagePart,
  ImageCropperRotate as ImageCropperRotatePart,
  ImageCropperSelection as ImageCropperSelectionPart,
} from "@ui-sdk/react/image-cropper"
import * as React from "react"

import { cn } from "@/lib/utils"

export * from "@ui-sdk/react/image-cropper"

/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* Press: buttons give under the finger and spring back on release. */
const press =
  "transition-[scale] duration-[calc(200ms*var(--kf-speed,1))] ease-pop not-disabled:active:scale-[0.96] motion-reduce:transition-none!"

/* The root names a group so the image can tell when a drag is under way. */
function ImageCropper({ className, ...props }: React.ComponentProps<typeof ImageCropperPart>) {
  return <ImageCropperPart className={withClass("group/kf-cropper", className)} {...props} />
}

/* The image clears out of a blur once it loads, and springs to its new place and turn on a rotate,
   a flip or a frame zoom. While a pointer pans it, it follows the pointer exactly. */
function ImageCropperImage({ className, ...props }: React.ComponentProps<typeof ImageCropperImagePart>) {
  return (
    <ImageCropperImagePart
      className={withClass(
        cn(
          "[transition:left_calc(560ms*var(--kf-speed,1))_var(--ease-spring),top_calc(560ms*var(--kf-speed,1))_var(--ease-spring),width_calc(560ms*var(--kf-speed,1))_var(--ease-spring),height_calc(560ms*var(--kf-speed,1))_var(--ease-spring),transform_calc(620ms*var(--kf-speed,1))_var(--ease-spring),opacity_calc(420ms*var(--kf-speed,1))_var(--ease-house),filter_calc(420ms*var(--kf-speed,1))_var(--ease-house)]",
          "data-loading:opacity-0 data-loading:blur-[10px]",
          "group-data-dragging/kf-cropper:[transition:opacity_calc(420ms*var(--kf-speed,1))_var(--ease-house),filter_calc(420ms*var(--kf-speed,1))_var(--ease-house)]",
          "motion-reduce:[transition:none]!",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* The selection springs to its new box when the ratio or the zoom changes, or an arrow key moves
   it, and tracks the pointer exactly while dragged. Its shadow (the dimmed area outside) fades:
   in once the image loads, and lighter or darker as your own classes change it during a drag. */
function ImageCropperSelection({ className, ...props }: React.ComponentProps<typeof ImageCropperSelectionPart>) {
  return (
    <ImageCropperSelectionPart
      className={withClass(
        cn(
          "[transition:left_calc(560ms*var(--kf-speed,1))_var(--ease-spring),top_calc(560ms*var(--kf-speed,1))_var(--ease-spring),width_calc(560ms*var(--kf-speed,1))_var(--ease-spring),height_calc(560ms*var(--kf-speed,1))_var(--ease-spring),box-shadow_calc(320ms*var(--kf-speed,1))_var(--ease-house),opacity_calc(360ms*var(--kf-speed,1))_var(--ease-house),scale_calc(520ms*var(--kf-speed,1))_var(--ease-spring)]",
          "data-dragging:[transition:box-shadow_calc(320ms*var(--kf-speed,1))_var(--ease-house)]",
          "starting:scale-[0.9] starting:opacity-0",
          "motion-reduce:[transition:none]!",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* The thirds fade in while you drag, and out when you let go. */
function ImageCropperGrid({ className, ...props }: React.ComponentProps<typeof ImageCropperGridPart>) {
  return (
    <ImageCropperGridPart
      className={withClass(
        cn(
          "opacity-0 transition-opacity duration-[calc(240ms*var(--kf-speed,1))] ease-house data-dragging:opacity-100",
          "motion-reduce:transition-none!",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* A handle grows with a pop under the pointer, and a little more while it is dragged. Set
   `data-hovered` to show the hover from script. */
function ImageCropperHandle({ className, ...props }: React.ComponentProps<typeof ImageCropperHandlePart>) {
  return (
    <ImageCropperHandlePart
      className={withClass(
        cn(
          "transition-[scale] duration-[calc(360ms*var(--kf-speed,1))] ease-pop",
          "not-data-disabled:hover:scale-[1.45] data-hovered:scale-[1.45] data-dragging:scale-[1.6]",
          "motion-reduce:transition-none!",
        ),
        className,
      )}
      {...props}
    />
  )
}

function ImageCropperRotate({ className, ...props }: React.ComponentProps<typeof ImageCropperRotatePart>) {
  return <ImageCropperRotatePart className={withClass(press, className)} {...props} />
}

function ImageCropperFlip({ className, ...props }: React.ComponentProps<typeof ImageCropperFlipPart>) {
  return <ImageCropperFlipPart className={withClass(press, className)} {...props} />
}

export {
  ImageCropper,
  ImageCropperFlip,
  ImageCropperGrid,
  ImageCropperHandle,
  ImageCropperImage,
  ImageCropperRotate,
  ImageCropperSelection,
}
```

## Questions

### How does the animated Image Cropper for UI SDK move?

Spring: The selection springs to a new box when the ratio or zoom changes, and follows the pointer exactly while dragged. Pop: Handles grow when you reach for them. Fade: The area outside the crop dims, and lightens while you drag.

### Do I need Motion or Framer Motion for the animated Image Cropper?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### Can I keep my own styling and only take the motion?

Yes. Import from `@/components/keyframery/primitives/image-cropper` instead. It has the same parts and props as `@ui-sdk/react/image-cropper` and adds motion only.

### What happens to the Image Cropper when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
