-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgatsby-ssr.tsx
More file actions
53 lines (47 loc) · 1.66 KB
/
gatsby-ssr.tsx
File metadata and controls
53 lines (47 loc) · 1.66 KB
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
import React from "react";
import type { GatsbySSR } from "gatsby";
// Based on following implementation:
// https://github.com/insin/gatsby-plugin-dark-mode
export const onRenderBody: GatsbySSR["onRenderBody"] = ({
setPreBodyComponents,
}) => {
setPreBodyComponents([
<script
id="dark-mode"
key="dark-mode"
// biome-ignore lint/security/noDangerouslySetInnerHtml: <No injection RISK - DONE FULLY DURING SSG>
dangerouslySetInnerHTML={{
__html: `
void function() {
window.__onThemeChange = function() {}
var preferredTheme
try {
preferredTheme = localStorage.getItem('theme')
} catch (err) { }
function setTheme(newTheme) {
if (preferredTheme && document.body.classList.contains(preferredTheme)) {
document.body.classList.replace(preferredTheme, newTheme)
} else {
document.body.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'))
}()
`,
}}
/>,
]);
};