Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[system] Prevent nested non-vars theme inheritance #45545

Merged
merged 3 commits into from
Mar 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion packages/mui-material/src/styles/ThemeProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as React from 'react';
import { expect } from 'chai';
import { createRenderer } from '@mui/internal-test-utils';
import { ThemeProvider, createTheme, useColorScheme } from '@mui/material/styles';
import { ThemeProvider, createTheme, useColorScheme, useTheme } from '@mui/material/styles';
import Button from '@mui/material/Button';

describe('ThemeProvider', () => {
const { render } = createRenderer();
Expand Down Expand Up @@ -109,4 +110,37 @@ describe('ThemeProvider', () => {
expect(getByTestId('mode-switcher')).to.have.property('value', 'dark');
});
});

describe('nested ThemeProvider', () => {
it('should have `vars` as null for nested non-vars theme', () => {
const upperTheme = createTheme({
cssVariables: true,
});
const nestedTheme = createTheme({
palette: {
// @ts-ignore
ochre: {
main: '#E3D026',
light: '#E9DB5D',
dark: '#A29415',
contrastText: '#242105',
},
},
});
let theme: any;
function Component() {
theme = useTheme();
return <Button>Button</Button>;
}
render(
<ThemeProvider theme={upperTheme}>
<ThemeProvider theme={nestedTheme}>
<Component />
</ThemeProvider>
</ThemeProvider>,
);

expect(theme.vars).to.equal(null);
});
});
});
5 changes: 5 additions & 0 deletions packages/mui-material/src/styles/ThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ export default function ThemeProvider<Theme = DefaultTheme>({
}
const muiTheme = (THEME_ID in theme ? theme[THEME_ID] : theme) as ThemeProviderProps['theme'];
if (!('colorSchemes' in muiTheme)) {
if (!('vars' in muiTheme)) {
// For non-CSS variables themes, set `vars` to null to prevent theme inheritance from the upper theme.
// The example use case is the docs demo that uses ThemeProvider to customize the theme while the upper theme is using CSS variables.
return <ThemeProviderNoVars theme={{ ...theme, vars: null }} {...props} />;
}
return <ThemeProviderNoVars theme={theme} {...props} />;
}
return <CssVarsProvider theme={theme as unknown as CssVarsTheme} {...props} />;
Expand Down