-
Notifications
You must be signed in to change notification settings - Fork 496
/
gatsby-ssr.tsx
30 lines (28 loc) · 1.2 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
import * as React from 'react';
import { wrapRootElement as wrap } from './root-wrapper';
import { themeKey } from './src/context/UserDataContext/UserDataContext';
export const wrapRootElement = wrap;
// https://joshwcomeau.com/gatsby/dark-mode/
const MagicScriptTag = () => {
// Note: see also src/context/UserDataContext/UserDataContext.ts if any of the below code needs to be changed.
const codeToRunOnClient = `
(function(){
var dark = false;
var pref = window.localStorage.getItem('${themeKey}');
if (typeof pref === 'string' && pref === '"dark"') dark = true;
else if (typeof pref !== 'string' || (typeof pref === 'string' && pref === '"system"')) {
const mql = window.matchMedia('(prefers-color-scheme: dark)');
const hasMediaQueryPreference = typeof mql.matches === 'boolean';
if (hasMediaQueryPreference) {
dark = mql.matches;
}
}
if (dark) document.documentElement.classList.add('dark');
})()
`;
// eslint-disable-next-line react/no-danger
return <script dangerouslySetInnerHTML={{ __html: codeToRunOnClient }} />;
};
export const onRenderBody = ({ setPreBodyComponents }) => {
setPreBodyComponents(<MagicScriptTag key="magic-script-tag" />);
};