-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-ssr.js
83 lines (63 loc) · 2.48 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
import React from 'react';
import Terser from 'terser';
import { Layout } from './src/components';
import { COLOR_MODE_KEY, COLORS, INITIAL_COLOR_MODE_CSS_PROP } from './src/styles/constants';
// https://www.joshwcomeau.com/react/dark-mode/
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 = `--${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})()`;
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--${name}: ${colorByTheme.light};`;
}, '');
const wrappedInSelector = `html { ${cssVariableString} }`;
return <style>{wrappedInSelector}</style>;
};
export const onRenderBody = ({ setPreBodyComponents, setHeadComponents }) => {
setHeadComponents(<FallbackStyles />);
setPreBodyComponents(<MagicScriptTag />);
};
export const wrapPageElement = ({ element, props }) => {
return <Layout {...props}>{element}</Layout>;
};