forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.ts
88 lines (82 loc) · 2.23 KB
/
common.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { cache, css } from '@emotion/css';
import type { CSSObject } from '@emotion/serialize';
import type { IOptions } from '@linaria/tags';
import { createTheme } from '@mui/material/styles';
import type { SxConfig } from '@mui/system';
import styleFunctionSx, {
unstable_defaultSxConfig as defaultSxConfig,
} from '@mui/system/styleFunctionSx';
export { SxConfig };
export type ICustomOptions<
T extends {
unstable_sxConfig?: SxConfig;
},
> = IOptions & {
theme?: T;
darkTheme?: T;
prefix?: string;
};
export function getTheme<
T extends {
unstable_sxConfig?: SxConfig;
},
>(theme: T | undefined, prefix = ''): T {
const sxConfig = {
...defaultSxConfig,
...(theme ?? {}).unstable_sxConfig,
};
Object.keys(sxConfig).forEach((configKey) => {
let value = sxConfig[configKey];
if (value.themeKey === 'palette' && value.transform) {
value = {
...value,
transform: (cssValue: unknown, userValue: unknown) => {
if (cssValue === userValue) {
return cssValue as string;
}
if (
typeof userValue === 'string' &&
!userValue.startsWith('rgb') &&
userValue.includes('.')
) {
return [
cssValue as string,
`var(--${prefix ? `${prefix}-` : ''}palette-${(userValue as string)
.split('.')
.join('-')}, ${cssValue})`,
];
}
return cssValue as string;
},
};
sxConfig[configKey] = value;
}
});
if (!theme) {
const newTheme = createTheme({
unstable_sxConfig: sxConfig,
});
return newTheme as unknown as T;
}
theme.unstable_sxConfig = sxConfig;
return theme;
}
export function generateSxCss<T extends {}>(
inputObj: CSSObject | ((param: { theme: T; darkTheme: T }) => CSSObject),
theme: T,
darkTheme: T,
) {
const cssObj = styleFunctionSx({
sx: typeof inputObj === 'function' ? inputObj({ theme, darkTheme }) : inputObj,
theme,
});
if (typeof cssObj === 'string') {
return cssObj;
}
const resultClass = css([cssObj as any]);
const finalCss = cache.registered[resultClass];
if (typeof finalCss === 'boolean') {
return '';
}
return finalCss;
}