From 8f74e9cc402c85fd5a1f8e40de825b3544c64bc9 Mon Sep 17 00:00:00 2001 From: scruffian Date: Tue, 1 Aug 2023 10:57:53 +0100 Subject: [PATCH] Image Aspect Ratio: Rely only on width to define image sizes when aspect ratio is set --- packages/block-library/src/image/image.js | 28 +++++++++++++++-------- packages/block-library/src/image/save.js | 22 +++++++++++------- 2 files changed, 32 insertions(+), 18 deletions(-) diff --git a/packages/block-library/src/image/image.js b/packages/block-library/src/image/image.js index 5fe5c93f4199b..b8c017c593ec7 100644 --- a/packages/block-library/src/image/image.js +++ b/packages/block-library/src/image/image.js @@ -547,6 +547,21 @@ export default function Image( { const borderProps = useBorderProps( attributes ); const isRounded = attributes.className?.includes( 'is-style-rounded' ); + const imgStyle = { + aspectRatio: aspectRatio ? aspectRatio : undefined, + objectFit: scale, + ...borderProps.style, + }; + if ( aspectRatio ) { + imgStyle.height = 'auto'; + imgStyle.width = '100%'; + } + if ( width ) { + imgStyle.width = width; + } + if ( height ) { + imgStyle.height = height; + } let img = ( // Disable reason: Image itself is not meant to be interactive, but // should direct focus to block. @@ -564,14 +579,7 @@ export default function Image( { } } ref={ imageRef } className={ borderProps.className } - style={ { - width: - ( width && height ) || aspectRatio ? '100%' : undefined, - height: - ( width && height ) || aspectRatio ? '100%' : undefined, - objectFit: scale, - ...borderProps.style, - } } + style={ imgStyle } /> { temporaryURL && } @@ -689,8 +697,8 @@ export default function Image( { onResizeStop(); setAttributes( { width: elt.offsetWidth, - height: elt.offsetHeight, - aspectRatio: undefined, + height: 'auto', + aspectRatio: aspectRatio ? aspectRatio : undefined, } ); } } resizeRatio={ align === 'center' ? 2 : 1 } diff --git a/packages/block-library/src/image/save.js b/packages/block-library/src/image/save.js index 6fa8c6b2342f3..d8827e3347b32 100644 --- a/packages/block-library/src/image/save.js +++ b/packages/block-library/src/image/save.js @@ -49,20 +49,26 @@ export default function save( { attributes } ) { [ `wp-image-${ id }` ]: !! id, } ); + const imgStyle = { + ...borderProps.style, + aspectRatio, + objectFit: scale, + }; + if ( width ) { + imgStyle.width = width; + } + + if ( height && ! isNaN( height ) ) { + imgStyle.height = height; + } const image = ( { );