UNPKG

@hitachivantara/uikit-react-core

Version:
86 lines (85 loc) 2.45 kB
import { getContainerElement } from "../utils/document.js"; import { setElementAttrs } from "../utils/theme.js"; import { createMuiTheme } from "./utils.js"; import { useEffect, useMemo, useState } from "react"; import { jsx } from "react/jsx-runtime"; import { ThemeProvider, useColorScheme } from "@mui/material/styles"; import { EmotionContext, HvThemeContext, defaultCacheKey, defaultEmotionCache } from "@hitachivantara/uikit-react-shared"; //#region src/providers/ThemeProvider.tsx function HvThemeProviderInner({ children, theme, colorMode: colorModeProp, themeRootId: rootId }) { const [colorModeValue, setColorModeValue] = useState(colorModeProp); const { setMode } = useColorScheme(); /** safe `colorMode`, ensuring no invalid values are used */ const colorMode = colorModeValue === "dark" ? "dark" : "light"; useEffect(() => { setColorModeValue(colorModeProp); setMode(colorModeProp); }, [colorModeProp]); useEffect(() => { const element = getContainerElement(rootId); if (!element) return; setElementAttrs(element, theme.name, colorMode); }, [ colorMode, rootId, theme.name ]); const value = useMemo(() => ({ colorModes: ["light", "dark"], selectedMode: colorMode, changeMode(newMode = colorMode) { setColorModeValue(newMode); setMode(newMode); }, rootId, activeTheme: { ...theme, colors: { ...theme.colors, modes: { ...theme.colors, light: { ...theme.colors.light, type: "light" }, dark: { ...theme.colors.dark, type: "dark" } } } }, themes: [theme], selectedTheme: theme.name, changeTheme(_theme, mode) { setColorModeValue(mode); setMode(mode); } }), [ theme, colorMode, setMode, rootId ]); return /* @__PURE__ */ jsx(HvThemeContext.Provider, { value, children }); } function HvThemeProvider(props) { const { theme, emotionCache, colorMode } = props; const muiTheme = useMemo(() => { return createMuiTheme(theme); }, [theme]); const emotionCacheValue = useMemo(() => ({ cache: emotionCache }), [emotionCache]); return /* @__PURE__ */ jsx(ThemeProvider, { theme: muiTheme, defaultMode: colorMode, children: /* @__PURE__ */ jsx(EmotionContext.Provider, { value: emotionCacheValue, children: /* @__PURE__ */ jsx(HvThemeProviderInner, { ...props }) }) }); } //#endregion export { EmotionContext, HvThemeContext, HvThemeProvider, defaultCacheKey, defaultEmotionCache };