Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/mosaic-image-cropper-primitive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
1 change: 1 addition & 0 deletions packages/mosaic/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ Most problems a feature hits already have a shared answer. Find the line for you
- The seconds left on a resend cooldown, for display → `useResendSeconds` (`src/hooks/`), from a `resendAvailableAt` time kept in the machine
- An avatar or logo row: picker, drop target, Upload button or manage menu → `AvatarUpload` (`src/blocks/avatar-upload/`), laid out by the caller
- Any other file picker or drop zone, such as a metadata or key file → `FileUpload` (`src/primitives/file-upload/`), see its `README.md`
- Cropping an image to a square: pan, zoom, rotate, then draw the result → `ImageCropper` and `cropImage` (`src/primitives/image-cropper/`), see its `README.md`
- An inline notice inside content: info, warning, error or success → `Banner` (`src/components/banner/`); a form-level error on a card uses `Card.Banner`
- Siblings that slide when an item is added or removed → `useLayoutAnimation` (`src/primitives/hooks/`)
- An input that reformats as the user types without moving the caret → `useFormattedInput` (`src/primitives/hooks/`)
Expand Down
116 changes: 116 additions & 0 deletions packages/mosaic/src/primitives/image-cropper/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# ImageCropper

A headless image cropper. The user pans the image by dragging or with the arrow keys, zooms with the
wheel, a pinch, the keyboard, a slider or step buttons, turns it a quarter at a time, and resets it.
The crop is a square. `cropImage` draws the square the user chose into a new image.

## When to Use

- Cropping a picked image to a square before uploading it, such as an avatar or a logo.

The primitive emits zero styles. The caller sizes the frame, draws any mask over it, and styles the
controls through `data-*` attributes.

## Usage

```tsx
import { useState } from 'react';

import { type Crop, cropImage, ImageCropper, INITIAL_CROP } from '../../primitives/image-cropper';

function Cropper({ src, onSave }: { src: string; onSave: (blob: Blob) => void }) {
const [crop, setCrop] = useState<Crop>(INITIAL_CROP);
Comment thread
alexcarpenter marked this conversation as resolved.
Resolved

return (
<ImageCropper.Root
src={src}
value={crop}
onValueChange={setCrop}
>
<ImageCropper.Viewport aria-label='Crop. Drag or use the arrow keys to move, plus and minus to zoom.'>
<ImageCropper.Area>
<ImageCropper.Image />
</ImageCropper.Area>
</ImageCropper.Viewport>
<ImageCropper.ZoomOut aria-label='Zoom out'>−</ImageCropper.ZoomOut>
<ImageCropper.Zoom aria-label='Zoom' />
<ImageCropper.ZoomIn aria-label='Zoom in'>+</ImageCropper.ZoomIn>
<ImageCropper.Rotate>Rotate</ImageCropper.Rotate>
<ImageCropper.Reset>Reset</ImageCropper.Reset>
<button onClick={async () => onSave(await cropImage(src, crop, { size: 512, type: 'image/png' }))}>Save</button>
</ImageCropper.Root>
);
}
```

`Area` is optional. Without it the whole `Viewport` is the crop. With it, the crop is the `Area`, and
the `Viewport` around it shows the rest of the image for context. Drags are measured against the
`Area`, so the image follows the pointer either way.

## Parts

| Part | Default Element | Description |
| ----------------------- | ---------------------- | ---------------------------------------------------------------------- |
| `ImageCropper.Root` | none | Owns the crop and the image size, provides context |
| `ImageCropper.Viewport` | `<div>` | The frame: pans on drag and arrow keys, zooms on wheel, pinch and keys |
| `ImageCropper.Area` | `<div>` | The square that is cropped, when it is smaller than the frame |
| `ImageCropper.Image` | `<img>` | The image, placed by the crop. Reports its size on load |
| `ImageCropper.Zoom` | `<input type="range">` | Sets the zoom, from 1 to `maxZoom` |
| `ImageCropper.ZoomIn` | `<button>` | Zooms in one step. Disabled at `maxZoom` |
| `ImageCropper.ZoomOut` | `<button>` | Zooms out one step. Disabled at 1 |
| `ImageCropper.Rotate` | `<button>` | Turns the image a quarter clockwise |
| `ImageCropper.Reset` | `<button>` | Returns to `INITIAL_CROP` |

