|
3 | 3 | import { consoleLightTheme, theme as themeContract } from '@ultraviolet/themes' |
4 | 4 | import { assignInlineVars } from '@vanilla-extract/dynamic' |
5 | 5 | import type { ReactNode } from 'react' |
6 | | -import { createContext, useContext } from 'react' |
| 6 | +import { createContext, useContext, useEffect } from 'react' |
7 | 7 |
|
8 | 8 | const ThemeContext = createContext(consoleLightTheme) |
9 | 9 |
|
@@ -31,14 +31,37 @@ type ThemeProviderProps = { |
31 | 31 | } |
32 | 32 |
|
33 | 33 | /** |
34 | | - * ThemeProvider will apply generated global CSS variables to the application. |
| 34 | + * ThemeProvider will apply generated global CSS variables to the application in the `<head>`. |
35 | 35 | * If no theme is provided, it will default to `lightTheme`. |
36 | 36 | */ |
37 | 37 | export const ThemeProvider = ({ |
38 | 38 | children, |
39 | 39 | theme = consoleLightTheme, |
40 | | -}: ThemeProviderProps) => ( |
41 | | - <ThemeContext.Provider value={theme}> |
42 | | - <div style={assignInlineVars(themeContract, theme)}>{children}</div> |
43 | | - </ThemeContext.Provider> |
44 | | -) |
| 40 | +}: ThemeProviderProps) => { |
| 41 | + useEffect(() => { |
| 42 | + const styleId = 'uv-theme' |
| 43 | + const existingStyle = document.getElementById(styleId) |
| 44 | + const cssVars = assignInlineVars(themeContract, theme) |
| 45 | + const cssString = `:root { ${Object.entries(cssVars) |
| 46 | + .map(([key, value]) => `${key}: ${value};`) |
| 47 | + .join(' ')} }` |
| 48 | + |
| 49 | + if (existingStyle) { |
| 50 | + existingStyle.textContent = cssString |
| 51 | + } else { |
| 52 | + const style = document.createElement('style') |
| 53 | + style.id = styleId |
| 54 | + style.textContent = cssString |
| 55 | + document.head.appendChild(style) |
| 56 | + } |
| 57 | + |
| 58 | + return () => { |
| 59 | + const style = document.getElementById(styleId) |
| 60 | + if (style) { |
| 61 | + style.remove() |
| 62 | + } |
| 63 | + } |
| 64 | + }, [theme]) |
| 65 | + |
| 66 | + return <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider> |
| 67 | +} |
0 commit comments