-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathgatsby-ssr.js
91 lines (71 loc) · 2.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import React from 'react'
import Terser from 'terser'
import {
COLOR_MODE_KEY,
COLORS,
INITIAL_COLOR_MODE_CSS_PROP,
} from './src/tokens/colors'
import App from './src/components/App'
function setColorsByTheme() {
const colors = '🌈'
const colorModeKey = '🔑'
const colorModeCssProp = '⚡️'
const mql = window.matchMedia('(prefers-color-scheme: dark)')
const prefersDarkFromMQ = mql.matches
const persistedPreference = localStorage.getItem(colorModeKey)
let colorMode = 'light'
const hasUsedToggle = typeof persistedPreference === 'string'
if (hasUsedToggle) {
colorMode = persistedPreference
} else {
colorMode = prefersDarkFromMQ ? 'dark' : 'light'
}
let root = document.documentElement
root.style.setProperty(colorModeCssProp, colorMode)
Object.entries(colors).forEach(([name, colorByTheme]) => {
const cssVarName = `--color-${name}`
typeof colorByTheme === 'object'
? root.style.setProperty(cssVarName, colorByTheme[colorMode])
: root.style.setProperty(cssVarName, colorByTheme)
})
}
const MagicScriptTag = () => {
const boundFn = String(setColorsByTheme)
.replace("'🌈'", JSON.stringify(COLORS))
.replace('🔑', COLOR_MODE_KEY)
.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 }} />
}
/**
* If the user has JS disabled, the injected script will never fire!
* This means that they won't have any colors set, everything will be default
* black and white.
* We can solve for this by injecting a `<style>` tag into the head of the
* document, which sets default values for all of our colors.
* Only light mode will be available for users with JS disabled.
*/
const FallbackStyles = () => {
// Create a string holding each CSS variable:
/*
`--color-text: black;
--color-background: white;`
*/
const cssVariableString = Object.entries(COLORS).reduce(
(acc, [name, colorByTheme]) => {
return `${acc}\n--color-${name}: ${colorByTheme.light};`
},
''
)
const wrappedInSelector = `html { ${cssVariableString} }`
return <style>{wrappedInSelector}</style>
}
export const onRenderBody = ({ setPreBodyComponents, setHeadComponents }) => {
setHeadComponents(<FallbackStyles />)
setPreBodyComponents(<MagicScriptTag />)
}
export const wrapPageElement = ({ element }) => {
return <App>{element}</App>
}