-
Notifications
You must be signed in to change notification settings - Fork 1
/
gatsby-ssr.js
53 lines (39 loc) · 1.45 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
import React from 'react'
import { COLORS, COLOR_MODE_KEY, INITIAL_COLOR_MODE_CSS_PROP } from './src/constants'
import App from './src/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}`
root.style.setProperty(cssVarName, colorByTheme[colorMode])
})
}
const MagicScriptTag = () => {
const boundFn = String(setColorsByTheme)
.replace("'🌈'", JSON.stringify(COLORS))
.replace('🔑', COLOR_MODE_KEY)
.replace('⚡️', INITIAL_COLOR_MODE_CSS_PROP)
let calledFunction = `(${boundFn})()`
// eslint-disable-next-line react/no-danger
return <script dangerouslySetInnerHTML={{ __html: calledFunction }} />
}
export const onRenderBody = ({ setPreBodyComponents }) => {
setPreBodyComponents(<MagicScriptTag />)
}
export const wrapPageElement = ({ element }) => {
return <App>{element}</App>
}