-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-ssr.js
94 lines (75 loc) · 2.42 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
92
93
94
import * as React from "react";
import {COLORS} from "./src/utils/colors";
import {
COLOR_MODE_KEY,
INITIAL_COLOR_MODE_CSS_PROP,
} from "./src/utils/constants";
import {minify} from "html-minifier-terser";
import {App} from "./src/components/App";
const minifyOptions = {
collapseWhitespace: true,
keepClosingSlash: true,
minifyCSS: true,
minifyJS: true,
minifyURLs: true,
removeComments: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
};
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})()`;
calledFunction = minify(calledFunction, minifyOptions);
return <script dangerouslySetInnerHTML={{__html: calledFunction}} />;
};
const FallbackStyles = () => {
const cssVariableString = Object.entries(COLORS).reduce(
(acc, [name, colorByTheme]) => {
return `${acc}\n--color-${name}: ${colorByTheme.light};`;
},
""
);
const wrappedInSelector = minify(
`html { ${cssVariableString} }`,
minifyOptions
);
return <style>{wrappedInSelector}</style>;
};
export const onRenderBody = ({
setHeadComponents,
setPreBodyComponents,
setPostBodyComponents,
}) => {
setHeadComponents(<FallbackStyles key="fallBackTheme" />);
setPreBodyComponents(<MagicScriptTag key="manageDarkTheme" />);
setPostBodyComponents(() => <div>Dove finisce questo?</div>);
};
export const wrapPageElement = ({element}) => {
return <App>{element}</App>;
};