Skip to content
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

#39457: Image block keep image size on replacing image #49982

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions packages/block-library/src/image/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,18 +77,18 @@ const isTemporaryImage = ( id, url ) => ! id && isBlobURL( url );
export const isExternalImage = ( id, url ) => url && ! id && ! isBlobURL( url );

/**
* Checks if WP generated default image size. Size generation is skipped
* Checks if WP generated the specified image size. Size generation is skipped
* when the image is smaller than the said size.
*
* @param {Object} image
* @param {string} defaultSize
* @param {string} size
*
* @return {boolean} Whether or not it has default image size.
*/
function hasDefaultSize( image, defaultSize ) {
function hasSize( image, size ) {
return (
'url' in ( image?.sizes?.[ defaultSize ] ?? {} ) ||
'source_url' in ( image?.media_details?.sizes?.[ defaultSize ] ?? {} )
'url' in ( image?.sizes?.[ size ] ?? {} ) ||
'source_url' in ( image?.media_details?.sizes?.[ size ] ?? {} )
);
}

Expand Down Expand Up @@ -168,7 +168,16 @@ export function ImageEdit( {

setTemporaryURL();

let mediaAttributes = pickRelevantMediaFiles( media, imageDefaultSize );
// Try to use the previous selected image size if its available
// otherwise try the default image size or fallback to "full"
let newSize = 'full';
if ( sizeSlug && hasSize( media, sizeSlug ) ) {
newSize = sizeSlug;
} else if ( hasSize( media, imageDefaultSize ) ) {
newSize = imageDefaultSize;
}

let mediaAttributes = pickRelevantMediaFiles( media, newSize );

// If a caption text was meanwhile written by the user,
// make sure the text is not overwritten by empty captions.
Expand All @@ -182,11 +191,7 @@ export function ImageEdit( {
// Reset the dimension attributes if changing to a different image.
if ( ! media.id || media.id !== id ) {
additionalAttributes = {
// Fallback to size "full" if there's no default image size.
// It means the image is smaller, and the block will use a full-size URL.
sizeSlug: hasDefaultSize( media, imageDefaultSize )
? imageDefaultSize
: 'full',
sizeSlug: newSize,
};
} else {
// Keep the same url when selecting the same file, so "Resolution"
Expand Down
Loading