-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-ssr.tsx
57 lines (48 loc) · 1.55 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
import React from 'react';
import { GatsbySSR } from 'gatsby';
export const onRenderBody: GatsbySSR['onRenderBody'] = ({
setPreBodyComponents,
}) => setPreBodyComponents([<ColorSchemeDetector key="ColorSchemeDetector" />]);
/**
* Detects the initial color scheme preference of the user and stores it and CSS
* custom properties to be accessed by other scripts.
*
* This allows for the color scheme and theme to be set before the initial
* render of a React component, preventing a flash of an incorrect theme and
* other issues caused by static site generation.
*/
function ColorSchemeDetector() {
const detectColorScheme = `
(function() {
function getColorScheme() {
const storedScheme = window.localStorage.getItem('colorScheme');
if (storedScheme === 'light' || storedScheme === 'dark') {
return storedScheme;
}
const query = window.matchMedia('(prefers-color-scheme: light)');
return query.matches ? 'light' : 'dark';
}
const scheme = getColorScheme();
window.nathanielJLibertyInitialColorScheme = scheme;
const root = document.documentElement;
root.style.setProperty(
'--color-base',
scheme === 'light'
? '#fff'
: '#000'
);
root.style.setProperty(
'--color-contrast',
scheme === 'light'
? '#000'
: '#fff'
);
root.style.setProperty(
'--color-shroud',
scheme === 'light'
? '255, 255, 255'
: '0, 0, 0'
);
})()`;
return <script dangerouslySetInnerHTML={{ __html: detectColorScheme }} />;
}