From 8ac9f8c4469d5e6cdfd5aa06bc0c89a37771f7c5 Mon Sep 17 00:00:00 2001 From: scruffian Date: Thu, 3 Aug 2023 12:23:10 +0100 Subject: [PATCH] Prevent image losing its aspect ratio at smaller window dimensions --- packages/block-library/src/image/image.js | 28 ++++++++++++++++++----- packages/block-library/src/image/save.js | 2 +- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/packages/block-library/src/image/image.js b/packages/block-library/src/image/image.js index a880c20ed59ab..d5e340dc7539d 100644 --- a/packages/block-library/src/image/image.js +++ b/packages/block-library/src/image/image.js @@ -252,11 +252,7 @@ export default function Image( { loadedNaturalHeight || undefined, }; - }, [ - loadedNaturalWidth, - loadedNaturalHeight, - imageRef.current?.complete, - ] ); + }, [ loadedNaturalWidth, loadedNaturalHeight, imageRef.current ] ); function onResizeStart() { toggleSelection( false ); @@ -480,6 +476,26 @@ export default function Image( { { + // If the width and height are set but the aspect ratio isn't + // then we need to calculate the aspect ratio from the width and height. + let newAspectRatio = newValue.aspectRatio; + const newNumericHeight = parseInt( + newValue.height, + 10 + ); + const newNumericWidth = parseInt( + newValue.width, + 10 + ); + if ( + ! newAspectRatio && + height && + newNumericWidth + ) { + newAspectRatio = + newNumericWidth + '/' + newNumericHeight; + } + // Rebuilding the object forces setting `undefined` // for values that are removed since setAttributes // doesn't do anything with keys that aren't set. @@ -487,7 +503,7 @@ export default function Image( { width: newValue.width, height: newValue.height, scale: newValue.scale, - aspectRatio: newValue.aspectRatio, + aspectRatio: newAspectRatio, } ); } } defaultScale="cover" diff --git a/packages/block-library/src/image/save.js b/packages/block-library/src/image/save.js index 81565af09abab..bac4133fc19c7 100644 --- a/packages/block-library/src/image/save.js +++ b/packages/block-library/src/image/save.js @@ -59,7 +59,7 @@ export default function save( { attributes } ) { aspectRatio, objectFit: scale, width, - height, + maxHeight: height, } } title={ title } />