@mui/system 5.0.6 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/LICENSE +21 -21
  3. package/breakpoints.js +41 -8
  4. package/createBox.d.ts +5 -1
  5. package/createBox.js +5 -3
  6. package/createTheme/createBreakpoints.js +2 -2
  7. package/cssVars/createCssVarsProvider.d.ts +88 -38
  8. package/cssVars/createCssVarsProvider.js +83 -61
  9. package/cssVars/cssVarsParser.d.ts +14 -3
  10. package/cssVars/cssVarsParser.js +41 -11
  11. package/cssVars/getInitColorSchemeScript.d.ts +7 -2
  12. package/cssVars/getInitColorSchemeScript.js +27 -5
  13. package/cssVars/useCurrentColorScheme.d.ts +50 -0
  14. package/cssVars/useCurrentColorScheme.js +235 -0
  15. package/esm/breakpoints.js +39 -8
  16. package/esm/createBox.js +5 -3
  17. package/esm/createTheme/createBreakpoints.js +2 -2
  18. package/esm/cssVars/createCssVarsProvider.js +82 -63
  19. package/esm/cssVars/cssVarsParser.js +40 -11
  20. package/esm/cssVars/getInitColorSchemeScript.js +24 -3
  21. package/esm/cssVars/useCurrentColorScheme.js +217 -0
  22. package/esm/styleFunctionSx/extendSxProp.js +20 -1
  23. package/esm/styleFunctionSx/styleFunctionSx.js +45 -35
  24. package/index.js +1 -1
  25. package/legacy/breakpoints.js +39 -8
  26. package/legacy/createBox.js +6 -3
  27. package/legacy/createTheme/createBreakpoints.js +2 -2
  28. package/legacy/cssVars/createCssVarsProvider.js +83 -70
  29. package/legacy/cssVars/cssVarsParser.js +37 -9
  30. package/legacy/cssVars/getInitColorSchemeScript.js +13 -4
  31. package/legacy/cssVars/useCurrentColorScheme.js +231 -0
  32. package/legacy/index.js +1 -1
  33. package/legacy/styleFunctionSx/extendSxProp.js +21 -1
  34. package/legacy/styleFunctionSx/styleFunctionSx.js +44 -34
  35. package/modern/breakpoints.js +39 -8
  36. package/modern/createBox.js +5 -3
  37. package/modern/createTheme/createBreakpoints.js +2 -2
  38. package/modern/cssVars/createCssVarsProvider.js +82 -63
  39. package/modern/cssVars/cssVarsParser.js +40 -11
  40. package/modern/cssVars/getInitColorSchemeScript.js +24 -3
  41. package/modern/cssVars/useCurrentColorScheme.js +217 -0
  42. package/modern/index.js +1 -1
  43. package/modern/styleFunctionSx/extendSxProp.js +20 -1
  44. package/modern/styleFunctionSx/styleFunctionSx.js +45 -35
  45. package/package.json +7 -7
  46. package/styleFunctionSx/extendSxProp.js +21 -1
  47. package/styleFunctionSx/styleFunctionSx.d.ts +2 -1
  48. package/styleFunctionSx/styleFunctionSx.js +46 -36
  49. package/styleFunctionSx/styleFunctionSx.spec.d.ts +1 -0
@@ -21,8 +21,12 @@ var _styledEngine = require("@mui/styled-engine");
21
21
 
22
22
  var _cssVarsParser = _interopRequireDefault(require("./cssVarsParser"));
23
23
 
24
+ var _ThemeProvider = _interopRequireDefault(require("../ThemeProvider"));
25
+
24
26
  var _getInitColorSchemeScript = _interopRequireWildcard(require("./getInitColorSchemeScript"));
25
27
 
28
+ var _useCurrentColorScheme = _interopRequireDefault(require("./useCurrentColorScheme"));
29
+
26
30
  var _jsxRuntime = require("react/jsx-runtime");
27
31
 
28
32
  const _excluded = ["colorSchemes"],
@@ -32,33 +36,16 @@ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "functio
32
36
 
33
37
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
34
38
 
