feat(v2): add ability set dark mode by default (#2597)

* feat(v2): add ability set dark mode by default

* s/forceDarkMode/defaultDarkMode

Co-authored-by: Yangshun Tay <tay.yang.shun@gmail.com>
This commit is contained in:
Alexey Pyltsyn 2020-04-17 14:19:55 +03:00 committed by GitHub
parent ea5a50c4de
commit 14f4ef875a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 5 deletions

View file

@ -11,7 +11,9 @@ const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin')
// Need to be inlined to prevent dark mode FOUC
// Make sure that the 'storageKey' is the same as the one in `/theme/hooks/useTheme.js`
const storageKey = 'theme';
const noFlash = `(function() {
const noFlash = (defaultDarkMode) => `(function() {
var defaultDarkMode = ${defaultDarkMode};
function setDataThemeAttribute(theme) {
document.documentElement.setAttribute('data-theme', theme);
}
@ -30,7 +32,7 @@ const noFlash = `(function() {
var preferredTheme = getPreferredTheme();
if (preferredTheme !== null) {
setDataThemeAttribute(preferredTheme);
} else if (darkQuery.matches) {
} else if (darkQuery.matches || defaultDarkMode) {
setDataThemeAttribute('dark');
}
})();`;
@ -39,8 +41,11 @@ module.exports = function (context, options) {
const {
siteConfig: {themeConfig},
} = context;
const {disableDarkMode = false, prism: {additionalLanguages = []} = {}} =
themeConfig || {};
const {
disableDarkMode = false,
defaultDarkMode = false,
prism: {additionalLanguages = []} = {},
} = themeConfig || {};
const {customCss} = options || {};
return {
@ -85,7 +90,7 @@ module.exports = function (context, options) {
attributes: {
type: 'text/javascript',
},
innerHTML: noFlash,
innerHTML: noFlash(defaultDarkMode),
},
],
};

View file

@ -25,6 +25,18 @@ module.exports = {
};
```
With the enabled `defaultDarkMode` option you could set dark mode by default. However, in this case, the user's preference will not be taken into account until they manually sets the desired mode via toggle in the navbar.
```js {4} title="docusaurus.config.js"
module.exports = {
// ...
themeConfig: {
defaultDarkMode: true,
// ...
},
};
```
### Meta image
You can configure a default image that will be used for your meta tag, in particular `og:image` and `twitter:image`.