Skip to content

Commit c06c9ee

Browse files
fix: adjusting width units will make the image width look correct.
fixes #3268
1 parent 8b01521 commit c06c9ee

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

src/block-components/image/edit.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,47 @@ const Controls = props => {
256256
}
257257
return ''
258258
} )() }
259+
onChangeUnit={ ( unit, attributeName, oldUnit ) => {
260+
// When the unit is changed, we need to adjust the width
261+
// so that the image does not get distorted.
262+
if ( isImageBlock && deviceType === 'Desktop' ) {
263+
// Switching from % to px
264+
if ( oldUnit === '%' && unit === 'px' ) {
265+
// If image is too small, use the original image width
266+
if ( imageBlockWidth && attributes.imageWidthAttribute < imageBlockWidth ) {
267+
return setAttributes( {
268+
imageWidth: attributes.imageWidthAttribute,
269+
[ attributeName ]: unit,
270+
} )
271+
}
272+
// If the width is larger than the block width, reset to 100% / width of block
273+
if ( attributes.imageWidth === '' ) {
274+
return setAttributes( {
275+
imageWidth: imageBlockWidth,
276+
[ attributeName ]: unit,
277+
} )
278+
}
279+
// Switching from px to %
280+
} else if ( oldUnit === 'px' && unit === '%' ) {
281+
// If the image is larger than the block width, reset to 100%
282+
if ( imageBlockWidth && attributes.imageWidthAttribute > imageBlockWidth ) {
283+
return setAttributes( {
284+
imageWidth: '',
285+
[ attributeName ]: unit,
286+
} )
287+
}
288+
// If image goes past 100$, reset to 100%
289+
if ( attributes.imageWidth > 100 ) {
290+
return setAttributes( {
291+
imageWidth: '',
292+
[ attributeName ]: unit,
293+
} )
294+
}
295+
}
296+
}
297+
// Normal saving behavior.
298+
setAttributes( { [ attributeName ]: unit } )
299+
} }
259300
responsive="all"
260301
onOverrideReset={ () => {
261302
// When resetting and in desktop, adjust the width so that we get the right "reset" value. Logic:

src/components/base-control2/index.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,13 +147,18 @@ const AdvancedControl = props => {
147147

148148
const unit = props.unit ? props.unit : unitAttribute
149149
const setAttributes = useBlockSetAttributesContext()
150-
const onChangeUnit = unit => setAttributes( { [ unitAttrName ]: unit } )
150+
const onChangeUnit = unit => {
151+
if ( props.onChangeUnit ) {
152+
return props.onChangeUnit( unit, unitAttrName, unitAttribute )
153+
}
154+
setAttributes( { [ unitAttrName ]: unit } )
155+
}
151156

152157
return (
153158
<BaseControl
154159
{ ...props }
155160
unit={ unit }
156-
onChangeUnit={ props.onChangeUnit || onChangeUnit }
161+
onChangeUnit={ onChangeUnit }
157162
/>
158163
)
159164
}

0 commit comments

Comments
 (0)