Repository navigation
Image Editor: Add applyImageEdit public function - #86665
Conversation
🤖 PR meta 🤖🎉 PropsIf you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message. To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. Props Bot commandsYou can trigger Props Bot actions by commenting on this PR:
Updated as activity occurs, without notifying anyone named here. Add the 📦 Bundle sizeSize Change: -73 B (0%) Total Size: 8.71 MB 📦 View Changed
⚡ PerformanceShow the resultsClient side metrics exclude the server response time. front-end-block-theme
front-end-classic-theme
media-processing
media-upload
post-editor
site-editor
🏁 Flaky testsSome tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information. As a user I want to be able to add multiple close buttons so that users can close the overlay from different positions in
|
andrewserong
left a comment
There was a problem hiding this comment.
I really like the ideas here! Conceptually, allowing a simple applyImageEdit function to pass along instructions to the image editor is a great idea. And I can imagine this being combined with tools or abilities (as you mention) eventually so that we can have clever programmatic or AI-enabled interactions.
One wrinkle, though, is that when interacting with the image editor via the UI, we naturally contain things to do a best effort to perform an action on behalf of a user. Or to put it more plainly, we allow fine-grained rotation and then contain / zoom in accordingly to make sure everything still fits. Whereas here, if I give it a bare fine-grained rotation like 5, I get an error:
Should this function (applyImageEdit) bake in the containment logic so that the consumer is effectively driving the image editor UI, rather than needing to be responsible for containment on its own?
Another option, we could have applyImageEdit default to including the containment, and have a third optional options param that allows a consumer to switch that off, enable a strict mode, or perhaps eventually, even allow crops that go outside the image editor in order to bake in a background color of some kind? The latter wouldn't be for this PR — just brainstorming some ideas for how this function could work over time.
For now, I think the main thing we'd want to add is the automatic containment so that consumers don't need to worry about it.
|
|
||
| // What each rejection means, from the `ImageEditRejection` docs. | ||
| const REJECTIONS: Record< | ||
| Extract< ApplyImageEditResult, { rejected: unknown } >[ 'rejected' ], |
There was a problem hiding this comment.
Rather than having to extract here, would it be worth exporting ImageEditRejection to make it easier for consumers to work with?
There was a problem hiding this comment.
Yes, I can see how that type would be handy. Good call.
Thanks for bringing this up. It was something I did think about, and I think in general it would be nice to be able to fit the crop to the bounding area by default. In other words, it should do exactly what the rotate control does. Here's where my brain was going for the record: I was imagining an agent-feedback loop, or someone trying to restore a previously described edit, where we wouldn't want to change a crop silently. That said, I agree with the idea that anyone using this API should be able to decide whether they want this at all, like you said, it might be a layered image on top of some background. This relates indirectly to circle cropping too, where there's no choice but to have transparent corners. So, here's what I think we can do:
Does that make sense? |
Sure does! I think your "this PR" notes will cover the majority use case (essentially use an AI tool to replicate the behaviour of using the existing UI tools).
For this, my weakly held opinion is that it's kind of a nice-to-have. I.e. this could be part of either the circle-crop thingie as you mention, but it also sort of forms part of being able to adjust the size of the canvas, which sounds like a new feature to me rather than just about API changes. I think the point I'm trying to make here is that this sounds like "feature" territory rather than "build out the image-editor package's API so plugins or agents can use the existing cropper". Not at all a bad idea to pursue that, I mostly mention it as it can be easy to get into a "one more thing" situation with APIs and so from my perspective I'd say that the "this PR" scope is already good. All that said, one of the things I'm interested in with all this is seeing how the image cropper might look and feel once it's hooked up to client-side abilities or possibly WebMCP. It'd be interesting to see, for example, in the block editor, can we go from an uploaded 4:3 image of a landscape with a horizon that isn't level and pass a prompt in a browser's chat window (e.g. Gemini in Chrome), and have it:
E.g. the prompt might be "level out the horizon on this image and crop it to 16:9", and based on the tools exposed, it can fire off the (hopefully simple) tools to do just that. When it comes to containment, the main question on my mind in the above agent loop is whether it makes it easier or harder to complete the task if containment is applied by default. My hunch is that it'll be easier with containment happening automatically, in the same way that it's easier for a human user to not have to perform a manual crop when fine-grain rotating something. In any case, this is all a very long way of saying a big +1 to the idea of making sure the API plays nicely with agents! Ideally we're building a cropper that works great for humans and programatic applications. Once this PR is in, it might be fun to try out a proof of concept demo with WebMCP or the like to get a feel for the overall shape of it, test out what we will or won't need? (Also a necessary caveat with all the above — I have no idea what I'm talking about when it comes to WebMCP other than having watched a 30 minute demo covering what it can do, so please take my opinions here with a grain of salt 😄) |
|
Great feedback and ideas, thanks @andrewserong
That sounds like a great, and probably necessary, stepping stone. Like you say, we'll probably turn up things we didn't anticipate, e.g., agents trying to perform other operations that the core library doesn't offer (scale comes to mind) who knows?! I'll chalk that up as the next phase to look into before taking it furhter.
Yes, well put. Specifically with the canvas on the page, I think it'll be a good bridge between agent and what the user is seeing on the page. Agree on the nice-to-have point, and it's not something we should rush into now. My intention was to really provide an entry point to the underlying crop operations for any canvas or crop operation, so a consumer (or agent) can decide that they don't care about filling the canvas. I'm imagining it being part of a tool chain, e.g., so a consumer might crop an image as part of a wider design imperative like "rotate the image, make it fix within the boundary (no zoom) and paint the transparent pixels green". We don't need this now, and I like your call of testing |
|
I set up a local testing env in node using Here's the report: Agent test of
|
| # | Prompt | Sonnet | Opus | What happened |
|---|---|---|---|---|
| 11 | "Straighten it a bit, the horizon's off." | Asked | Asked | Both said they cannot see the photo and asked which way and how far. Opus offered to start at 2° if the person prefers. |
| 12 | "Crop out the sky." | Asked | Asked | Both asked where the horizon is, and offered to accept a fraction or a pixel row. |
| 13 | "Zoom in on the left side." | Done, left half | Done, left half at middle height | Two readings of "zoom in". Sonnet cropped the left half at full height. Opus kept 16:9 and took 800×450 from the left. Both said they guessed. Sonnet's first call was the top-left quarter by mistake. It caught the slip from its own arguments, before any read-back, and redid it. |
| 14 | "Make it portrait for Instagram." | Done, 4:5 | Done, 4:5 | Both locked the ratio to 0.8 and took the editor's default crop, 720×900, centered. Both said the subject may be off-center. Opus noted Instagram's 1080×1350 and the upscale. |
| 15 | "Make it square." | Done, 900×900 | Done, 900×900 | Both locked the ratio to 1. Sonnet took the default crop. Opus also applied the crop in strict mode. Opus then pasted the full raw state JSON to the person, including basePan, baseZoom and baseRotation. |
| 16 | "Rotate it, it's sideways." | Done, 90° | Done, 90° | Both guessed clockwise, said so, and offered 270° if it comes out upside down. |
| 17 | "Take a bit off the edges." | Done, 5% each side | Done, 5% each side | Same default from both. Sonnet did not read the size back and said so. Opus did and got 1439.9999999999998 by 809.9999999999999. |
| 18 | "Crop it to the top half. Actually no, undo that." | Nothing applied | Nothing applied | Both read the retraction and did not apply the crop. No tool was needed. |
What this set showed
| Observation | Runs | Shared by both models |
|---|---|---|
| Vision-dependent asks ended in a question to the person, not a guess | 4 of 4 (11, 12) | Yes |
| Vague asks got a stated default: 5% off edges, 4:5 for Instagram, left half, 90° clockwise, and an offer to adjust | 10 of 10 (13 to 17) | Yes |
| Used the ratio lock, not a computed crop, to get "square" or "portrait" | 4 of 4 (14, 15) | Yes |
| Said the tools "only build a state" and asked how to apply it to the open photo | 7 of 16 | Yes |
| Noted that a fresh state loses edits already made in the editor | 1 of 16 | Opus |
| Pasted the raw state JSON, with internal fields, to the person | 1 of 16 | Opus |
| Float noise in a read-back, now also for a plain axis-aligned crop | 3 of 16 | Yes |
| Wrong final edit | 0 of 16 |
Follow-ups
None changes #86665. Items 1 and 3 repeat the precise set, now with more evidence.
- Snap float noise at the read-back boundary.
getOutputSizereturned 1439.9999999999998 for a 5% crop with no rotation. Round values within a small tolerance of a whole number or of zero ingetImageEditandgetOutputSize. Small, separate PR. - The entry point needs three calls, not one. Describe the current edit, so the agent starts from what the person already did rather than from a fresh state. Apply an edit and commit it as one undo step, which is the "apply to the open photo" the agents kept asking for. And set or clear the ratio lock, because both models reached for the lock to make a square or a portrait, and
ImageEdithas no ratio in it. - Keep the state opaque to the agent, and stop the base fields escaping the public state. One run pasted
basePan,baseZoomandbaseRotationto the person. The entry point should return edits, never states. The leak of undeclared fields predates this PR and wants its own decision. - Design for the agent not seeing the picture. Half the plain prompts could not be done without the person's answer or a look at the canvas. The loop that works is: apply a stated guess, the person looks, the person says "a bit more" or "the other way", one undo step takes the guess back. The entry point should make that loop cheap: apply returns the edit as it now stands, undo is one step, and the defaults the agent chose are stated in words.
- Not needed: a
fittedflag, an undo in the package API, a pixel-to-fraction helper. Both models converted pixels and fractions without trouble in both sets.
Previous run
Agent test summary
Setup. A scratch MCP server wraps the built package with four tools: createImageEditorState, applyImageEdit, getImageEdit, getOutputSize. Tool descriptions are the README text and nothing else. Each scenario ran as a fresh claude -p with only those tools. Eight scenarios, Sonnet and Opus, 16 runs The photo is 1600 by 900. "Correct" means the final edit and the reported region or size match the task.
Results
| # | Scenario | Sonnet | Opus | What happened |
|---|---|---|---|---|
| 1 | Largest centered square | Correct | Correct | Both locked the ratio to 1. Sonnet never called applyImageEdit: it read back the editor's default square and reported it. Opus applied { x: 0.21875, width: 0.5625 } in strict mode. |
| 2 | Left half, then a quarter turn | Correct | Correct | Both re-expressed the crop in the turned frame as the top half. Sonnet did it in one call. Opus did two, both strict. |
| 3 | 800×600 at pixel 100, 50 | Correct | Correct | Both divided by the image size, applied strict, and confirmed 800×600 by reading the size back. |
| 4 | Half width starting at 80 percent | Correct | Correct | Both tried strict first and got outside-image. Sonnet stopped and offered options. Opus re-applied in default mode, read back x: 0.5, and reported the slide. |
| 5 | 800×400 region under a square lock | Correct | Correct | Both got locked-ratio in strict mode, re-applied in default mode, read back 800×800 at y 50 to 850, and said it is not what was asked. |
| 6 | Straighten by 5 degrees | Correct | Correct | Both read back the inscribed crop and the size 1389.9 by 781.8, and explained what is lost. |
| 7 | Mirror, then a quarter turn | Correct | Correct | Read-back matched. Both noticed the state object holds rotation: 270 and explained it as the flip's sign rule. |
| 8 | Crop, rotate, undo the rotation | Correct | Correct | Sonnet re-applied the crop without a rotation. Opus kept the earlier state and returned to it. Sonnet remapped the crop to the turned frame correctly this time, so the first run's error did not recur. |
Patterns across both runs (32 transcripts)
| Observation | Runs | Shared by both models |
|---|---|---|
Chose strict: true without being told to, then fell back to default mode to show the fit |
24 of 28 crop calls | Yes |
Spent a paragraph on float noise in read-back values such as -6.8e-8, 2.3e-9 and 900.0000000000001 |
28 of 32 | Yes |
Reconciled internal fields in the state JSON (rotation: 270, baseRotation, cropRect.y) with the read-back edit |
6 of 32 | Yes |
| Reused crop numbers across a rotation, framing the wrong region | 1 of 32, first run only | No, Sonnet once |
| Misread the crop frame, the replace rule, or a rejection reason | 0 of 32 |
Follow-ups
In priority order. None changes #86665.
- Snap float noise at the read-back boundary. In
getImageEditandgetOutputSize, round a value within a small tolerance of zero or of a whole number to that number. Every agent handled the noise, and every agent explained it to the person. Small, separate PR. - Keep the state opaque to an agent. The entry point for the media editor modal should hand back an id or a token, never the state object. Six runs went off reconciling
rotation: 270with90. A design rule for the follow-up PR, not a package change. - Stop internal base fields leaking from the public state. The object the package returns carries
basePan,baseZoomandbaseRotation, whichImageEditorStatedoes not declare. Anyone serialising a state gets them. Predates this PR. Decide whether to strip them at the public boundary or declare them. - Say in the README when to use strict. (Added in aa6df6d) Both models reached for it unprompted in nearly every crop and used the rejection to decide what to do next. One sentence: code that needs the crop taken as given should pass strict and handle the rejection.
- No
fittedflag. The runs argue against one. The pattern agents invented, strict first and fit on purpose, already tells them when fitting happened. - No undo in the package API. Both approaches worked with states as values. Undo belongs to the modal's entry point, as planned.
|
Oh, interesting! Thanks for giving that a try. One of the reasons I think WebMCP will be interesting to try is that I think the web versions can see what's happening in the browser, so they might have an easier time working with the tools? So we'll likely wind up with two agent-based use cases: headless (where it can't see what's happening) and those that can 🤔 |
I'm not 100% sure we'd get "sight" out the box, if you mean an image/screenshot of the canvas reaching the model. WebMCP will offer whatever tools to the agent we register with it. An agent could take screenshots of the page for itself I guess too. So after this PR the package exposes pure functions (not a state ): you pass a state in, you get an edit or a new state out. What I do have planned is access to the canvas state, which is kinda the same I think. Right now only the consumer has access to its own session state, so we'll need to work out an entry point for that. I think we can register MCP from within the consumer's state provider, e.g, in const context = navigator.modelContext;
context.registerTool( {
name: 'get_image_edit',
description: 'The current flip, rotation and crop of the open image, and its output size.',
inputSchema: { type: 'object', properties: {} },
execute: () => ( {
edit: session.getImageEdit(),
size: getOutputSize( session.imageEditor.state ), // we have access to the current session's state here, so we feed it to the tool call
} ),
} );
// Agent calls: get_image_edit
// Agent gets: { edit: { rotation: 5, crop: { x: 0.084, y: 0.123, width: 0.831, height: 0.755 } }, size: { width: 1390, height: 782 } }So the next step is to try that. I'm not sure anything needs to change in this PR for the next steps to take place, but I can definitely try to set it up locally to see. It looks like I can "simulate" a test locally without setting all this up using storybook. There's the "Apply an Edit " story so the agent looks at the canvas, types JSON into the box, clicks Apply, looks again. I did that in the mean time. Posting below for the record. No need to read all the slops! Agent test of `applyImageEdit` with sightSetup. The same eight plain prompts, run against the Storybook story "Apply an Edit" in a headless Chrome through a Playwright MCP server. The agent can screenshot the page, type into the "Edit to apply" box and click Apply, and read the edit the editor holds from the text under the canvas. The prompt tells it to use the box and not the canvas handles, because a first run showed Sonnet zooming and panning with the keyboard instead. The story's sample picture is not a landscape photo: it is a 1000 by 1464 upright scan of an 1887 print, a grid of labelled illustrations. That turned out to matter. Sonnet and Opus, 16 runs. Results
What sight changed
Two things about the harness, not the API:
Follow-upsNothing new for the package. The list from the two earlier sets stands, with one change of emphasis.
|
Hmm, just thinking further on this. We could also expose ways to get the image (original for benchmark) and its cropped preview (for checking what has been done). Lots of ideas to test here! |
|
WebMCP results (not perfect env, and just more data dump. feel free to ignore) 😄 ExampleAgent test of
|
| # | Prompt | Sonnet | Opus | What happened |
|---|---|---|---|---|
| 11 | "Straighten it a bit, the horizon's off." | Declined | Declined | Both loaded the image pixels in the page and measured the grid lines: tilt under 0.1°. Both said rotating would only crop and soften, and asked for an angle if one was meant. |
| 12 | "Crop out the sky." | Declined | Declined | No sky in the print. Opus offered alternatives: trim the title strip, or zoom in on one cell. |
| 13 | "Zoom in on the left side." | Done, left half | Done, left half | apply_image_edit with { crop: { x: 0, y: 0, width: 0.5, height: 1 } }, Opus in strict mode. Both reported 500×1464. |
| 14 | "Make it portrait for Instagram." | Done, 4:5 | Done, 4:5 | Both read the size from get_image_edit and computed height: 1250/1464, centered. Opus said what is lost: the title strip. |
| 15 | "Make it square." | Done, 1000×1000 | Done, 1000×1000 | Both computed height: 1000/1464, centered. Sonnet used strict and said the editor took it as given. Opus listed the rows lost top and bottom. |
| 16 | "Rotate it, it's sideways." | Declined | Declined | Both looked, saw upright text, and asked which way. |
| 17 | "Take a bit off the edges." | Done, 5% | Done, 5% | Both strict. Both read the current edit first "to preserve any existing parts", then applied. |
| 18 | "Crop it to the top half. Actually no, undo that." | Applied, then reset_image |
Nothing applied | Sonnet did both steps and confirmed with get_image_edit. Opus read the retraction. |
Compared with the two earlier sets
| Blind MCP | Clicking the story | WebMCP tools | |
|---|---|---|---|
| Wrong final edit | 0 of 16 | 0 of 16 | 0 of 16 |
| Vision-dependent asks | Asked the person | Looked, declined | Looked, declined; two runs measured tilt from pixels |
| Used the API rather than the UI | Only option | Had to be told | Had to be told; all 16 complied |
| Cost per 16 runs | about $1.10 | about $2 | about $1.10 |
| Read the edit back after applying | Most runs | Most runs | Every run that applied, via the tool's own return value |
What WebMCP itself taught us
These are about the platform, and they are the things the entry point PR has to get right.
- Register once per page. React's development mode runs effects twice. The second
registerToolthrew "Duplicate tool name", because unregistering through the AbortSignal is asynchronous. The scratch story registers once at module level and reads the live state through a target the component updates on each render. The media editor modal will need the same care, or a guard ongetTools()before registering. - Registration is late for a client that looks straight away. In about half the runs,
getTools()returned an empty list on the first call because the story had not mounted yet. The agents retried after two seconds. A real client should listen toontoolchange. The entry point should register as early as the session exists. executeTooltakes the tool object, not its name.executeTool( 'apply_image_edit', … )throws "parameter 1 is not of type 'Tool'". Every client has to callgetTools()first.- Results come back as a string. The tool returned
{ content: [ { type: 'text', text } ] }, andexecuteToolhanded the agent that object JSON-encoded. Agents parsed it without trouble. Whether to return a plain object instead is a choice for the entry point. - No real WebMCP client is on this machine. Claude in Chrome does not discover WebMCP tools, per the open issues on the Claude Code repository. Google's example extension at GoogleChromeLabs/webmcp-extension is a true client with a model behind it, and needs Chrome 155 or newer, the flag, and a model server with an API key. This test used Playwright
evaluateas the client, which exercises the page side fully and the discovery path, but not out-of-band discovery by a browser agent.
Follow-ups, updated
The list stands. WebMCP changes two items.
- Media editor entry point:
getImageEdit,applyImageEditas one undo step,undo. Unchanged, still first. - Expose the entry point as WebMCP tools in the modal. Now known to be testable locally with the flag. Register once, early, through an AbortSignal; return the edit, not the state; put the README text in the descriptions. The scratch story is a working draft of this.
- Storybook copy for the agent test. Promote the scratch story, minus the hacks, once the entry point's shape is settled, so the test runs without a WordPress site.
- Snap float noise in
getImageEditandgetOutputSize. Unchanged. The read-back still shows-4.7e-8and500.00000000000006. - Keep the state opaque, and decide about the base fields. Unchanged, and now demonstrated: with the tools returning edits, no run saw an internal field.
- Try Google's example extension as a second client when the entry point exists, to test out-of-band discovery. Needs an API key in a local model server.
.
Funnily enough there's some promising stuff in there, that the agents actively rejected the instruction because it really was looking at the image. E.g. for the
So yeah, sounds like there'll be some fun stuff to play with in follow-ups!
Might also be worth checking out how the WebMCP experiment has been implemented in the AI plugin: WordPress/ai#1081. That said, I couldn't quite tell from that PR why it wasn't using In any case, thanks for the discussion here! I'll leave it there and get back to giving this a code review 😄 |
andrewserong
left a comment
There was a problem hiding this comment.
Thanks for all the updates here, this is looking so good!
Just left a few comments, nothing blocking, especially my nit-picky feedback on the docs. Wording for this stuff can be hard, and we can tweak in follow-ups if need be!
Overall I really like the shape of the function, the default containment behaviour, it's nice having the strict option, and the story works really well for playing around with it.
LGTM! 🚀
`getImageEdit` reads the edit out of a state. Nothing could take one back in, so nobody had checked that the shape works for writing before the package is first published. `applyImageEdit( state, edit )` builds the state through the reducer's reset, then reads the result back with `getImageEdit`. If the two differ, the editor could not hold the edit and it is rejected with a cause. The edit is the whole edit: a part left out means none. The view is the one the editor settles on after a resize, so the pan and zoom are replaced. It is not exported yet. Three checks cover it: - Every state the invariants test reaches hands its own edit back to a clean state and reads the same edit again. - For two edits written by hand, the export camera picks the pixels the edit names. - None of the 864 hand-built parity states applies as a different edit. Each comes back the same or is rejected.
Export `applyImageEdit` and its result type from the package root, next to `getImageEdit`. The public API test opens the canvas on a state built by `applyImageEdit`: a quarter turn and the left half of the turned image. The canvas keeps that edit, and the size tooltip shows 300 by 1200 pixels. If loading the image reset a state that already holds it, this is the only test that fails.
Add a README entry and a recipe. The README says what a consumer cannot guess from the type: a part left out means none, changing the flip or rotation without the crop frames a different part of the image, the pan and zoom are replaced, and what each rejection means. The recipe applies an edit with no canvas and exports the result. Its code was type-checked against the package exports. The function's own comment said the crop's longer side fills the view. On a view that is not square the side that fills it can be the shorter one, so it now says the crop is zoomed in until it meets an edge of the view or the zoom limit.
Keep only what the code and names do not already say.
…eEdit The check that the new state holds the edit compared angles with a signed remainder, so 720° and above came out as -180 and the edit was rejected as outside-image. Reduce the difference to within one turn first.
…yImageEdit Only a width or height of exactly 0 counted as no image. A missing, NaN or negative size went on to the crop check and was rejected as outside-image, which blames the crop for a problem with the image.
Any crop with a positive size was accepted, down to a fraction of a pixel. Export rounds the crop to whole pixels, so one under half a pixel gives an empty canvas and the export fails. Reject a crop under one source pixel wide or high as invalid; any larger minimum is left to the caller.
The invariants round trip required every reachable edit to apply, but applyImageEdit now rejects crops under one pixel, and setCropRect can reach them. No seed lands on one yet. Expect invalid for those instead.
getImageEdit and getOutputSize only treated a size of exactly 0 as no image, so a NaN, missing or negative size gave a NaN edit and size. applyImageEdit already calls that no-image. Use its guard in both.
Type an ImageEdit as JSON and apply it to the canvas. The story shows why an edit was rejected, the edit the canvas now holds, and can copy that edit back into the box. A switch locks the crop to a square, to try a locked ratio.
The README and the ImageEditRejection comment explained invalid and outside-image only. Add no-image and locked-ratio, and show the explanation in the story next to the reason, so a tester does not have to look it up.
The story shows the image credit, whose text fails color-contrast, so Storybook's accessibility check failed it. The other stories that show the credit are marked todo for the same reason (#81596).
"A part missing from edit means none" read as if a missing part might be kept or might be required. Say that the edit replaces the current one, what each missing part resets to, and how to keep a part. List the rejection reasons, and add a short example.
A bare fine rotation such as { rotation: 5 } was rejected, because a
missing crop meant the whole tilted bounding box, empty corners and
all. A missing crop now gets the crop the rotate control picks.
A crop the image does not cover is fitted as the editor fits one: it
shrinks about its centre only as far as its shape needs, then moves
the shortest way inside. Under a locked ratio it keeps its centre and
width, as the crop setter does, so an 800 by 400 crop under a square
lock becomes 800 by 800 rather than 450 by 450.
Pass { strict: true } to reject an edit that needs fitting instead,
which is what applyImageEdit did before.
Export ApplyImageEditOptions and ImageEditRejection from the package root, as ExportImageOptions is, so a consumer can name the rejection reasons without extracting them from the result type. The Apply an Edit story uses ImageEditRejection for its messages and gains a switch for strict mode, so all four reasons can be tried.
JSON.parse accepts values that are not an edit. null threw when applyImageEdit read it, and an array, a number or a string read as an empty edit, which reset the canvas. Say what is wrong instead.
A missing crop is the editor's choice in both modes, so { rotation: 5 }
applies with strict too. The README and the option say so, and the
recipe says which rejections are left without strict.
…ested branches Fill the empty @PARAM tags and say why strict skips the locked-ratio pre-fit. Replace the test that only checked the lock survived, which the missing-crop test already proves, with one that a conforming crop under a lock is accepted as passed in strict mode. Cover both axes flipped, a negative rotation and a non-finite crop number.
List the rejection reasons one per line, and say in plain sentences what holdsEdit checks and what applyImageEdit keeps and resets. Spell center the US way in the lines this PR adds.
…t docs A string flip value is truthy, so "false" would flip the image. Reject it as invalid, like a non-finite number. In the README, say in plain words that every call describes the whole result, keep the strict option with the fitting it changes, and list the four rejection reasons together.
de42150 to
12370f1
Compare
What?
Part of:
Introduces
applyImageEdit( state, edit ), the reverse ofgetImageEdit. The former is a setter, the latter a getter.How
applyImageEditturns anImageEditback into an editor state, that is, what the canvas shows (ImageEditorState):The intended use is to apply crop instructions to an image programmatically, with or without a crop canvas. See follow ups for what needs to happen to enable this.
Contrast with
getImageEdit, which turnsImageEditorStateinto a state that describes the crop against the image (ImageEdit):See for reference
A crop the image doesn't cover is fitted, as in the editor.
{ strict: true }rejects it instead. Invalid input is always rejected.Why?
#86630 made
ImageEditthe type for reading and writing, but nothing wrote one. This tests the shape beforeapplyImageEditis published. The type needed no change.Testing Instructions
No UI calls it yet, but you can test in storybook
npm run storybook:devand open Editor/Image Editor/Canvas › Apply An Edit.{ "rotation": 10 }and click Apply. The image tilts and zooms in, as with the rotate control.locked-ratio.