-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-ssr.js
65 lines (51 loc) · 1.71 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
55
56
57
58
59
60
61
62
63
64
65
/**
* Much of this code deals with dark mode. It's ripped straight from:
* @see https://joshwcomeau.com/gatsby/dark-mode/
*
* Huge thanks to Josh for outlining how to do this
*/
import React from "react"
import Terser from "terser"
import {
theme,
INITIAL_COLOR_MODE_CSS_PROP,
} from "./src/constants"
/**
* DARK MODE CODE
*
* Prevents the "flash" of light mode
*/
/**
* Trust me, I know that it looks like we're reading entries from an emoji
* but what's really happening is that this function is being converted to a
* string, then mutated by "MagicScriptTag" in order to add in dynamic code
* into that string. This way, we're able to avoid duplicating
*/
function setColorsByTheme() {
const theme = "🌈"
const colorModeCssProp = "⚡️"
const mql = window.matchMedia("(prefers-color-scheme: dark)")
const prefersDarkFromMQ = mql.matches
let colorMode = "light"
colorMode = prefersDarkFromMQ ? "dark" : "light"
let root = document.documentElement
root.style.setProperty(colorModeCssProp, colorMode)
const colors = theme[colorMode];
Object.entries(colors).forEach(([name, color]) => {
const cssVarName = `--${name}`
root.style.setProperty(cssVarName, color)
})
}
const MagicScriptTag = () => {
const boundFn = String(setColorsByTheme)
.replace('"🌈"', JSON.stringify(theme))
.replace("⚡️", INITIAL_COLOR_MODE_CSS_PROP)
let calledFunction = `(${boundFn})()`
calledFunction = Terser.minify(calledFunction).code
// eslint-disable-next-line react/no-danger
return <script dangerouslySetInnerHTML={{ __html: calledFunction }} />
}
export const onRenderBody = ({ setPreBodyComponents }) => {
// Set the dark mode script
setPreBodyComponents(<MagicScriptTag />)
}