forked from layer5io/layer5
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added onRenderBody to have IIFE script after body
Signed-off-by: Randy Lau <[email protected]>
- Loading branch information
1 parent
debf651
commit 6f0c020
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import React from "react"; | ||
import { DarkThemeKey, ThemeSetting } from "./src/theme/app/ThemeManager.js"; | ||
import lighttheme, { darktheme } from "./src/theme/app/themeStyles"; | ||
|
||
const themes = { light: lighttheme, dark: darktheme }; | ||
|
||
const MagicScriptTag = (props) => { | ||
const codeToRunOnClient = ` | ||
(function() { | ||
const themeFromLocalStorage = localStorage.getItem('${DarkThemeKey}') || '${ThemeSetting.SYSTEM}'; | ||
const systemDarkModeSetting = () => window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null; | ||
const isDarkModeActive = () => { | ||
return !!systemDarkModeSetting()?.matches; | ||
}; | ||
let colorMode; | ||
switch (themeFromLocalStorage) { | ||
case '${ThemeSetting.SYSTEM}': | ||
colorMode = isDarkModeActive() ? '${ThemeSetting.DARK}' : '{ThemeSetting.LIGHT}' | ||
break | ||
case '${ThemeSetting.DARK}': | ||
case '${ThemeSetting.LIGHT}': | ||
colorMode = themeFromLocalStorage | ||
break | ||
default: | ||
colorMode = '${ThemeSetting.LIGHT}' | ||
} | ||
const root = document.documentElement; | ||
const iterate = (obj) => { | ||
Object.keys(obj).forEach(key => { | ||
if (typeof obj[key] === 'object') { | ||
iterate(obj[key]) | ||
} else { | ||
root.style.setProperty("--" + key, obj[key]) | ||
} | ||
}) | ||
} | ||
const parsedTheme = JSON.parse('${JSON.stringify(props.theme)}') | ||
const theme = parsedTheme[colorMode] | ||
iterate(theme) | ||
root.style.setProperty('--initial-color-mode', colorMode); | ||
})() | ||
`; | ||
return <script dangerouslySetInnerHTML={{ __html: codeToRunOnClient }} />; | ||
}; | ||
|
||
export const onRenderBody = ( { setPreBodyComponents }) => { | ||
setPreBodyComponents(<MagicScriptTag key="theme-injection" theme={themes} />); | ||
}; |