-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-ssr.js
41 lines (40 loc) · 1.17 KB
/
gatsby-ssr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const React = require("react");
exports.onRenderBody = function ({ setPreBodyComponents }) {
setPreBodyComponents([
React.createElement("script", {
key: "gatsby-dark-mode",
dangerouslySetInnerHTML: {
__html: `
void function() {
window.__onThemeChange = function() {}
var preferredTheme
try {
preferredTheme = localStorage.getItem('theme')
} catch (err) { }
function setTheme(newTheme) {
if (preferredTheme && document.documentElement.classList.contains(preferredTheme)) {
document.documentElement.classList.replace(preferredTheme, newTheme)
} else {
document.documentElement.classList.add(newTheme)
}
window.__theme = newTheme
preferredTheme = newTheme
window.__onThemeChange(newTheme)
}
window.__setPreferredTheme = function(newTheme) {
setTheme(newTheme)
try {
localStorage.setItem('theme', newTheme)
} catch (err) {}
}
var darkQuery = window.matchMedia('(prefers-color-scheme: dark)')
darkQuery.addListener(function(e) {
window.__setPreferredTheme(e.matches ? 'dark' : 'light')
})
setTheme(preferredTheme || (darkQuery.matches ? 'dark' : 'light'))
}()
`,
},
}),
]);
};