-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-ssr.js
49 lines (45 loc) · 1.76 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
import React from 'react'
import DefaultLayout from './src/layouts/default-layout'
// provide a custom script for persisting and altering the preferred-color-mode setting
// this will get loaded in "onRenderBody", to inject the script in window-only environments
// ! see 'src/components/Theme/ThemeProvider.tsx' for usage details on the theme
const ThemeScript = () => {
const calledFnc = `
(function() {
window.__onThemeChange = function () {}
function setTheme(newTheme) {
window.__theme = newTheme
preferredTheme = newTheme
document.body.className = newTheme
window.__onThemeChange(newTheme)
}
var preferredTheme
try {
preferredTheme = localStorage.getItem('PREFERRED_THEME')
} catch (err) {}
window.__setPreferredTheme = function (newTheme) {
setTheme(newTheme)
try {
localStorage.setItem('PREFERRED_THEME', newTheme)
} catch (err) {}
}
var darkQuery = window.matchMedia('(prefers-color-scheme: dark)')
darkQuery.addEventListener('change', function (e) {
window.__setPreferredTheme(e.matches ? 'dark' : 'light')
})
setTheme(preferredTheme || (darkQuery.matches ? 'dark' : 'light'))
})()
`
// eslint-disable-next-line react/no-danger
return <script key='themeScript' dangerouslySetInnerHTML={{ __html: calledFnc }} />
}
export const onRenderBody = ({ setPreBodyComponents }) => {
setPreBodyComponents(<ThemeScript key='themeScript' />)
}
// wrap the page element with DefaultLayout
// to prevent remounting navbar etc.
export const wrapPageElement = ({ element, props }) => {
// props provide same data to Layout as Page element will get
// including location, data, etc - you don't need to pass it
return <DefaultLayout {...props}>{element}</DefaultLayout>
}