Every control stays disabled until the image has loaded, because the crop limits depend on its size.

## Props

### `ImageCropper.Root`

| Prop | Type | Default | Description |
| --------------- | ---------------------- | -------------- | ----------------------------------------------- |
| `src` | `string` | — | The image to crop, such as an object URL |
| `value` | `Crop` | — | Controlled crop |
| `defaultValue` | `Crop` | `INITIAL_CROP` | Initial crop (uncontrolled) |
| `onValueChange` | `(crop: Crop) => void` | — | Called on every pan, zoom, turn and reset |
| `maxZoom` | `number` | `4` | Largest zoom, as a multiple of the cover scale |
| `disabled` | `boolean` | `false` | Ignores every gesture and disables the controls |

A `Crop` is `{ x, y, zoom, rotation }`. `x` and `y` move the image centre from the frame centre, as a
fraction of the frame. `zoom` 1 is the smallest scale that still covers the frame. `rotation` is `0`,
`90`, `180` or `270`. The crop is always clamped so the image covers the frame.

Other parts take no additional props. All parts except `Root` accept a `render` prop and standard
HTML attributes for their default element.

### `cropImage(src, crop, { size, type })`

Returns a `Promise<Blob>` holding the square the crop shows, `size` pixels wide, encoded as `type`.
It draws to a canvas, so an animated image keeps only its first frame.

## Keyboard

On a focused `Viewport`:

| Key | Action |
| ---------- | ------------------------ |
| Arrow keys | Pan. Hold Shift for more |
| `+` / `=` | Zoom in one step |
| `-` / `_` | Zoom out one step |
| `0` | Reset |

## Data Attributes

| Attribute | Applies To | Description |
| --------------- | ---------------------------------------------- | ----------------------------------- |
| `data-dragging` | Viewport | Present while a pointer is dragging |
| `data-loaded` | Image | Present once the image has loaded |
| `data-disabled` | Viewport, Zoom, ZoomIn, ZoomOut, Rotate, Reset | Present when the part is disabled |

## ARIA

- `Viewport` has `role="application"` so screen readers pass the arrow keys through. Give it an
`aria-label` that names the keys. It leaves the tab order until the image has loaded.
- `Image` has an empty `alt`, because the `Viewport` label describes it.
- `ZoomIn`, `ZoomOut`, `Rotate` and `Reset` render `<button type="button">`. Give icon-only buttons an
`aria-label`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest';

import { INITIAL_CROP } from '../crop';
import { cropImage } from '../crop-image';

const RED = [255, 0, 0];
const BLUE = [0, 0, 255];

function halves(width: number, height: number): string {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
if (!context) {
throw new Error('no canvas');
}
context.fillStyle = 'rgb(255 0 0)';
context.fillRect(0, 0, width / 2, height);
context.fillStyle = 'rgb(0 0 255)';
context.fillRect(width / 2, 0, width / 2, height);
return canvas.toDataURL('image/png');
}

async function pixels(blob: Blob) {
const bitmap = await createImageBitmap(blob);
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
const context = canvas.getContext('2d');
if (!context) {
throw new Error('no canvas');
}
context.drawImage(bitmap, 0, 0);
const at = (x: number, y: number) => [...context.getImageData(x, y, 1, 1).data.slice(0, 3)];
return { width: bitmap.width, height: bitmap.height, at };
}

