Repository navigation
feat(mosaic): add ImageCropper primitive #10783
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
+1,504
−0
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
dcd2fc0
feat(mosaic): add ImageCropper primitive
alexcarpenter 6b52ec4
docs(mosaic): list ImageCropper in reuse before you write
alexcarpenter d0ec8a7
fix(mosaic): size an image cropper image that loaded before it mounted
alexcarpenter 09960bf
docs(swingset): add ImageCropper primitive page
alexcarpenter f80d585
fix(mosaic): address ImageCropper review feedback
alexcarpenter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| --- | ||
| --- |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
|
|
||
| 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`. | ||
70 changes: 70 additions & 0 deletions
70
packages/mosaic/src/primitives/image-cropper/__tests__/crop-image.browser.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
78 changes: 78 additions & 0 deletions
78
packages/mosaic/src/primitives/image-cropper/__tests__/crop.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.