forked from taniarascia/taniarascia.com
-
Notifications
You must be signed in to change notification settings - Fork 6
/
gatsby-ssr.js
54 lines (45 loc) · 1.5 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
43
44
45
46
47
48
49
50
51
52
53
54
const React = require("react")
exports.onRenderBody = ({ setHtmlAttributes, setHeadComponents }) => {
setHtmlAttributes({
lang: "en"
})
setHeadComponents([
// https://victorzhou.com/blog/dark-mode-gatsby/
// https://github.com/vzhou842/victorzhou.com/blob/master/gatsby-ssr.js
<script key="theme" dangerouslySetInnerHTML={{
__html: `
(function() {
function setTheme(theme) {
if (theme === 'dark') {
document.documentElement.className = 'dark';
} else {
document.documentElement.className = 'light';
}
window.theme = theme;
};
window.setPreferredTheme = function(theme) {
setTheme(theme);
try {
localStorage.setItem('preferred-theme', theme);
} catch (e) {}
};
var preferredTheme;
try {
preferredTheme = localStorage.getItem('preferred-theme');
} catch (e) {}
window.themeListeners = [];
var darkQuery = window.matchMedia('(prefers-color-scheme: dark)');
darkQuery.addListener(function(e) {
window.setPreferredTheme(e.matches ? 'dark' : 'light');
window.themeListeners.forEach(function(listener) {
listener();
});
});
setTheme(preferredTheme || (darkQuery.matches ? 'dark' : 'light'));
})();
`
.replace(/\n/g, ' ')
.replace(/ {2}/g, ''),
}} />,
]);
}