-
Notifications
You must be signed in to change notification settings - Fork 5
/
gatsby-ssr.js
42 lines (35 loc) · 1.28 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
42
/*eslint-env node */
const React = require('react')
// Adds the dark mode class name to the html element before render,
// using an inline script to void a flash of white in dark mode
exports.onRenderBody = ({ setHeadComponents }) => {
const script = `
function setColorScheme(scheme) {
// Remove the current scheme
document.documentElement.classList.remove(
scheme === 'light' ? 'dark' : 'light'
)
// Add the new scheme
document.documentElement.classList.add(scheme)
}
var isDarkMode =
localStorage.colorScheme === 'dark' ||
(!('colorScheme' in localStorage) &&
window.matchMedia('(prefers-color-scheme: dark)').matches)
setColorScheme(isDarkMode ? 'dark' : 'light')
// Listen for system color scheme changes
window.matchMedia('(prefers-color-scheme: dark)').addListener(function(e) {
// Change the theme if the user hasn't explicitly toggled it
// (indicated by the presence of colorScheme local storage)
if (!('colorScheme' in localStorage)) {
setColorScheme(e.matches ? 'dark' : 'light')
}
})
`
setHeadComponents([
<script
key='dark-mode-script'
dangerouslySetInnerHTML={{ __html: script }}
></script>,
])
}