Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -245,12 +245,22 @@ function BackgroundImageToolsPanelItem( {
return;
}

const sizeValue = style?.background?.backgroundSize;
const positionValue = style?.background?.backgroundPosition;

onChange(
setImmutably( style, [ 'background', 'backgroundImage' ], {
url: media.url,
id: media.id,
source: 'file',
title: media.title || undefined,
setImmutably( style, [ 'background' ], {
...style?.background,
backgroundImage: {
url: media.url,
id: media.id,
source: 'file',
title: media.title || undefined,
},
backgroundPosition:
! positionValue && ( 'auto' === sizeValue || ! sizeValue )
? '50% 0'
: positionValue,
} )
);
};
Expand Down Expand Up @@ -426,13 +436,16 @@ function BackgroundSizeToolsPanelItem( {
const updateBackgroundSize = ( next ) => {
// When switching to 'contain' toggle the repeat off.
let nextRepeat = repeatValue;
let nextPosition = positionValue;

if ( next === 'contain' ) {
nextRepeat = 'no-repeat';
nextPosition = undefined;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting to undefined between toggles so that "50% 0" doesn't persist.

This means however, that any user-defined position values are lost as well.

I'm wondering if we should save the value in local state and only reset when a default value is detected, e.g, "50% 0"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO it's fine to reset the position when switching between sizes as you're kind of resetting how the image will appear anyway. Could be a follow-up PR if we think it's needed after all?

}

if ( next === 'cover' ) {
nextRepeat = undefined;
nextPosition = undefined;
}

if (
Expand All @@ -441,6 +454,15 @@ function BackgroundSizeToolsPanelItem( {
next === 'auto'
) {
nextRepeat = undefined;
/*
* A background image uploaded and set in the editor (an image with a record id),
* receives a default background position of '50% 0',
* when the toggle switches to "Tile". This is to increase the chance that
* the image's focus point is visible.
*/
if ( !! style?.background?.backgroundImage?.id ) {
nextPosition = '50% 0';
}
}

/*
Expand All @@ -454,6 +476,7 @@ function BackgroundSizeToolsPanelItem( {
onChange(
setImmutably( style, [ 'background' ], {
...style?.background,
backgroundPosition: nextPosition,
backgroundRepeat: nextRepeat,
backgroundSize: next,
} )
Expand Down Expand Up @@ -545,6 +568,7 @@ function BackgroundSizeToolsPanelItem( {
size="__unstable-large"
__unstableInputWidth="100px"
min={ 0 }
placeholder={ __( 'Auto' ) }
/>
) : null }
{ currentValueForToggle !== 'cover' && (
Expand Down