| 1 |
import {useMemo, useRef, useState, useEffect, ReactNode} from 'react'; |
| 2 |
import {CacheProvider} from '@emotion/react'; |
| 3 |
import createCache from '@emotion/cache'; |
| 4 |
|
| 5 |
/** |
| 6 |
* Custom Cache Provider for react-select in WordPress 6.9+ Iframe Context |
| 7 |
* |
| 8 |
* In WordPress 6.9+, block editor content renders inside an iframe. |
| 9 |
* This component provides an Emotion cache configured to inject styles |
| 10 |
* into the correct document (the iframe's head instead of the parent's). |
| 11 |
* |
| 12 |
* This is similar to react-select's NonceProvider but adds the crucial |
| 13 |
* `container` option to target the iframe's document. |
| 14 |
*/ |
| 15 |
|
| 16 |
/** |
| 17 |
* @since 4.13.2 |
| 18 |
*/ |
| 19 |
type EmotionStylesProviderProps = { |
| 20 |
children: ReactNode; |
| 21 |
cacheKey?: string; |
| 22 |
}; |
| 23 |
|
| 24 |
/** |
| 25 |
* Provides an Emotion cache that injects styles into the current document. |
| 26 |
* This is essential for WordPress 6.9+ where blocks render in an iframe. |
| 27 |
* @since 4.13.2 |
| 28 |
*/ |
| 29 |
export default function EmotionStylesProvider({children, cacheKey = 'givewp'}: EmotionStylesProviderProps) { |
| 30 |
const containerRef = useRef<HTMLDivElement>(null); |
| 31 |
const [container, setContainer] = useState<HTMLElement | null>(null); |
| 32 |
|
| 33 |
// Get the correct document head after mount |
| 34 |
useEffect(() => { |
| 35 |
if (containerRef.current) { |
| 36 |
setContainer(containerRef.current.ownerDocument.head); |
| 37 |
} |
| 38 |
}, []); |
| 39 |
|
| 40 |
// Create cache with the container option to target the correct document |
| 41 |
const emotionCache = useMemo(() => { |
| 42 |
if (!container) { |
| 43 |
return null; |
| 44 |
} |
| 45 |
return createCache({ |
| 46 |
key: cacheKey, |
| 47 |
container: container, |
| 48 |
}); |
| 49 |
}, [cacheKey, container]); |
| 50 |
|
| 51 |
// Render a wrapper div to get the document reference |
| 52 |
// Use display:contents so it doesn't affect layout |
| 53 |
// IMPORTANT: Don't render children until cache is ready to ensure |
| 54 |
// Emotion styles are injected into the correct document from the start |
| 55 |
return ( |
| 56 |
<div ref={containerRef} style={{display: 'contents'}}> |
| 57 |
{emotionCache && ( |
| 58 |
<CacheProvider value={emotionCache}> |
| 59 |
{children} |
| 60 |
</CacheProvider> |
| 61 |
)} |
| 62 |
</div> |
| 63 |
); |
| 64 |
} |
| 65 |
|