-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatsby-ssr.js
41 lines (30 loc) · 1.24 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
import theme from "./src/theme/theme";
import React from "react";
function setColorsByTheme() {
const colors = "🎨";
const colorModeKey = "🔑";
const colorModeCssProp = "🎇";
let colorMode = "dark";
const persistedColorPreference = window.localStorage.getItem(colorModeKey);
const hastPersistedPreference = typeof persistedColorPreference === "string";
const mql = window.matchMedia("(prefers-color-scheme: dark)");
if (hastPersistedPreference) colorMode = persistedColorPreference;
else colorMode = mql.matches ? "dark" : "light";
let root = document.documentElement;
root.style.setProperty(colorModeCssProp, colorMode);
for (const [colorName, colorValue] of Object.entries(colors[colorMode])) {
const cssVarName = `--color-${colorName}`;
root.style.setProperty(cssVarName, colorValue);
}
}
const MagicScriptTag = () => {
const boundFn = String(setColorsByTheme)
.replace(`"🎨"`, JSON.stringify(theme))
.replace("🔑", "color-mode")
.replace("🎇", "--initial-color-mode");
let calledFunction = `(${boundFn})()`;
return <script dangerouslySetInnerHTML={{ __html: calledFunction }} />;
};
export const onRenderBody = ({ setPreBodyComponents }) => {
setPreBodyComponents(<MagicScriptTag />);
};