Repository navigation
Description
What problem does this address?
Currently a lot of code across Gutenberg uses apiFetch for interacting with the wp/v2/media endpoint.
The uploadMedia function from the media-utils package is used fairly ubiquitously, since it has a lot of built-in benefits like validation and handling multiple files. (note that this is exposed within Gutenberg as the uploadMedia block-editor setting if you're searching for usage).
There are a few problems though:
- It doesn't have caching or cache invalidation built-in, so it can result in additional API requests.
- Users might be tempted to bypass
editEntityRecord, meaning edits don't end up on the undo stack. - It has separate TypeScript types to core data, for example
WP_REST_API_Attachment, which means jumping through hoops when using core-data and media-utils together. - The
uploadMedia(and media utils package) has received improvements which haven't landed in core-data.
What is your proposed solution?
uploadMedia function / mediaUtils package
Architecturally, the core-data package should be the centralized place for working with the WordPress REST API from client side code.
I think it'd be a good idea to try migrating uploadMedia to that package and building cache invalidation into it. #70405 did add a temporary patch for this, but that's not a long term solution.
Cropping tools
Another part is the wp/v2/media/{ id }/edit endpoint, which is currently used for cropping tools:
gutenberg/packages/block-editor/src/components/image-editor/use-save-image.js
Lines 74 to 78 in 5d0ff24
| apiFetch( { | |
| path: `/wp/v2/media/${ id }/edit`, | |
| method: 'POST', | |
| data: { src: url, modifiers }, | |
| } ) |
This code is in the wrong place in the block editor package (apiFetch is a restricted import of block-editor). It results in new media being created, so it also needs cache invalidation. Handling undo/redo for cropping tools would also be good, currently those manipulations are somewhat destructive (the original media is kept, but if you perform successive crops, you can't go back to a previous state). Having said that, this endpoint doesn't work like others, so that might need some exploration. Also, it might be good for cropping to be handled client-side in the future (but undo/redo would still remain a useful feature then).
Activity
andrewserong commentedon Jul 18, 2025
Thanks for writing all this up! When it comes to the
uploadMediapackage, it looks like there might still be more work to do over in #61447 as it's currently hidden behind an experiment. But I see there's some recent progress underway over in #70623 for switching to the client-side approach. (I haven't had a chance to look deeply into those, just thought I'd link to them as they look related)talldan commentedon Jul 18, 2025
Right - I wasn't sure if the code in the
uploadMediapackage might already be backwards compatible, it already calls through to the originaluploadMediaby the looks of it.The biggest question for me are about how the queue system might fit into core data, whether it makes sense to move it to core data if it only works for media or if it can be generalized. The only other queue system in core-data I know of is
createBatch, which serves a different purpose (combining multiple rest requests into one), but maybe it's similar enough. It could expose an API for pre-processing.I don't know enough about it right now, just throwing ideas around.
swissspidy commentedon Jul 18, 2025
The upload-media package is deliberately decoupled from WordPress so that it can be used outside of it as well in other editors. So please no merging into core-data, that would be detrimental to this whole effort. Think of the upload-media package as a middleware to whatever upload function you have, be it media-utils or core-data.
talldan commentedon Jul 18, 2025
Thanks for clarifying. I think it'd be good to update the package to make that clear. It does say it can be leveraged outside the block editor, I interpreted that as meaning other parts of WordPress.
edit: I've update the issue description to only cover the
media-utilsversion of theuploadMediafunction and the/wp/v2/media/${ id }/editapiFetch calls.aryanpatil2703 commentedon Jul 20, 2025
Hello! I've carefully reviewed the details of this issue and I'm very interested in working on it. This is a significant architectural improvement for centralizing data handling, and I agree that moving media interactions into
core-datais the right long-term solution.Here is my proposed plan, breaking down the work into the two main areas you've outlined:
Part 1: Refactoring
uploadMediaMy primary goal here will be to migrate the core logic of the
uploadMediafunction from@wordpress/media-utilsinto the@wordpress/core-datapackage.My approach will be:
core-datathat replicates the functionality ofuploadMedia, including its validation and multi-file handling capabilities.core-data's resolvers and selectors to implement proper caching and automatic cache invalidation for thewp/v2/mediakind. This will resolve the need for temporary fixes like the one in Media: Invalidate entities when new media is uploaded #70405.WP_REST_API_Attachmentandcore-data's entity records.uploadMediausage across the codebase.Part 2: Improving the Cropping Tools
For the image cropping functionality, the goal is to move the logic out of
@wordpress/block-editorand intocore-data.My approach will be:
wp/v2/media/{id}/editendpoint's behavior. As noted, it doesn't function like a standard REST endpoint, so I'll need to understand its unique request/response cycle before modeling it.core-datato handle these "edit" requests.apiFetchrestricted import violation inblock-editor.core-data, we can invalidate the cache for the specific media item after a crop.I can tackle these two parts as separate but related pull requests to keep the reviews manageable.
If this plan aligns with your vision for the solution, please feel free to assign this issue to me. I'm excited to contribute to this important refactor.
ramonjd commentedon Jul 21, 2025
Thanks for bringing this up.
I'm looking at this for another project. Another possibility could be tighter integration into the backend image editing classes.
The Media editor fetches images via admin-ajax.php and transforms are done without saving the image. Undo/redo history is stored in a collection of JSON objects. Cross-origin is already baked in, and it supports a lot of image formats and image processing options.
Cropping clientside using
<canvas />is also possible and might be a better UX at a later stage - I'm not sure if there are other advantages.. It'd have to handle cross origin.talldan commentedon Jul 21, 2025
@aryanpatil2703 Thanks for volunteering. I think you're a first time contributor? You're welcome to contribute in whatever way you want, but my advice is that this particular task might be better for an experienced contributor because of the size, scope and history.
There are some tasks with the 'Good First Issue' label that are usually good for first contributors - https://github.com/WordPress/gutenberg/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22Good%20First%20Issue%22.
ramonjd commentedon Jul 21, 2025
I'm taking a peak at core-data now 🤔 to see where
/media/editmight fit in. I'm not 100% sure yet, just poking around and creating notes for now for my own benefit.So we know the following selects make identical requests to
'/wp/v2/media&context=edit&_locale=user'await wp.data.resolveSelect( 'core' ).getEntityRecords( 'root', 'media' )await wp.data.resolveSelect( 'core' ).getEntityRecords( 'postType', 'attachment' ).And are stored in two places in state accordingly:
They return the same records (attachment post type records), however
root > mediareturns raw attribute thanks to rawAttributes: [ 'caption', 'title', 'description' ] defined in its entity.I know there's history and context I'm missing but this difference prima facie warrants no duplication. Based on this alone, I'd question why
mediaexists if not as a convenience.The attachments endpoint seems special anyway, so it'd need special handling whether it lives in core data state. For example. the "media/edit" route is a bit of a misnomer for the rest controller endpoint as it creates a new file. I think it'll need it's own
saveEntityRecordtype action, or some special condition insidesaveEntityRecord, and dispatchreceiveEntityRecordsto add the new item to state.Unrelated idea for later: the endpoint returns the parent's id and url. I'm wondering if we could store these relationships in the entity records as well, e.g.,
media => [ parent_id, edit_ids ]for the purposes of versioning/undo/redo.talldan commentedon Jul 21, 2025
The problem with the attachment/media entities feels like a separate concern to me. I need to make another issue to document it as I think I've only mentioned it in comments so far. (edit: ticketed in this issue - Core data: postType/attachment and root/media entities duplicate one another)
Yeah, it's an unusual one, because we're saving an entity of one
idto create an with a completely differentid. I don't know that there's anything else like it.Adding a (private) action for it is my first thought, given how that endpoint works so differently. A thunk could potentially trigger the request and then call
receiveEntityRecordswith the result to invalidate the media/attachment entities, which is essentially thatsaveEntityRecorddoes.With client side processing on the horizon, this endpoint might not be a long-term concern anyway. The vips library that's being used (#70623 is the latest PR I believe), looks to have APIs for crop, rotate etc. Private code that can be removed in the future might be the way to go.
ramonjd commentedon Jul 21, 2025
👍🏻
I also forgot to document that, as well as being inconsistent with the interface for post type REST endpoints,
/media/editis not a standard CRUD, rather, it takes an existing attachment, applies transformations, and creates a new media post.Therefore I'm thinking that it should at least be discoverable to the entity store (and our private action) through a custom link relation in
_linkse.g.,wp:media-editTIL! Thanks for the links.
ramonjd commentedon Jul 21, 2025
For fun, I'm testing stuff over here:
/media/editreturns the new id only. Calling thegetEntityRecordselector using that id updates the store. Didn't go further than that, but the general approach—using a private action—seems sound. 🍺