# Avatar cropper

> The profile photo field without a modal: the avatar itself grows into the crop, and shrinks back with the face you framed.

Changing a profile photo usually means a modal with a crop box and a slider, and a result that pops in when it closes. Here the avatar is the crop. Choose, drop or paste a photo and the circle grows into the stage, the rest of the photo fading in dimmed around it. The photo moves like one you hold: it follows the finger exactly, resists past an edge the way iOS Photos does and springs back, so the crop never shows a gap, and it keeps the speed you let go with. Pinch, scroll or the slider zoom about where you point, and the zoom rolls to its new value when you let go. Rotate throws a quarter turn with a slight overshoot and the photo settles inside its new bounds. Save goes Saving, Saved, then the stage shrinks back into the circle carrying the face you framed: the same layer all the way, so the new avatar is already there when it lands.

## Install

```bash
npx shadcn@latest add @hairline/avatar-cropper
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `status-button`, `text-morph`, `number-roll`
- Docs and live preview: https://hairlineui.com/ui/avatar-cropper
- Registry item (source): https://hairlineui.com/r/avatar-cropper.json

## Usage

```tsx
import { AvatarCropper } from "@/components/avatar-cropper";

<AvatarCropper
  name={user.name}
  defaultValue={user.avatarUrl}
  onSave={async (photo) => {
    const { url } = await uploadAvatar(photo);
    return url;
  }}
/>
```

## Upload the crop to your storage

onSave gets a square WebP (512px by default) and where the crop sits in the original, in its own pixels, in case you keep originals and crop on the server. Return the stored URL and the avatar shows it; throw and the button reads Try again.

```tsx
"use client";
import { AvatarCropper } from "@/components/avatar-cropper";

export function ProfilePhoto({ user }: { user: { name: string; avatarUrl: string | null } }) {
  return (
    <AvatarCropper
      name={user.name}
      defaultValue={user.avatarUrl}
      onSave={async (photo, area) => {
        const body = new FormData();
        body.append("photo", photo, "avatar.webp");
        body.append("area", JSON.stringify(area));
        const res = await fetch("/api/me/avatar", { method: "PUT", body });
        if (!res.ok) throw new Error("Upload failed");
        const { url } = await res.json();
        return url;
      }}
      onRemove={async () => {
        await fetch("/api/me/avatar", { method: "DELETE" });
      }}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | – | Whose photo: the initials when there's none, and the accessible names. |
| `onSave` | `(photo: Blob, area: CropArea) => Promise<string \| void>` | – | Receives the cropped square and { centerX, centerY, size, rotation } in the original's pixels. Resolve with the stored URL (or nothing to show the crop itself); throw to show the error. |
| `value` | `string \| null` | – | Controlled photo URL. |
| `defaultValue` | `string \| null` | – | Starting photo URL when uncontrolled. |
| `onValueChange` | `(url: string \| null) => void` | – | After a save lands or a removal. |
| `onRemove` | `() => Promise<void> \| void` | – | Shows Remove while there's a photo. |
| `shape` | `"circle" \| "square"` | `"circle"` | "square" crops a rounded square, for workspace and team logos. |
| `size` | `number` | `64` | The avatar's size in px. |
| `outputSize` | `number` | `512` | Side of the saved square in px. |
| `outputType` | `string` | `"image/webp"` | Any type canvas.toBlob encodes, with outputQuality (0.9). |
| `maxSize` | `number` | `10_000_000` | Largest file in bytes; bigger ones are refused with a shake and the limit. |
| `maxZoom` | `number` | `4` | How far past the fit it zooms. |
| `title` | `string` | `"Profile photo"` | Beside the avatar. |
| `hint` | `string` | – | Under the title; it gives way to how to crop while editing. |
| `ref` | `Ref<AvatarCropperHandle>` | – | open(file \| blob \| url) and browse(), e.g. for a photo from your own picker or a camera. |

## States

- **idle**: The avatar with Upload or Replace, and Remove when there's a photo. Hovering dims it and shows a camera; dragging a file over it scales it to 1.06 with a slight overshoot and thickens its ring.
- **open**: The avatar's circle grows into a stage up to 320px in 560ms: it starts as exactly the avatar (the crop circle scaled onto it) and widens its clip to the stage's rounded square while the space below eases open. The dim and the controls fade in 160–220ms later.
- **hold**: Dragging moves the photo one to one; past an edge it gives less the further it goes (iOS's 0.55 resistance) and the thirds appear inside the crop. Pinch and scroll zoom about the fingers or pointer, from the fit to 4x.
- **release**: The photo carries its release speed and slows down; anything outside the bounds springs back critically damped, keeping that speed. The zoom then rolls to its new percent.
- **rotate**: A quarter turn clockwise in 560ms with a slight overshoot; the photo springs inside the new bounds while it turns.
- **save**: Save → Saving → Saved (StatusButton), then the stage shrinks back into the avatar's circle with the crop in it. The new photo is decoded before it lands, so the hand-over is invisible. A failed save shakes the button and reads Try again; the stage stays.
- **cancel**: Escape or Cancel shrinks the stage back and fades it over the last 45% while the old photo (or the initials) fades back in.
- **remove**: Remove → Removing, then the photo dissolves into the initials through a blur.

## What it handles

Changing a profile photo usually means a modal with a crop box and a slider, and a result that pops in when it closes. Here the avatar itself becomes the crop, and the gestures, the export and the saving states are done for you.

- **Choose, drop or paste**: Click the avatar, drop a file on it or paste from the clipboard. A file over maxSize is refused with the limit.
- **Crop like a photo you hold**: Drag, pinch or scroll to zoom up to 4x, and rotate in quarter turns. The crop never shows a gap.
- **Works from the keyboard**: Arrow keys move the photo, plus and minus zoom, R rotates, Enter saves and Escape cancels.
- **Saves a ready-made square**: onSave gets a 512px WebP by default, plus where the crop sits in the original photo.
- **Saving has states**: Save becomes Saving, then Saved. A failure shakes the button, says Try again and keeps the stage open.
- **Circle or square**: Use a circle for people and a rounded square for workspace and team logos.

## Replaces

a crop modal, a crop library, canvas export code, pinch and zoom handling, file drop and paste, upload button states

## Where it fits

- **Profile settings**: Let people change their photo without leaving the page.
- **Onboarding**: Ask for a profile picture while someone is setting up an account.
- **Workspace and team logos**: Crop a rounded square instead of a circle.
- **Creator and seller profiles**: Marketplace and community profiles where a good picture matters.

## Notes

- The avatar is a button: Enter or Space opens the file picker, and paste takes a photo from the clipboard while focus is anywhere in the field. Dropping a file on the avatar or the stage opens it.
- The stage is focusable: arrow keys move the photo (Shift for bigger steps), plus and minus zoom, R rotates, Enter saves and Escape cancels. The zoom slider is a native range input; the zoom is announced when it settles, never while it moves.
- One frame loop with fixed 4ms steps writes transforms to three nested layers (move, zoom, turn) and sleeps once everything is still; React only hears about it then. The layers are promoted while they move and released after, so the photo is redrawn sharp at its new size.
- Only the stage takes touch (touch-action: none); the page itself is never locked. Wheel and trackpad pinch zoom about the pointer and don't scroll the page while over the photo.
- The crop is drawn from the original at full resolution with the same transform you see, so what lands in the circle is what you saved.
- Reduced motion opens and closes in place and the photo goes straight to its bounds instead of springing.

License: MIT (https://hairlineui.com/license#components)