35
- const resolveMode = (key, fallback, supportedColorSchemes) => {
36
- if (typeof window === 'undefined') {
37
- return undefined;
38
- }
39
-
40
- let value;
41
-
42
- try {
43
- value = localStorage.getItem(key) || undefined;
44
-
45
- if (!supportedColorSchemes.includes(value)) {
46
- value = undefined;
47
- }
48
- } catch (e) {// Unsupported
49
- }
50
-
51
- return value || fallback;
52
- };
53
-
54
- function createCssVarsProvider(ThemeContext, options) {
39
+ function createCssVarsProvider(options) {
55
40
  const {
56
41
  theme: baseTheme = {},
42
+ defaultMode: desisgnSystemMode = 'light',
57
43
  defaultColorScheme: designSystemColorScheme,
58
- prefix: designSystemPrefix = ''
44
+ prefix: designSystemPrefix = '',
45
+ shouldSkipGeneratingVar
59
46
  } = options;
60
47
 
61
- if (!baseTheme.colorSchemes || !baseTheme.colorSchemes[designSystemColorScheme]) {
48
+ if (!baseTheme.colorSchemes || typeof designSystemColorScheme === 'string' && !baseTheme.colorSchemes[designSystemColorScheme] || typeof designSystemColorScheme === 'object' && !baseTheme.colorSchemes[designSystemColorScheme == null ? void 0 : designSystemColorScheme.light] || typeof designSystemColorScheme === 'object' && !baseTheme.colorSchemes[designSystemColorScheme == null ? void 0 : designSystemColorScheme.dark]) {
62
49
  console.error(`MUI: \`${designSystemColorScheme}\` does not exist in \`theme.colorSchemes\`.`);
63
50
  }
64
51
 
@@ -78,8 +65,9 @@ function createCssVarsProvider(ThemeContext, options) {
78
65
  children,
79
66
  theme: themeProp = {},
80
67
  prefix = designSystemPrefix,
81
- storageKey = _getInitColorSchemeScript.DEFAULT_STORAGE_KEY,
68
+ modeStorageKey = _getInitColorSchemeScript.DEFAULT_MODE_STORAGE_KEY,
82
69
  attribute = _getInitColorSchemeScript.DEFAULT_ATTRIBUTE,
70
+ defaultMode = desisgnSystemMode,
83
71
  defaultColorScheme = designSystemColorScheme
84
72
  }) {
85
73
  const {
@@ -93,14 +81,44 @@ function createCssVarsProvider(ThemeContext, options) {
93
81
  let mergedTheme = (0, _utils.deepmerge)(restBaseTheme, restThemeProp);
94
82
  const colorSchemes = (0, _utils.deepmerge)(baseColorSchemes, colorSchemesProp);
95
83
  const allColorSchemes = Object.keys(colorSchemes);
96
- const joinedColorSchemes = allColorSchemes.join(',');
97
- const [colorScheme, setColorScheme] = React.useState(() => resolveMode(storageKey, defaultColorScheme, allColorSchemes));
98
- const resolvedColorScheme = colorScheme || defaultColorScheme;
84
+ const defaultLightColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.light;
85
+ const defaultDarkColorScheme = typeof defaultColorScheme === 'string' ? defaultColorScheme : defaultColorScheme.dark;
86
+ const {
87
+ mode,
88
+ setMode,
89
+ lightColorScheme,
90
+ darkColorScheme,
91
+ colorScheme,
92
+ setColorScheme
93
+ } = (0, _useCurrentColorScheme.default)({
94
+ supportedColorSchemes: allColorSchemes,
95
+ defaultLightColorScheme,
96
+ defaultDarkColorScheme,
97
+ modeStorageKey,
98
+ defaultMode
99
+ });
100
+
101
+ const resolvedColorScheme = (() => {
102
+ if (!colorScheme) {
103
+ // This scope occurs on the server
104
+ if (defaultMode === 'dark') {
105
+ return defaultDarkColorScheme;
106
+ } // use light color scheme, if default mode is 'light' | 'auto'
107
+
108
+
109
+ return defaultLightColorScheme;
110
+ }
111
+
112
+ return colorScheme;
113
+ })();
114
+
99
115
  const {
100
116
  css: rootCss,
101
117
  vars: rootVars
102
118
  } = (0, _cssVarsParser.default)(mergedTheme, {
103
- prefix
119
+ prefix,
120
+ basePrefix: designSystemPrefix,
121
+ shouldSkipGeneratingVar
104
122
  });
105
123
  mergedTheme = (0, _extends2.default)({}, mergedTheme, colorSchemes[resolvedColorScheme], {
106
124
  vars: rootVars
@@ -111,15 +129,29 @@ function createCssVarsProvider(ThemeContext, options) {
111
129
  css,
112
130
  vars
113
131
  } = (0, _cssVarsParser.default)(scheme, {
114
- prefix
132
+ prefix,
133
+ basePrefix: designSystemPrefix,
134
+ shouldSkipGeneratingVar
115
135
  });
116
136
 
117
137
  if (key === resolvedColorScheme) {
118
138
  mergedTheme.vars = (0, _extends2.default)({}, mergedTheme.vars, vars);
119
139
  }
120
140
 
121
- if (key === defaultColorScheme) {
122
- styleSheet[':root'] = (0, _utils.deepmerge)(rootCss, css);
141
+ const resolvedDefaultColorScheme = (() => {
142
+ if (typeof defaultColorScheme === 'string') {
143
+ return defaultColorScheme;
144
+ }
145
+
146
+ if (defaultMode === 'dark') {
147
+ return defaultColorScheme.dark;
148
+ }
149
+
150
+ return defaultColorScheme.light;
151
+ })();
152
+
153
+ if (key === resolvedDefaultColorScheme) {
154
+ styleSheet[':root'] = css;
123
155
  } else {
124
156
  styleSheet[`[${attribute}="${key}"]`] = css;
125
157
  }
@@ -127,41 +159,26 @@ function createCssVarsProvider(ThemeContext, options) {
127
159
  React.useEffect(() => {
128
160
  if (colorScheme) {
129
161
  document.body.setAttribute(attribute, colorScheme);
130
- localStorage.setItem(storageKey, colorScheme);
131
- }
132
- }, [colorScheme, attribute, storageKey]); // local storage modified in the context of another document
133
-
134
- React.useEffect(() => {
135
- const handleStorage = event => {
136
- const storageColorScheme = event.newValue;
137
-
138
- if (event.key === storageKey && joinedColorSchemes.match(storageColorScheme)) {
139
- if (storageColorScheme) {
140
- setColorScheme(storageColorScheme);
141
- }
142
- }
143
- };
144
-
145
- window.addEventListener('storage', handleStorage);
146
- return () => window.removeEventListener('storage', handleStorage);
147
- }, [setColorScheme, storageKey, joinedColorSchemes]);
148
- const wrappedSetColorScheme = React.useCallback(val => {
149
- if (typeof val === 'string' && !allColorSchemes.includes(val)) {
150
- console.error(`\`${val}\` does not exist in \`theme.colorSchemes\`.`);
151
- } else {
152
- setColorScheme(val);
153
162
  }
154
- }, [setColorScheme, allColorSchemes]);
163
+ }, [colorScheme, attribute]);
155
164
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(ColorSchemeContext.Provider, {
156
165
  value: {
166
+ mode,
167
+ setMode,
168
+ lightColorScheme,
169
+ darkColorScheme,
157
170
  colorScheme,
158
- setColorScheme: wrappedSetColorScheme,
171
+ setColorScheme,
159
172
  allColorSchemes
160
173
  },
161
174
  children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_styledEngine.GlobalStyles, {
175
+ styles: {
176
+ ':root': rootCss
177
+ }
178
+ }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_styledEngine.GlobalStyles, {
162
179
  styles: styleSheet
163
- }), /*#__PURE__*/(0, _jsxRuntime.jsx)(ThemeContext.Provider, {
164
- value: mergedTheme,
180
+ }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_ThemeProvider.default, {
181
+ theme: mergedTheme,
165
182
  children: children
166
183
  })]
167
184
  });
@@ -181,17 +198,22 @@ function createCssVarsProvider(ThemeContext, options) {
181
198
  /**
182
199
  * The initial color scheme used.
183
200
  */
184
- defaultColorScheme: _propTypes.default.string,
201
+ defaultColorScheme: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.object]),
185
202
 
186
203
  /**
187
- * css variable prefix
204
+ * The initial mode used.
188
205
  */
189
- prefix: _propTypes.default.string,
206
+ defaultMode: _propTypes.default.string,
190
207
 
191
208
  /**
192
209
  * The key in the local storage used to store current color scheme.
193
210
  */
194
- storageKey: _propTypes.default.string,
211
+ modeStorageKey: _propTypes.default.string,
212
+
213
+ /**
214
+ * css variable prefix
215
+ */
216
+ prefix: _propTypes.default.string,
195
217
 
196
218
  /**
197
219
  * The calculated theme object that will be passed through context.
@@ -30,12 +30,21 @@ export declare const assignNestedKeys: <Object_1 = NestedRecord<any>, Value = an
30
30
  * walkObjectDeep({ palette: { primary: { main: '#000000' } } }, console.log)
31
31
  * // ['palette', 'primary', 'main'] '#000000'
32
32
  */
33
- export declare const walkObjectDeep: <Value, T = Record<string, any>>(obj: T, callback: (keys: Array<string>, value: Value) => void) => void;
33
+ export declare const walkObjectDeep: <Value, T = Record<string, any>>(obj: T, callback: (keys: Array<string>, value: Value, scope: Record<string, string | number>) => void) => void;
34
34
  /**
35
35
  * a function that parse theme and return { css, vars }
36
36
  *
37
37
  * @param {Object} theme
38
- * @param {{ prefix?: string }} options
38
+ * @param {{
39
+ * prefix?: string,
40
+ * basePrefix?: string,
41
+ * shouldSkipGeneratingVar?: (objectPathKeys: Array<string>, value: string | number) => boolean
42
+ * }} options.
43
+ * `basePrefix`: defined by design system.
44
+ * `prefix`: defined by application
45
+ *
46
+ * This function also mutate the string value of theme input by replacing `basePrefix` (if existed) with `prefix`
47
+ *
39
48
  * @returns {{ css: Object, vars: Object }} `css` is the stylesheet, `vars` is an object to get css variable (same structure as theme)
40
49
  *
41
50
  * @example
@@ -48,8 +57,10 @@ export declare const walkObjectDeep: <Value, T = Record<string, any>>(obj: T, ca
48
57
  * console.log(css) // { '--fontSize': '12px', '--lineHeight': 1.2, '--palette-primary-500': '#000000' }
49
58
  * console.log(vars) // { fontSize: '--fontSize', lineHeight: '--lineHeight', palette: { primary: { 500: 'var(--palette-primary-500)' } } }
50
59
  */
51
- export default function cssVarsParser(obj: Record<string, any>, options?: {
60
+ export default function cssVarsParser(theme: Record<string, any>, options?: {
52
61
  prefix?: string;
62
+ basePrefix?: string;
63
+ shouldSkipGeneratingVar?: (objectPathKeys: Array<string>, value: string | number) => boolean;
53
64
  }): {
54
65
  css: NestedRecord<string>;
55
66
  vars: NestedRecord<string>;
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
 
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
3
5
  Object.defineProperty(exports, "__esModule", {
4
6
  value: true
5
7
  });
@@ -7,6 +9,8 @@ exports.assignNestedKeys = void 0;
7
9
  exports.default = cssVarsParser;
8
10
  exports.walkObjectDeep = void 0;
9
11
 
12
+ var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
13
+
10
14
  /**
11
15
  * This function create an object from keys, value and then assign to target
12
16
  *
@@ -62,7 +66,7 @@ const walkObjectDeep = (obj, callback) => {
62
66
  if (typeof value === 'object' && Object.keys(value).length > 0) {
63
67
  recurse(value, [...parentKeys, key]);
64
68
  } else {
65
- callback([...parentKeys, key], value);
69
+ callback([...parentKeys, key], value, object);
66
70
  }
67
71
  }
68
72
  });
@@ -89,7 +93,16 @@ const getCssValue = (keys, value) => {
89
93
  * a function that parse theme and return { css, vars }
90
94
  *
91
95
  * @param {Object} theme
92
- * @param {{ prefix?: string }} options
96
+ * @param {{
97
+ * prefix?: string,
98
+ * basePrefix?: string,
99
+ * shouldSkipGeneratingVar?: (objectPathKeys: Array<string>, value: string | number) => boolean
100
+ * }} options.
101
+ * `basePrefix`: defined by design system.
102
+ * `prefix`: defined by application
103
+ *
104
+ * This function also mutate the string value of theme input by replacing `basePrefix` (if existed) with `prefix`
105
+ *
93
106
  * @returns {{ css: Object, vars: Object }} `css` is the stylesheet, `vars` is an object to get css variable (same structure as theme)
94
107
  *
95
108
  * @example
@@ -104,19 +117,36 @@ const getCssValue = (keys, value) => {
104
117
  */
105
118
 
106
119
 
107
- function cssVarsParser(obj, options) {
120
+ function cssVarsParser(theme, options) {
121
+ const clonedTheme = (0, _extends2.default)({}, theme);
122
+ delete clonedTheme.vars; // remove 'vars' from the structure
123
+
108
124
  const {
109
- prefix
125
+ prefix,
126
+ basePrefix = '',
127
+ shouldSkipGeneratingVar
110
128
  } = options || {};
111
129
  const css = {};
112
130
  const vars = {};
113
- walkObjectDeep(obj, (keys, value) => {
114
- if (typeof value === 'string' || typeof value === 'number') {
115
- const cssVar = `--${prefix ? `${prefix}-` : ''}${keys.join('-')}`;
116
- Object.assign(css, {
117
- [cssVar]: getCssValue(keys, value)
118
- });
119
- assignNestedKeys(vars, keys, `var(${cssVar})`);
131
+ walkObjectDeep(clonedTheme, (keys, val, scope) => {
132
+ if (typeof val === 'string' || typeof val === 'number') {
133
+ let value = val;
134
+
135
+ if (typeof value === 'string' && value.startsWith('var')) {
136
+ // replace the value of the `scope` object with the prefix or remove basePrefix from the value
137
+ value = prefix ? value.replace(basePrefix, prefix) : value.replace(`${basePrefix}-`, ''); // scope is the deepest object in the tree, keys is the theme path keys
138
+
139
+ scope[keys.slice(-1)[0]] = value;
140
+ }
141
+
142
+ if (!shouldSkipGeneratingVar || shouldSkipGeneratingVar && !shouldSkipGeneratingVar(keys, value)) {
143
+ // only create css & var if `shouldSkipGeneratingVar` return false
144
+ const cssVar = `--${prefix ? `${prefix}-` : ''}${keys.join('-')}`;
145
+ Object.assign(css, {
146
+ [cssVar]: getCssValue(keys, value)
147
+ });
148
+ assignNestedKeys(vars, keys, `var(${cssVar})`);
149
+ }
120
150
  }
121
151
  });
122
152
  return {
@@ -1,7 +1,12 @@
1
1
  /// <reference types="react" />
2
- export declare const DEFAULT_STORAGE_KEY = "mui-color-scheme";
2
+ export declare const DEFAULT_MODE_STORAGE_KEY = "mui-mode";
3
+ export declare const DEFAULT_COLOR_SCHEME_STORAGE_KEY = "mui-color-scheme";
3
4
  export declare const DEFAULT_ATTRIBUTE = "data-mui-color-scheme";
4
5
  export default function getInitColorSchemeScript(options?: {
5
- storageKey?: string;
6
+ defaultMode?: 'light' | 'dark' | 'system';
7
+ defaultLightColorScheme?: string;
8
+ defaultDarkColorScheme?: string;
9
+ modeStorageKey?: string;
10
+ colorSchemeStorageKey?: string;
6
11
  attribute?: string;
7
12
  }): JSX.Element;
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.DEFAULT_STORAGE_KEY = exports.DEFAULT_ATTRIBUTE = void 0;
6
+ exports.DEFAULT_MODE_STORAGE_KEY = exports.DEFAULT_COLOR_SCHEME_STORAGE_KEY = exports.DEFAULT_ATTRIBUTE = void 0;
7
7
  exports.default = getInitColorSchemeScript;
8
8
 
9
9
  var React = _interopRequireWildcard(require("react"));
@@ -14,21 +14,43 @@ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "functio
14
14
 
15
15
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
16
16
 
17
- const DEFAULT_STORAGE_KEY = 'mui-color-scheme';
18
- exports.DEFAULT_STORAGE_KEY = DEFAULT_STORAGE_KEY;
17
+ const DEFAULT_MODE_STORAGE_KEY = 'mui-mode';
18
+ exports.DEFAULT_MODE_STORAGE_KEY = DEFAULT_MODE_STORAGE_KEY;
19
+ const DEFAULT_COLOR_SCHEME_STORAGE_KEY = 'mui-color-scheme';
20
+ exports.DEFAULT_COLOR_SCHEME_STORAGE_KEY = DEFAULT_COLOR_SCHEME_STORAGE_KEY;
19
21
  const DEFAULT_ATTRIBUTE = 'data-mui-color-scheme';
20
22
  exports.DEFAULT_ATTRIBUTE = DEFAULT_ATTRIBUTE;
21
23
 
22
24
  function getInitColorSchemeScript(options) {
23
25
  const {
24
- storageKey = DEFAULT_STORAGE_KEY,
26
+ defaultMode = 'light',
27
+ defaultLightColorScheme = 'light',
28
+ defaultDarkColorScheme = 'dark',
29
+ modeStorageKey = DEFAULT_MODE_STORAGE_KEY,
30
+ colorSchemeStorageKey = DEFAULT_COLOR_SCHEME_STORAGE_KEY,
25
31
  attribute = DEFAULT_ATTRIBUTE
26
32
  } = options || {};
27
33
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("script", {
28
34
  // eslint-disable-next-line react/no-danger
29
35
  dangerouslySetInnerHTML: {
30
36
  __html: `(function() { try {
31
- var colorScheme = localStorage.getItem('${storageKey}');
37
+ var mode = localStorage.getItem('${modeStorageKey}');
38
+ var colorScheme = '';
39
+ if (mode === 'system' || (!mode && ${defaultMode} === 'system')) {
40
+ // handle system mode
41
+ var mql = window.matchMedia('(prefers-color-scheme: dark)');
42
+ if (mql.matches) {
43
+ colorScheme = localStorage.getItem('${colorSchemeStorageKey}-dark') || ${defaultLightColorScheme};
44
+ } else {
45
+ colorScheme = localStorage.getItem('${colorSchemeStorageKey}-light') || ${defaultDarkColorScheme};
46
+ }
47
+ }
48
+ if (mode === 'light') {
49
+ colorScheme = localStorage.getItem('${colorSchemeStorageKey}-light') || ${defaultLightColorScheme};
50
+ }
51
+ if (mode === 'dark') {
52
+ colorScheme = localStorage.getItem('${colorSchemeStorageKey}-dark') || ${defaultDarkColorScheme};
53
+ }
32
54
  if (colorScheme) {
33
55
  document.body.setAttribute('${attribute}', colorScheme);
34
56
  }
@@ -0,0 +1,50 @@
1
+ export declare type Mode = 'light' | 'dark' | 'system';
2
+ export declare type SystemMode = Exclude<Mode, 'system'>;
3
+ export interface State<SupportedColorScheme extends string> {
4
+ /**
5
+ * User selected mode.
6
+ * Note: on the server, mode is always undefined
7
+ */
8
+ mode: Mode | undefined;
9
+ /**
10
+ * Only valid if `mode: 'system'`, either 'light' | 'dark'.
11
+ */
12
+ systemMode: SystemMode | undefined;
13
+ /**
14
+ * The color scheme for the light mode.
15
+ */
16
+ lightColorScheme: SupportedColorScheme;
17
+ /**
18
+ * The color scheme for the dark mode.
19
+ */
20
+ darkColorScheme: SupportedColorScheme;
21
+ }
22
+ export declare type Result<SupportedColorScheme extends string> = State<SupportedColorScheme> & {
23
+ /**
24
+ * The current application color scheme. It is always `undefined` on the server.
25
+ */
26
+ colorScheme: SupportedColorScheme | undefined;
27
+ /**
28
+ * `mode` is saved to internal state and localStorage
29
+ * If `mode` is null, it will be reset to the defaultMode
30
+ */
31
+ setMode: (mode: Mode | null) => void;
32
+ /**
33
+ * `colorScheme` is saved to internal state and localStorage
34
+ * If `colorScheme` is null, it will be reset to the defaultColorScheme (light | dark)
35
+ */
36
+ setColorScheme: (colorScheme: SupportedColorScheme | Partial<{
37
+ light: SupportedColorScheme | null;
38
+ dark: SupportedColorScheme | null;
39
+ }> | null) => void;
40
+ };
41
+ export declare function getSystemMode(mode: undefined | string): SystemMode | undefined;
42
+ export declare function getColorScheme<SupportedColorScheme extends string>(state: State<SupportedColorScheme>): SupportedColorScheme | undefined;
43
+ export default function useCurrentColorScheme<SupportedColorScheme extends string>(options: {
44
+ defaultLightColorScheme: SupportedColorScheme;
45
+ defaultDarkColorScheme: SupportedColorScheme;
46
+ supportedColorSchemes: Array<SupportedColorScheme>;
47
+ defaultMode?: Mode;
48
+ modeStorageKey?: string;
49
+ colorSchemeStorageKey?: string;
50
+ }): Result<SupportedColorScheme>;