import { type EmotionCache } from '@emotion/utils'
import * as React from 'react'
import { useContext, forwardRef } from 'react'
import createCache from '@emotion/cache'
import { isBrowser } from './utils'
let EmotionCacheContext: React.Context<EmotionCache | null> =
React.createContext(
typeof HTMLElement !== 'undefined'
? createCache({ key: 'css' })
: null
)
if (process.env.NODE_ENV !== 'production') {
EmotionCacheContext.displayName = 'EmotionCacheContext'
}
export let CacheProvider = EmotionCacheContext.Provider
export let __unsafe_useEmotionCache =
function useEmotionCache(): EmotionCache | null {
return useContext(EmotionCacheContext)
}
let withEmotionCache = function withEmotionCache<Props, Ref: React.Ref<*>>(
func: (props: Props, cache: EmotionCache, ref: Ref) => React.Node
): React.AbstractComponent<Props> {
return forwardRef((props: Props, ref: Ref) => {
let cache = ((useContext(EmotionCacheContext): any): EmotionCache)
return func(props, cache, ref)
})
}
if (!isBrowser) {
withEmotionCache = function withEmotionCache<Props>(
func: (props: Props, cache: EmotionCache) => React.Node
): React.StatelessFunctionalComponent<Props> {
return (props: Props) => {
let cache = useContext(EmotionCacheContext)
if (cache === null) {
cache = createCache({ key: 'css' })
return (
<EmotionCacheContext.Provider value={cache}>
{func(props, cache)}
</EmotionCacheContext.Provider>
)
} else {
return func(props, cache)
}
}
}
}
export { withEmotionCache }