Skip to content

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

@talldan

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions