File size: 1,587 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import { CacheProvider, EmotionCache } from "@emotion/react"
import {
createContext,
useContext,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react"
import { createEmotionCache } from "./emotion-cache"
export interface ClientStyleContextData {
reset: () => void
}
export const ClientStyleContext = createContext<ClientStyleContextData>({
reset: () => {},
})
export const useClientStyleContext = () => {
return useContext(ClientStyleContext)
}
interface ClientCacheProviderProps {
children: React.ReactNode
}
export function ClientCacheProvider({ children }: ClientCacheProviderProps) {
const [cache, setCache] = useState(createEmotionCache())
const context = useMemo(
() => ({
reset() {
setCache(createEmotionCache())
},
}),
[],
)
return (
<ClientStyleContext.Provider value={context}>
<CacheProvider value={cache}>{children}</CacheProvider>
</ClientStyleContext.Provider>
)
}
const useSafeLayoutEffect =
typeof window === "undefined" ? () => {} : useLayoutEffect
export function useInjectStyles(cache: EmotionCache) {
const styles = useClientStyleContext()
const injectRef = useRef(true)
useSafeLayoutEffect(() => {
if (!injectRef.current) return
cache.sheet.container = document.head
const tags = cache.sheet.tags
cache.sheet.flush()
tags.forEach((tag) => {
const sheet = cache.sheet as unknown as {
_insertTag: (tag: HTMLStyleElement) => void
}
sheet._insertTag(tag)
})
styles.reset()
injectRef.current = false
}, [])
}
|