-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-ssr.js
54 lines (37 loc) · 1.57 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
import React from "react"
import { COLOURS } from "./src/styles/constants"
import { ThemeProvider } from "./src/styles/ThemeProvider"
const AssertColourScheme = () => {
const setCSSVarsOnClient = `
(function(){
function getInitialColourScheme() {
const persistedColourSchemePreference = window.localStorage.getItem('colour-scheme');
if(typeof persistedColourSchemePreference === 'string') {
return persistedColourSchemePreference;
}
const mediaQueryColourSchemePreference = window.matchMedia('(prefers-color-scheme: dark)');
if(typeof mediaQueryColourSchemePreference.matches === 'boolean') {
return mediaQueryColourSchemePreference.matches ? 'dark' : 'light';
}
return 'light';
}
const colourScheme = getInitialColourScheme();
const root = document.documentElement;
Object.entries(${JSON.stringify(
COLOURS
)}).forEach(([colourKey, colourValue]) => {
const cssVarName = '--colour-' + colourKey;
root.style.setProperty(cssVarName, colourValue[colourScheme])
})
root.style.setProperty('--initial-colour-scheme', colourScheme);
})()
`
return <script dangerouslySetInnerHTML={{ __html: setCSSVarsOnClient }} />
}
export const onRenderBody = ({ setPreBodyComponents }) =>
setPreBodyComponents(
<AssertColourScheme key={"script_assert_colour_scheme"} />
)
export const wrapRootElement = ({ element }) => (
<ThemeProvider>{element}</ThemeProvider>
)