-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-ssr.tsx
71 lines (59 loc) · 2 KB
/
gatsby-ssr.tsx
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import React from "react"
import { darkTheme, lightTheme } from "./src/theme/themeVariables"
import { Layout } from "./src/components/layout"
import { GlobalProvider } from "./src/context/globalState"
import type { GatsbySSR } from "gatsby"
// Unfortunately this work around seems to be the only way
// to load in dark mode without flickering from light mode first
// Thanks to Josh W Comeau for sharing his solution that I've adapted below
// https://www.joshwcomeau.com/react/dark-mode/
const ScriptInjection = () => {
const codeToRunOnClient = `(() => {
const darkTheme = ${JSON.stringify(darkTheme)}
const lightTheme = ${JSON.stringify(lightTheme)}
const root = document.documentElement
const themePreviouslySet = localStorage.getItem("theme")
const prefersDark = matchMedia?.("(prefers-color-scheme: dark)").matches
let theme, themeName
if (themePreviouslySet) {
themeName = themePreviouslySet
switch (themePreviouslySet) {
case "dark":
theme = darkTheme
break
case "light":
theme = lightTheme
break
default:
theme = lightTheme
}
} else if (prefersDark) {
theme = darkTheme
themeName = "dark"
}
else {
theme = lightTheme
themeName = "light"
}
Object.entries(theme).forEach(
([key, value]) => {
const cssVarName = \`--\${key}\`
root.style.setProperty(cssVarName, value)
}
)
root.setAttribute("theme", themeName)
})()`
// eslint-disable-next-line react/no-danger
return <script dangerouslySetInnerHTML={{ __html: codeToRunOnClient }} />
}
export const onRenderBody: GatsbySSR["onRenderBody"] = ({
setPreBodyComponents,
}) => {
setPreBodyComponents([<ScriptInjection key="🔑" />])
}
export const wrapRootElement: GatsbySSR["wrapRootElement"] = ({ element }) => (
<GlobalProvider>{element}</GlobalProvider>
)
export const wrapPageElement: GatsbySSR["wrapPageElement"] = ({ element }) => (
<Layout>{element}</Layout>
)