UNPKG

1.66 kBJavaScriptView Raw
1import excludeVariablesFromRoot from "./excludeVariablesFromRoot.js";
2export default theme => (colorScheme, css) => {
3 const root = theme.rootSelector || ':root';
4 const selector = theme.colorSchemeSelector;
5 let rule = selector;
6 if (selector === 'class') {
7 rule = '.%s';
8 }
9 if (selector === 'data') {
10 rule = '[data-%s]';
11 }
12 if (selector?.startsWith('data-') && !selector.includes('%s')) {
13 // 'data-mui-color-scheme' -> '[data-mui-color-scheme="%s"]'
14 rule = `[${selector}="%s"]`;
15 }
16 if (theme.defaultColorScheme === colorScheme) {
17 if (colorScheme === 'dark') {
18 const excludedVariables = {};
19 excludeVariablesFromRoot(theme.cssVarPrefix).forEach(cssVar => {
20 excludedVariables[cssVar] = css[cssVar];
21 delete css[cssVar];
22 });
23 if (rule === 'media') {
24 return {
25 [root]: css,
26 [`@media (prefers-color-scheme: dark)`]: {
27 [root]: excludedVariables
28 }
29 };
30 }
31 if (rule) {
32 return {
33 [rule.replace('%s', colorScheme)]: excludedVariables,
34 [`${root}, ${rule.replace('%s', colorScheme)}`]: css
35 };
36 }
37 return {
38 [root]: {
39 ...css,
40 ...excludedVariables
41 }
42 };
43 }
44 if (rule && rule !== 'media') {
45 return `${root}, ${rule.replace('%s', String(colorScheme))}`;
46 }
47 } else if (colorScheme) {
48 if (rule === 'media') {
49 return {
50 [`@media (prefers-color-scheme: ${String(colorScheme)})`]: {
51 [root]: css
52 }
53 };
54 }
55 if (rule) {
56 return rule.replace('%s', String(colorScheme));
57 }
58 }
59 return root;
60};
\No newline at end of file