UNPKG

@selfcommunity/react-core

Version:

React Core Components useful for integrating UI Community components (react-ui).

76 lines (72 loc) 2.68 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, useContext, useState } from 'react'; import ThemeProvider from '@mui/material/styles/ThemeProvider'; import getTheme from '../../../themes/theme'; import { useSCContext } from '../SCContextProvider'; import { useSCPreferences } from '../SCPreferencesProvider'; import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect'; /** * Creates Global Context * :::tip Context can be consumed in one of the following ways: ```jsx 1. <SCThemeContext.Consumer>{(theme,) => (...)}</SCThemeContext.Consumer> ``` ```jsx 2. const scThemeContext: SCThemeContextType = useContext(SCThemeContext); ``` ```jsx 3. const scThemeContext: SCThemeContextType = useSCTheme(); ```` ::: */ export const SCThemeContext = createContext({}); /** * #### Description: * This component makes the `theme` available down the React tree. * It should preferably be used at **the root of your component tree**. * See: https://mui.com/system/styled/ * * @param children * @return * ```jsx * <SCThemeContext.Provider value={{theme, setTheme: setCustomTheme}}> * <ThemeProvider theme={theme}>{children}</ThemeProvider> * </SCThemeContext.Provider> * ``` */ export default function SCThemeProvider({ children = null }) { const scContext = useSCContext(); const scPreferencesContext = useSCPreferences(); const [theme, setTheme] = useState(getTheme(scContext.settings.theme, scPreferencesContext.preferences)); /** * Set custom theme * Merge with scPreferencesContext.preferences * @param theme */ const setCustomTheme = (theme) => { setTheme(getTheme(theme, scPreferencesContext.preferences)); }; /** * Update theme if initial conf changes */ useDeepCompareEffectNoCheck(() => { setCustomTheme(theme); }, [scContext.settings.theme]); return (_jsx(SCThemeContext.Provider, Object.assign({ value: { theme, setTheme: setCustomTheme } }, { children: _jsx(ThemeProvider, Object.assign({ theme: theme }, { children: children })) }))); } /** * Export hoc to inject the base theme to components * @param Component */ export const withSCTheme = (Component) => (props) => { const scThemeContext = useContext(SCThemeContext); return (_jsx(ThemeProvider, Object.assign({ theme: scThemeContext.theme }, { children: _jsx(Component, Object.assign({ setTheme: scThemeContext.setTheme }, props)) }))); }; /** * Let's only export the `useSCTheme` hook instead of the context. * We only want to use the hook directly and never the context component. */ export function useSCTheme() { return useContext(SCThemeContext); }