Merge pull request #18512 from backstage/philipph/fix-overrides

[MUI v5] Add missing `px` to theme overrdies
This commit is contained in:
Ben Lambert
2023-07-04 17:30:05 +02:00
committed by GitHub
3 changed files with 33 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/theme': patch
---
Override the spacing to a v5 compliant method
@@ -18,12 +18,14 @@ import { Theme } from '@mui/material/styles';
import { transformV5ComponentThemesToV4 } from './overrides';
describe('transformV5ComponentThemesToV4', () => {
// TODO: Create actual v5 Theme to avoid missing properties in test
const mockTheme = {
palette: {
primary: {
main: 'red',
},
},
spacing: (n: number) => `${n * 8}px`,
} as unknown as Theme;
it('transforms empty component themes', () => {
expect(transformV5ComponentThemesToV4(mockTheme)).toEqual({
+26
View File
@@ -29,6 +29,26 @@ type StaticStyleRules = Record<
CSSProperties | Record<string, CSSProperties>
>;
// Utility function based on v5 `createSpacing`: https://github.com/mui/material-ui/blob/master/packages/mui-system/src/createTheme/createSpacing.ts#L42C3-L59C5
const __v5Spacing =
(defaultSpacing: number) =>
(...argsInput: ReadonlyArray<number | string>) => {
const args = argsInput.length === 0 ? [1] : argsInput;
const transform = (argument: string | number, themeSpacing: number) => {
if (typeof argument === 'string') {
return argument;
}
return themeSpacing * argument;
};
return args
.map(argument => {
const output = transform(argument, defaultSpacing);
return typeof output === 'number' ? `${output}px` : output;
})
.join(' ');
};
// Converts callback-based overrides to static styles, e.g.
// { root: theme => ({ color: theme.color }) } -> { root: { color: 'red' } }
function adaptV5CssBaselineOverride(
@@ -60,6 +80,12 @@ function adaptV5Override(
return Object.fromEntries(
Object.entries(overrides).map(([className, style]) => {
if (typeof style === 'function') {
const defaultSpacing = theme.spacing(1);
if (typeof defaultSpacing === 'number') {
// Override potential v4 spacing method: https://mui.com/material-ui/migration/v5-style-changes/#%E2%9C%85-remove-px-suffix
// `adaptV4Theme as reference: https://github.com/mui/material-ui/blob/v5.x/packages/mui-material/src/styles/adaptV4Theme.js#L54C41-L54C41
theme.spacing = __v5Spacing(defaultSpacing);
}
return [className, style({ theme })];
}
return [className, style];