Skip to content

Commit

Permalink
[system] Add enableColorScheme option to getInitColorSchemeScript (#3…
Browse files Browse the repository at this point in the history
  • Loading branch information
siriwatknp committed Jun 23, 2022
1 parent aac7888 commit 9a318c9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/mui-system/src/cssVars/createCssVarsProvider.js
Expand Up @@ -305,6 +305,7 @@ export default function createCssVarsProvider(options) {
attribute: defaultAttribute,
colorSchemeStorageKey: defaultColorSchemeStorageKey,
modeStorageKey: defaultModeStorageKey,
enableColorScheme: designSystemEnableColorScheme,
...params,
});

Expand Down
12 changes: 12 additions & 0 deletions packages/mui-system/src/cssVars/getInitColorSchemeScript.tsx
Expand Up @@ -5,6 +5,11 @@ export const DEFAULT_COLOR_SCHEME_STORAGE_KEY = 'color-scheme';
export const DEFAULT_ATTRIBUTE = 'data-color-scheme';

export interface GetInitColorSchemeScriptOptions {
/**
* Indicate to the browser which color scheme is used (light or dark) for rendering built-in UI
* @default true
*/
enableColorScheme?: boolean;
/**
* If `true`, the initial color scheme is set to the user's prefers-color-scheme mode
* @default false
Expand Down Expand Up @@ -42,6 +47,7 @@ export interface GetInitColorSchemeScriptOptions {

export default function getInitColorSchemeScript(options?: GetInitColorSchemeScriptOptions) {
const {
enableColorScheme = true,
enableSystem = false,
defaultLightColorScheme = 'light',
defaultDarkColorScheme = 'dark',
Expand All @@ -56,13 +62,16 @@ export default function getInitColorSchemeScript(options?: GetInitColorSchemeScr
dangerouslySetInnerHTML={{
__html: `(function() { try {
var mode = localStorage.getItem('${modeStorageKey}');
var cssColorScheme = mode;
var colorScheme = '';
if (mode === 'system' || (!mode && !!${enableSystem})) {
// handle system mode
var mql = window.matchMedia('(prefers-color-scheme: dark)');
if (mql.matches) {
cssColorScheme = 'dark';
colorScheme = localStorage.getItem('${colorSchemeStorageKey}-dark') || '${defaultDarkColorScheme}';
} else {
cssColorScheme = 'light';
colorScheme = localStorage.getItem('${colorSchemeStorageKey}-light') || '${defaultLightColorScheme}';
}
}
Expand All @@ -75,6 +84,9 @@ export default function getInitColorSchemeScript(options?: GetInitColorSchemeScr
if (colorScheme) {
${colorSchemeNode}.setAttribute('${attribute}', colorScheme);
}
if (${enableColorScheme} && !!cssColorScheme) {
${colorSchemeNode}.style.setProperty('color-scheme', cssColorScheme);
}
} catch (e) {} })();`,
}}
/>
Expand Down

0 comments on commit 9a318c9

Please sign in to comment.