docusaurus/packages/docusaurus-theme-classic/src/index.js
Alexey Pyltsyn 14f4ef875a
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>
2020-04-17 19:19:55 +08:00

99 lines
2.4 KiB
JavaScript

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const path = require('path');
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 = (defaultDarkMode) => `(function() {
var defaultDarkMode = ${defaultDarkMode};
function setDataThemeAttribute(theme) {
document.documentElement.setAttribute('data-theme', theme);
}
function getPreferredTheme() {
var theme = null;
try {
theme = localStorage.getItem('${storageKey}');
} catch (err) {}
return theme;
}
var darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
var preferredTheme = getPreferredTheme();
if (preferredTheme !== null) {
setDataThemeAttribute(preferredTheme);
} else if (darkQuery.matches || defaultDarkMode) {
setDataThemeAttribute('dark');
}
})();`;
module.exports = function (context, options) {
const {
siteConfig: {themeConfig},
} = context;
const {
disableDarkMode = false,
defaultDarkMode = false,
prism: {additionalLanguages = []} = {},
} = themeConfig || {};
const {customCss} = options || {};
return {
name: 'docusaurus-theme-classic',
getThemePath() {
return path.resolve(__dirname, './theme');
},
getClientModules() {
return [
'infima/dist/css/default/default.css',
'remark-admonitions/styles/infima.css',
customCss,
path.resolve(__dirname, './prism-include-languages'),
];
},
configureWebpack() {
const prismLanguages = additionalLanguages
.map((lang) => `prism-${lang}`)
.join('|');
return {
plugins: [
new ContextReplacementPlugin(
/prismjs[\\/]components$/,
new RegExp(`^./(${prismLanguages})$`),
),
],
};
},
injectHtmlTags() {
if (disableDarkMode) {
return {};
}
return {
preBodyTags: [
{
tagName: 'script',
attributes: {
type: 'text/javascript',
},
innerHTML: noFlash(defaultDarkMode),
},
],
};
},
};
};