From f9283ba326c9eb193f609fe4cd738a754bc695e1 Mon Sep 17 00:00:00 2001 From: Diego Andai Date: Tue, 28 May 2024 09:28:28 -0400 Subject: [PATCH] [system][createStyled] Intercept `ownerState` coming from `props` and `ownerState` (#42358) --- .../src/createStyled/createStyled.js | 8 ++--- .../mui-system/createStyled.test.js | 32 +++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/packages/mui-system/src/createStyled/createStyled.js b/packages/mui-system/src/createStyled/createStyled.js index 3c01934e020172..5e7a5f6f1adf5d 100644 --- a/packages/mui-system/src/createStyled/createStyled.js +++ b/packages/mui-system/src/createStyled/createStyled.js @@ -56,6 +56,8 @@ function processStyleArg(callableStyle, { ownerState, ...props }) { ); } + const mergedState = { ...props, ...ownerState, ownerState }; + if ( !!resolvedStylesArg && typeof resolvedStylesArg === 'object' && @@ -66,7 +68,7 @@ function processStyleArg(callableStyle, { ownerState, ...props }) { variants.forEach((variant) => { let isMatch = true; if (typeof variant.props === 'function') { - isMatch = variant.props({ ownerState, ...props, ...ownerState }); + isMatch = variant.props(mergedState); } else { Object.keys(variant.props).forEach((key) => { if (ownerState?.[key] !== variant.props[key] && props[key] !== variant.props[key]) { @@ -79,9 +81,7 @@ function processStyleArg(callableStyle, { ownerState, ...props }) { result = [result]; } result.push( - typeof variant.style === 'function' - ? variant.style({ ownerState, ...props, ...ownerState }) - : variant.style, + typeof variant.style === 'function' ? variant.style(mergedState) : variant.style, ); } }); diff --git a/test/integration/mui-system/createStyled.test.js b/test/integration/mui-system/createStyled.test.js index 5301c6a56f8cc0..9d9b57f3242935 100644 --- a/test/integration/mui-system/createStyled.test.js +++ b/test/integration/mui-system/createStyled.test.js @@ -729,5 +729,37 @@ describe('createStyled', () => { expect(getByTestId('outlined')).toHaveComputedStyle({ borderTopColor: 'rgb(0, 0, 255)' }); expect(getByTestId('text')).toHaveComputedStyle({ color: 'rgb(0, 0, 255)' }); }); + + it('should not consume values from nested ownerState', () => { + const styled = createStyled({ defaultTheme: { colors: { blue: 'rgb(0, 0, 255)' } } }); + + const Test = styled('div')(({ theme }) => ({ + variants: [ + { + props: ({ ownerState }) => ownerState.color === 'blue', + style: { + backgroundColor: theme.colors.blue, + }, + }, + ], + })); + + const ownerState = { color: 'blue' }; + + const { getByTestId } = render( + + + Blue + + + Nested ownerState + + , + ); + expect(getByTestId('blue')).toHaveComputedStyle({ backgroundColor: 'rgb(0, 0, 255)' }); + expect(getByTestId('nested')).not.toHaveComputedStyle({ + backgroundColor: 'rgb(0, 0, 255)', + }); + }); }); });