Skip to content

Commit

Permalink
Use own emotion cache to support adding styles to the shadow root
Browse files Browse the repository at this point in the history
  • Loading branch information
tchock committed Dec 21, 2024
1 parent 90cb5a2 commit f2f58e2
Showing 1 changed file with 32 additions and 18 deletions.
50 changes: 32 additions & 18 deletions src/theme/PabloThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import { defaultTheme } from './defaultTheme';
import { PabloTheme, ComponentStyles, PabloThemeProviderProps } from './types';
import { pabloThemeContext, pabloComponentStylesContext, rootContext } from './context';
import { themeVarNames } from './themeVars';
import { css, Global, ThemeProvider } from '@emotion/react';
import { prefixer } from 'stylis';
import createCache from '@emotion/cache';
import { css, Global, ThemeProvider, CacheProvider } from '@emotion/react';

const overwriteMerge = (_, sourceArray) => sourceArray;
const isMergeableObject = (val) => isObject(val) && !Array.isArray(val) && !(val instanceof Map);
Expand All @@ -25,7 +27,7 @@ function createThemeVarDefinitions(theme: any, keyNameObject: any) {
export const PabloThemeProvider = ({
theme = {},
componentStyles = {},
root,
root = document,
children,
}: PabloThemeProviderProps) => {
const mergedTheme = merge(defaultTheme, theme, {
Expand All @@ -36,6 +38,16 @@ export const PabloThemeProvider = ({

const mergedComponentStyles = merge(defaultComponentStyles, componentStyles) as ComponentStyles;

const emotionCache = React.useMemo(
() =>
createCache({
key: 'app',
container: root instanceof Document ? root.head : root,
stylisPlugins: [prefixer],
}),
[root]
);

const styledTheme = React.useMemo(
() => ({
...mergedTheme,
Expand All @@ -45,21 +57,23 @@ export const PabloThemeProvider = ({
);

return (
<rootContext.Provider value={root || document}>
<ThemeProvider theme={styledTheme}>
<Global
styles={css`
:root {
${createThemeVarDefinitions(mergedTheme, themeVarNames)}
}
`}
/>
<pabloThemeContext.Provider value={mergedTheme}>
<pabloComponentStylesContext.Provider value={mergedComponentStyles}>
{children}
</pabloComponentStylesContext.Provider>
</pabloThemeContext.Provider>
</ThemeProvider>
</rootContext.Provider>
<CacheProvider value={emotionCache}>
<rootContext.Provider value={root}>
<ThemeProvider theme={styledTheme}>
<Global
styles={css`
:root {
${createThemeVarDefinitions(mergedTheme, themeVarNames)}
}
`}
/>
<pabloThemeContext.Provider value={mergedTheme}>
<pabloComponentStylesContext.Provider value={mergedComponentStyles}>
{children}
</pabloComponentStylesContext.Provider>
</pabloThemeContext.Provider>
</ThemeProvider>
</rootContext.Provider>
</CacheProvider>
);
};

0 comments on commit f2f58e2

Please sign in to comment.