Skip to content

Commit

Permalink
feat(v2): auto switch theme depending on the system theme (#2117)
Browse files Browse the repository at this point in the history
  • Loading branch information
lex111 authored and yangshun committed Dec 12, 2019
1 parent aa87bc5 commit 26a3d72
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions packages/docusaurus-theme-classic/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,29 @@ const noFlash = `(function() {
function setDataThemeAttribute(theme) {
document.querySelector('html').setAttribute('data-theme', theme);
}
var preferDarkQuery = '(prefers-color-scheme: dark)';
var mql = window.matchMedia(preferDarkQuery);
var supportsColorSchemeQuery = mql.media === preferDarkQuery;
var localStorageTheme = null;
try {
localStorageTheme = localStorage.getItem('${storageKey}');
} catch (err) {}
var localStorageExists = localStorageTheme !== null;
if (localStorageExists) {
setDataThemeAttribute(localStorageTheme);
} else if (supportsColorSchemeQuery && mql.matches) {
function getPreferredTheme() {
var theme = null;
try {
theme = localStorage.getItem('${storageKey}');
} catch (err) {}
return theme;
}
var darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
darkQuery.addListener(function(e) {
if (getPreferredTheme() !== null) {
return;
}
setDataThemeAttribute(e.matches ? 'dark' : '');
});
var preferredTheme = getPreferredTheme();
if (preferredTheme !== null) {
setDataThemeAttribute(preferredTheme);
} else if (darkQuery.matches) {
setDataThemeAttribute('dark');
}
})();`;
Expand Down

0 comments on commit 26a3d72

Please sign in to comment.