describe('cropImage', () => {
it('draws the square the frame shows at the requested size and type', async () => {
const blob = await cropImage(halves(200, 100), INITIAL_CROP, { size: 64, type: 'image/png' });
const image = await pixels(blob);

expect(blob.type).toBe('image/png');
expect([image.width, image.height]).toEqual([64, 64]);
expect(image.at(8, 32)).toEqual(RED);
expect(image.at(56, 32)).toEqual(BLUE);
});

it('follows a pan', async () => {
const blob = await cropImage(halves(200, 100), { ...INITIAL_CROP, x: 0.5 }, { size: 64, type: 'image/png' });
const image = await pixels(blob);

expect(image.at(8, 32)).toEqual(RED);
expect(image.at(56, 32)).toEqual(RED);
});

it('follows a quarter turn', async () => {
const blob = await cropImage(halves(200, 100), { ...INITIAL_CROP, rotation: 90 }, { size: 64, type: 'image/png' });
const image = await pixels(blob);

expect(image.at(32, 8)).toEqual(RED);
expect(image.at(32, 56)).toEqual(BLUE);
});

it('clamps a crop that would leave part of the square outside the image', async () => {
const blob = await cropImage(halves(100, 100), { ...INITIAL_CROP, x: 0.5 }, { size: 64, type: 'image/png' });
const image = await pixels(blob);

expect(image.at(8, 32)).toEqual(RED);
expect(image.at(56, 32)).toEqual(BLUE);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { describe, expect, it } from 'vitest';

import { clampCrop, type Crop, INITIAL_CROP, pixelCrop, rotateCrop, zoomCrop } from '../crop';

const wide = { width: 200, height: 100 };
const tall = { width: 100, height: 200 };
const square = { width: 100, height: 100 };
const maxZoom = 4;

function crop(overrides: Partial<Crop>): Crop {
return { ...INITIAL_CROP, ...overrides };
}

describe('clampCrop', () => {
it('lets a wide image pan sideways until its edge meets the frame', () => {
expect(clampCrop(crop({ x: 2, y: 2 }), wide, maxZoom)).toEqual(crop({ x: 0.5, y: 0 }));
expect(clampCrop(crop({ x: -2 }), wide, maxZoom)).toEqual(crop({ x: -0.5 }));
});

it('lets a tall image pan up and down until its edge meets the frame', () => {
expect(clampCrop(crop({ x: 2, y: -2 }), tall, maxZoom)).toEqual(crop({ x: 0, y: -0.5 }));
});

it('widens the pan range as the image zooms in', () => {
expect(clampCrop(crop({ x: 5, y: 5, zoom: 2 }), square, maxZoom)).toEqual(crop({ x: 0.5, y: 0.5, zoom: 2 }));
});

it('keeps zoom between cover and the max', () => {
expect(clampCrop(crop({ zoom: 0.5 }), square, maxZoom).zoom).toBe(1);
expect(clampCrop(crop({ zoom: 9 }), square, maxZoom).zoom).toBe(4);
});

it('swaps the pan axes for an image turned a quarter', () => {
expect(clampCrop(crop({ x: 2, y: 2, rotation: 90 }), wide, maxZoom)).toEqual(crop({ x: 0, y: 0.5, rotation: 90 }));
});
});

describe('zoomCrop', () => {
it('keeps the point under the centre of the frame in place', () => {
expect(zoomCrop(crop({ x: 0.25, zoom: 2 }), 4, square, maxZoom)).toEqual(crop({ x: 0.5, zoom: 4 }));
});

it('pulls the pan back inside the image when zooming out', () => {
expect(zoomCrop(crop({ x: 1.5, zoom: 2 }), 1, wide, maxZoom)).toEqual(crop({ x: 0.5, zoom: 1 }));
});
});

describe('rotateCrop', () => {
it('turns the image a quarter clockwise around the centre of the frame', () => {
expect(rotateCrop(crop({ x: 0.5 }), wide, maxZoom)).toEqual(crop({ x: 0, y: 0.5, rotation: 90 }));
});

it('wraps back to upright after four turns', () => {
expect(rotateCrop(crop({ rotation: 270 }), square, maxZoom).rotation).toBe(0);
});
});

describe('pixelCrop', () => {
it('takes the whole of a square image at rest', () => {
expect(pixelCrop(INITIAL_CROP, square)).toEqual({ x: 0, y: 0, size: 100 });
});

it('takes the middle of a wide image at rest', () => {
expect(pixelCrop(INITIAL_CROP, wide)).toEqual({ x: 50, y: 0, size: 100 });
});

it('takes the left side when the image is panned right', () => {
expect(pixelCrop(crop({ x: 0.5 }), wide)).toEqual({ x: 0, y: 0, size: 100 });
});

it('takes a smaller square when zoomed in', () => {
expect(pixelCrop(crop({ zoom: 2 }), wide)).toEqual({ x: 75, y: 25, size: 50 });
});

it('measures from the turned image', () => {
expect(pixelCrop(crop({ y: 0.5, rotation: 90 }), wide)).toEqual({ x: 0, y: 0, size: 100 });
});
});
Loading
Loading