From f4e220b23b3d3659fbf1086041b0361bdbc7f154 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Wed, 11 Dec 2019 22:48:38 +0300 Subject: [PATCH] feat(v2): auto switch theme depending on the system theme --- .../docusaurus-theme-classic/src/index.js | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/packages/docusaurus-theme-classic/src/index.js b/packages/docusaurus-theme-classic/src/index.js index 2a177761bae6..ba2eaed5e5dc 100644 --- a/packages/docusaurus-theme-classic/src/index.js +++ b/packages/docusaurus-theme-classic/src/index.js @@ -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'); } })();`;