-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Docs: Update media editor documentation #78617
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
36 changes: 11 additions & 25 deletions
36
packages/media-editor/src/components/rotation-ruler/README.md
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 |
|---|---|---|
| @@ -1,37 +1,23 @@ | ||
| # RotationRuler | ||
|
|
||
| Private to `@wordpress/media-editor`. A horizontal ruler-slider for | ||
| fine-grained numeric values (used for fine-tune rotation in the media | ||
| editor toolbar). Drag the ruler to scrub; the current value is shown | ||
| in an active label sitting over the centered pointer triangle, with | ||
| labelled major ticks running through the strip behind it. A visually | ||
| hidden `<input type="range">` underneath provides keyboard access and | ||
| accessibility. Drag values quantize to multiples of `step`. | ||
| Private controlled ruler input for fine rotation. Pointer drag values are clamped to `min` / `max` and quantized to `step`. Keyboard arrow changes are clamped to `min` / `max` and increment or decrement by `step` (or `step / 2` with Shift). | ||
|
|
||
| ## Usage | ||
|
|
||
| ```tsx | ||
| <RotationRuler | ||
| value={ rotation } | ||
| onChange={ setRotation } | ||
| label={ __( 'Fine rotation' ) } | ||
| min={ -45 } | ||
| max={ 45 } | ||
| value={ rotation } | ||
| onChange={ setRotation } | ||
| label={ __( 'Fine rotation' ) } | ||
| min={ -45 } | ||
| max={ 45 } | ||
| /> | ||
| ``` | ||
|
|
||
| ## Props | ||
|
|
||
| See `index.tsx` for the full `RotationRulerProps` interface. The | ||
| component is controlled (`value` / `onChange`); callers own state and | ||
| clamp/transform values as they wish before passing them in. | ||
|
|
||
| ## Keyboard | ||
|
|
||
| - **← / ↓** — decrement by `step` | ||
| - **→ / ↑** — increment by `step` | ||
| - **Shift + arrow** — half-step (e.g. 0.5° when `step` is 1°), for | ||
| keyboard precision when the integer drag-step is too coarse. | ||
| **Shift + drag** does the same on the pointer. | ||
| - **Home / End** — min / max | ||
| - **PageUp / PageDown** — ±10% of range (native input behaviour) | ||
| - Left / Down: decrement by `step`. | ||
| - Right / Up: increment by `step`. | ||
| - Shift + arrow: use half the configured `step`. | ||
| - Home / End: move to min / max. | ||
| - PageUp / PageDown: use native range input behavior. |
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 |
|---|---|---|
| @@ -1,163 +1,61 @@ | ||
| # Image Editor | ||
|
|
||
| > **Status: internal.** This module is not exported from `@wordpress/media-editor`'s public API. Only code inside `@wordpress/media-editor` should import it, via relative paths (e.g. `../image-editor`). When the module is promoted to the package's public surface, the `@wordpress/media-editor` import paths used in these docs will work. | ||
| > **Status: internal.** This module is not part of `@wordpress/media-editor`'s public API. Import it only from inside the media-editor package, through the local `../image-editor` barrel. | ||
|
|
||
| A modular image editor inside `@wordpress/media-editor`. Two layers: | ||
| The image editor is the cropper engine used by the media editor: | ||
|
|
||
| - **Core** — framework-agnostic state, math, and interaction logic. Pure TypeScript + `gl-matrix`. The export helpers in `core/export/` are browser-only (they use `HTMLCanvasElement` and `Image`), but everything else — reducer, camera math, interaction controller — has no DOM or React dependency. A non-React UI layer (Vue, Svelte, vanilla) can reuse core directly. | ||
| - **React adapter** — thin wrappers over core. The public surface is `<Cropper>`, `useCropperState`, plus the optional `CropperProvider` / `useCropper` context pair. `useInteraction` and `useTransformStyle` exist internally but are not exported. | ||
| - **Core:** state, camera math, containment, source-region, transforms, and canvas export. | ||
| - **React:** `<Cropper>`, `useCropperReducer`, and the optional `CropperProvider` / `useCropper` context wrapper. | ||
|
|
||
| ## Quick start | ||
| `useCropperReducer` does not provide undo/redo. The media editor's composite state layer adds history and sidebar crop options on top of the cropper reducer. | ||
|
|
||
| ## Quick Start | ||
|
|
||
| ```tsx | ||
| import { Cropper, useCropperState } from '../image-editor'; | ||
| import { Cropper, useCropperReducer } from '../image-editor'; | ||
|
|
||
| function ImageCropper() { | ||
| const controller = useCropperReducer(); | ||
|
|
||
| function ImageEditor() { | ||
| const controller = useCropperState(); | ||
| return ( | ||
| <div style={ { width: 600, height: 400 } }> | ||
| <Cropper | ||
| src="https://example.com/photo.jpg" | ||
| controller={ controller } | ||
| showDimming | ||
| showGrid | ||
| freeformCrop | ||
| showDimming | ||
| showGrid="interactive" | ||
| /> | ||
| </div> | ||
| ); | ||
| } | ||
| ``` | ||
|
|
||
| `useCropperState` returns a single `controller` object that bundles the current state and every setter. Pass it to `<Cropper>` as a single prop, and call setters like `controller.setZoom( 2 )` or `controller.snapRotate90( 1 )` from your own toolbars. | ||
|
|
||
| ## Styles | ||
|
|
||
| The cropper's styles are compiled as part of `@wordpress/media-editor`'s SCSS build. Internal callers that render `<Cropper>` inherit them automatically when the package's stylesheet is loaded. All CSS classes use the `wp-media-editor-image-editor` prefix. | ||
|
|
||
| ## Docs | ||
|
|
||
| - [docs/architecture.md](docs/architecture.md) — Data flow, coordinate spaces, and design decisions | ||
| - [docs/recipes.md](docs/recipes.md) — Getting started walkthrough, extension points, and integration patterns | ||
| - [docs/roadmap.md](docs/roadmap.md) — Planned follow-up work and phases | ||
|
|
||
| ## API Reference | ||
|
|
||
| ### React components | ||
|
|
||
| #### `Cropper` | ||
|
|
||
| Main cropper component. Fills its parent container. | ||
|
|
||
| | Prop | Type | Default | Description | | ||
| | ---------------- | ------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| | `src` | `string` | **required** | Image source URL | | ||
| | `controller` | `UseCropperStateReturn` | **required** | The full object returned by `useCropperState()` | | ||
| | `stencil` | `ComponentType<StencilProps>` | `RectangleStencil` | Custom crop area UI | | ||
| | `showGrid` | `boolean` | `false` | Rule-of-thirds grid overlay | | ||
| | `showDimming` | `boolean` | `true` | Dimming overlay outside crop | | ||
| | `showDimensions` | `boolean` | `true` | Live output-dimensions tooltip that follows the active resize handle | | ||
| | `minZoom` | `number` | coverage-aware | Minimum zoom for interactive gestures (wheel, pinch, double-tap). Defaults to the coverage-aware floor, which can drop below `1` when the crop remains covered. | | ||
| | `maxZoom` | `number` | `10` | Maximum zoom for interactive gestures. User-requested zoom is clamped to this maximum while containment still enforces the coverage-aware lower bound. | | ||
| | `aspectRatio` | `number` | — | Fixed aspect ratio (width/height) | | ||
| | `freeformCrop` | `boolean` | `false` | Enable resize handles | | ||
| | `onImageLoaded` | `(size: Size) => void` | — | Image load callback | | ||
| | `onStateChange` | `(state: CropperState) => void` | — | Fires on every state change (high frequency — at pointermove rate during drags). Avoid heavy work in the handler; for commit-style events use `onGestureEnd` instead. | | ||
| | `onGestureStart` | `() => void` | — | Gesture boundary start | | ||
| | `onGestureEnd` | `() => void` | — | Gesture boundary end | | ||
| | `className` | `string` | — | Additional CSS class | | ||
|
|
||
| #### `CropperProvider` / `useCropper()` | ||
|
|
||
| Context wrapper for deep component trees. Wraps `useCropperState` and provides it to descendants via `useCropper()`. | ||
|
|
||
| ### React hooks | ||
| `useCropperReducer` returns a controller object with the current `state`, named setters, `reset`, `isDirty`, and `getCroppedImage`. | ||
|
|
||
| #### `useCropperState( initialState?: Partial<CropperState> ): UseCropperStateReturn` | ||
| ## Internal APIs | ||
|
|
||
| State management hook. Returns a `controller` object with the current state and a named setter for each supported transition. | ||
| ### `Cropper` | ||
|
|
||
| > **Pan vs. crop rectangle**: `setPan` / `state.pan` sets the image _pan offset_ (how the image is translated inside the viewport). `setCropRect` / `state.cropRect` sets the _crop rectangle_ (the region being selected). | ||
| Fills its parent container. Required props are `src` and `controller`. Common options include `freeformCrop`, `aspectRatio`, `showGrid`, `showDimming`, `showDimensions`, `onGestureStart`, and `onGestureEnd`. | ||
|
|
||
| | Field | Type | Description | | ||
| | ----------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------- | | ||
| | `state` | `CropperState` | Current state (read-only) | | ||
| | `setImage` | `(image: CropperState['image']) => void` | Set the loaded image (src + natural size) | | ||
| | `setPan` | `(pan: NormalizedPoint) => void` | Set image pan offset | | ||
| | `setZoom` | `(zoom: number) => void` | Set zoom (clamped 1–10) | | ||
| | `setZoomAtPoint` | `(zoom: number, pan: NormalizedPoint) => void` | Set zoom and pan together for focal-point zoom | | ||
| | `setRotation` | `(degrees: number) => void` | Set rotation (normalized 0–360) | | ||
| | `setFlip` | `(flip: Flip) => void` | Set flip state | | ||
| | `snapRotate90` | `(direction: 1 \| -1) => void` | 90° snap rotation | | ||
| | `setCropRect` | `(rect: NormalizedRect) => void` | Set crop rectangle | | ||
| | `settleCrop` | `() => void` | Settle the crop rect after a resize drag (typically from `onResizeEnd`) | | ||
| | `applyOperation` | `(op: TransformOperation) => void` | Apply a pipeline operation | | ||
| | `reset` | `(state?: Partial<CropperState>) => void` | Reset to initial or given state | | ||
| | `isDirty` | `boolean` | Whether state differs from initial | | ||
| | `getCroppedImage` | `(mime?: string, quality?: number) => Promise<Blob>` | Export as Blob. Throws on load/CORS/context failure — wrap in try/catch to recover. | | ||
| ### `useCropperReducer( initialState? )` | ||
|
|
||
| The controller does not expose the reducer dispatch. Use the named setters or `applyOperation()` to change state. | ||
| Pure React state hook for the cropper reducer. Returns a `CropperController`: current state, named setters, `reset`, `isDirty`, and `getCroppedImage`. | ||
|
|
||
| ### Source region | ||
| ### `CropperProvider` / `useCropper` | ||
|
|
||
| #### `getSourceRegion( state, imageSize ): SourceRegion` | ||
| Convenience context wrapper around `useCropperReducer` for component trees that need shared cropper state. | ||
|
|
||
| Converts crop state to source-pixel coordinates: `{ x, y, width, height, rotation, flip, zoom }`. For server-side processing (FFmpeg, ImageMagick, etc.). | ||
| ## Core Helpers | ||
|
|
||
| #### `getSourceRegionPercent( state, imageSize ): SourceRegionPercent` | ||
| The local barrel also exposes helpers for reducer composition, source-region calculation, pipeline replay, and canvas export. Use named setters or `TransformOperation` values for normal state changes. Use reducer actions only when composing a controller such as `useMediaEditorState()`. | ||
|
|
||
| Same as `getSourceRegion` but returns percentages (0–100): `{ x, y, width, height }`. Compatible with the WordPress REST API attachments `/edit` endpoint. | ||
|
|
||
| ### Export | ||
|
|
||
| #### `exportCroppedImage( src, state, mimeType?, quality? ): Promise<Blob>` | ||
|
|
||
| End-to-end: load image, render with transforms, export as Blob. Browser-only (needs `HTMLCanvasElement`). | ||
|
|
||
| Rejects on: | ||
|
|
||
| - **Image load failures** (network error, 404) — the native load error is propagated. | ||
| - **CORS / tainted canvas** — if the source doesn't set `Access-Control-Allow-Origin`, `canvas.toBlob()` rejects because the canvas is tainted. Fix at the server: send permissive CORS headers. | ||
| - **Missing canvas context** — throws with a descriptive `Error`. | ||
|
|
||
| Wrap in `try/catch` to distinguish failure modes. | ||
|
|
||
| #### `applyToCanvas( source: CanvasImageSource, imageSize, state ): HTMLCanvasElement` | ||
|
|
||
| Applies transforms to any `CanvasImageSource` (image, canvas, video frame, offscreen canvas). For multi-step editing pipelines. | ||
|
|
||
| ### Pipeline | ||
|
|
||
| #### `stateFromPipeline( operations: TransformOperation[] ): CropperState` | ||
|
|
||
| Replays a sequence of operations from default state. Pure function, no DOM needed. For headless/server-side processing. | ||
|
|
||
| #### `applyOperationToState( state, operation ): CropperState` | ||
|
|
||
| Applies a single operation to an existing state. | ||
|
|
||
| ### Types | ||
|
|
||
| | Type | Description | | ||
| | ----------------------- | --------------------------------------------------------------------------------- | | ||
| | `CropperState` | `{ image, pan, zoom, rotation, flip, cropRect, basePan, baseZoom, baseRotation }` | | ||
| | `UseCropperStateReturn` | The full shape returned by `useCropperState()`: state + setters | | ||
| | `CropperProps` | Props for the `<Cropper>` component | | ||
| | `StencilProps` | Contract for pluggable stencil components | | ||
| | `TransformOperation` | `{ type: 'crop' \| 'rotate' \| 'flip' \| 'zoom', ... }` | | ||
| | `NormalizedPoint` | `{ x: number, y: number }` in [0,1] space | | ||
| | `NormalizedRect` | `{ x, y, width, height }` in [0,1] space | | ||
| | `Size` | `{ width: number, height: number }` | | ||
| | `Flip` | `{ horizontal: boolean, vertical: boolean }` | | ||
| | `SourceRegion` | `{ x, y, width, height, rotation, flip, zoom }` in source pixels | | ||
| | `SourceRegionPercent` | `{ x, y, width, height }` as percentages (0–100) | | ||
| | `AspectRatioPreset` | `{ label: string, value: number }` | | ||
| ## Styles | ||
|
|
||
| `CropperAction` (the reducer's action union) is internal. Drive state through the named setters on the controller object. | ||
| Styles are bundled through the media-editor stylesheet. Classes use the `wp-media-editor-image-editor` prefix. | ||
|
|
||
| ### Constants | ||
| ## More | ||
|
|
||
| | Constant | Value | Description | | ||
| | ----------------------- | ----- | ------------------------------------------------------ | | ||
| | `DEFAULT_STATE` | — | Default `CropperState` | | ||
| | `DEFAULT_ASPECT_RATIOS` | Array | Preset aspect ratios (Free, Original, 1:1, 16:9, etc.) | | ||
| | `ORIGINAL_ASPECT_RATIO` | `-1` | Sentinel value for "use image's original ratio" | | ||
| - [docs/architecture.md](docs/architecture.md) | ||
| - [docs/recipes.md](docs/recipes.md) | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I removed all this because the image cropper is still internal. Seemed premature to document the API before the package is public.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also to avoid having to come back and change things before the feature is settled.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed 👍