Skip to content

Commit

Permalink
Prevent image losing its aspect ratio at smaller window dimensions
Browse files Browse the repository at this point in the history
  • Loading branch information
scruffian committed Aug 3, 2023
1 parent 6edd9ff commit 8ac9f8c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
28 changes: 22 additions & 6 deletions packages/block-library/src/image/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,11 +252,7 @@ export default function Image( {
loadedNaturalHeight ||
undefined,
};
}, [
loadedNaturalWidth,
loadedNaturalHeight,
imageRef.current?.complete,
] );
}, [ loadedNaturalWidth, loadedNaturalHeight, imageRef.current ] );

function onResizeStart() {
toggleSelection( false );
Expand Down Expand Up @@ -480,14 +476,34 @@ export default function Image( {
<DimensionsTool
value={ { width, height, scale, aspectRatio } }
onChange={ ( newValue ) => {
// 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.
setAttributes( {
width: newValue.width,
height: newValue.height,
scale: newValue.scale,
aspectRatio: newValue.aspectRatio,
aspectRatio: newAspectRatio,
} );
} }
defaultScale="cover"
Expand Down
2 changes: 1 addition & 1 deletion packages/block-library/src/image/save.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export default function save( { attributes } ) {
aspectRatio,
objectFit: scale,
width,
height,
maxHeight: height,
} }
title={ title }
/>
Expand Down

0 comments on commit 8ac9f8c

Please sign in to comment.