Skip to content

Core data: improve handling of media/attachment entities #70768

Open

Description

@talldan

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:

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

  1. added
    [Type] Enhancement
    [Feature] Media
    [Package] Core data
    [Package] Media Utils
    on Jul 18, 2025
  2. andrewserong commented on Jul 18, 2025

    @andrewserong
    Contributor

    Thanks for writing all this up! When it comes to the uploadMedia package, 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)

  3. talldan commented on Jul 18, 2025

    @talldan
    ContributorAuthor

    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)

    Right - I wasn't sure if the code in the uploadMedia package might already be backwards compatible, it already calls through to the original uploadMedia by 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.

  4. swissspidy commented on Jul 18, 2025

    @swissspidy
    Member

    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.

  5. talldan commented on Jul 18, 2025

    @talldan
    ContributorAuthor

    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-utils version of the uploadMedia function and the /wp/v2/media/${ id }/edit apiFetch calls.

  6. aryanpatil2703 commented on Jul 20, 2025

    @aryanpatil2703

    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-data is 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 uploadMedia

    My primary goal here will be to migrate the core logic of the uploadMedia function from @wordpress/media-utils into the @wordpress/core-data package.

    My approach will be:

    1. Create a new action within core-data that replicates the functionality of uploadMedia, including its validation and multi-file handling capabilities.
    2. Integrate this new action with core-data's resolvers and selectors to implement proper caching and automatic cache invalidation for the wp/v2/media kind. This will resolve the need for temporary fixes like the one in Media: Invalidate entities when new media is uploaded #70405.
    3. This will also unify the TypeScript types, resolving the friction between WP_REST_API_Attachment and core-data's entity records.
    4. Once the new action is stable, I'll begin replacing the legacy uploadMedia usage 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-editor and into core-data.

    My approach will be:

    1. First, I'll investigate the wp/v2/media/{id}/edit endpoint'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.
    2. Based on that investigation, I will create a new, specialized action in core-data to handle these "edit" requests.
    3. This will immediately solve the apiFetch restricted import violation in block-editor.
    4. Crucially, by routing this through core-data, we can invalidate the cache for the specific media item after a crop.
    5. This also creates a clear path toward integrating image cropping into the global undo/redo stack, as these operations can be treated as standard entity edits.

    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.

  7. ramonjd commented on Jul 21, 2025

    @ramonjd
    Member

    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).

    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.

  8. talldan commented on Jul 21, 2025

    @talldan
    ContributorAuthor

    @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.

  9. ramonjd commented on Jul 21, 2025

    @ramonjd
    Member

    Another part is the wp/v2/media/{ id }/edit endpoint, which is currently used for cropping tools:

    I'm taking a peak at core-data now 🤔 to see where /media/edit might 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:

    Image

    They return the same records (attachment post type records), however root > media returns 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 media exists 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 saveEntityRecord type action, or some special condition inside saveEntityRecord, and dispatch receiveEntityRecords to 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.

  10. talldan commented on Jul 21, 2025

    @talldan
    ContributorAuthor

    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 media exists if not as a convenience.

    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)

    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 saveEntityRecord type action, or some special condition inside saveEntityRecord, and dispatch receiveEntityRecords to add the new item to state.

    Yeah, it's an unusual one, because we're saving an entity of one id to create an with a completely different id. 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 receiveEntityRecords with the result to invalidate the media/attachment entities, which is essentially that saveEntityRecord does.

    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.

  11. ramonjd commented on Jul 21, 2025

    @ramonjd
    Member

    Adding a (private) action for it is my first thought, given how that endpoint works so differently.

    👍🏻

    I also forgot to document that, as well as being inconsistent with the interface for post type REST endpoints, /media/edit is 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 _links e.g., wp:media-edit

    The vips library that's being used (#70623 is the latest PR I believe), looks to have APIs for crop, rotate etc

    TIL! Thanks for the links.

  12. ramonjd commented on Jul 21, 2025

    @ramonjd
    Member

    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 receiveEntityRecords with the result to invalidate the media/attachment entities, which is essentially that saveEntityRecord does.

    For fun, I'm testing stuff over here:

    /media/edit returns the new id only. Calling the getEntityRecord selector using that id updates the store. Didn't go further than that, but the general approach—using a private action—seems sound. 🍺

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    [Feature] Media[Package] Core data[Package] Media Utils[Type] Enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions