({ children, ...rest })
| 14 | type Props = IframeHTMLAttributes<HTMLIFrameElement> & PropsWithChildren<unknown>; |
| 15 | |
| 16 | export const InlineFrame: FC<Props> = ({ children, ...rest }) => { |
| 17 | const iframeRef = useRef<HTMLIFrameElement>(null); |
| 18 | const [iframeLoaded, setIframeLoaded] = useState(false); |
| 19 | |
| 20 | const getInlineDocument = useCallback(() => iframeRef.current?.contentDocument, []); |
| 21 | |
| 22 | const syncStyles = useCallback(() => { |
| 23 | const inlineDocument = getInlineDocument(); |
| 24 | |
| 25 | if (inlineDocument) { |
| 26 | inlineDocument.head.innerHTML = document.head.innerHTML; |
| 27 | } |
| 28 | }, [getInlineDocument]); |
| 29 | |
| 30 | const renderFrameContents = useCallback(() => { |
| 31 | const inlineDocument = getInlineDocument(); |
| 32 | |
| 33 | if (!inlineDocument) { |
| 34 | return null; |
| 35 | } |
| 36 | |
| 37 | const inlineWindow = inlineDocument.defaultView ?? window; |
| 38 | |
| 39 | inlineDocument.head.innerHTML = document.head.innerHTML; |
| 40 | |
| 41 | return createPortal( |
| 42 | <InlineFrameProvider |
| 43 | value={{ |
| 44 | document: inlineDocument, |
| 45 | window: inlineWindow, |
| 46 | }} |
| 47 | > |
| 48 | {children} |
| 49 | </InlineFrameProvider>, |
| 50 | inlineDocument.body, |
| 51 | ); |
| 52 | }, [children, getInlineDocument]); |
| 53 | |
| 54 | useEffect(() => { |
| 55 | if (!iframeLoaded) { |
| 56 | return; |
| 57 | } |
| 58 | |
| 59 | const observer = new MutationObserver(syncStyles); |
| 60 | |
| 61 | observer.observe(document.head, { |
| 62 | childList: true, |
| 63 | subtree: true, |
| 64 | }); |
| 65 | |
| 66 | return () => { |
| 67 | observer.disconnect(); |
| 68 | }; |
| 69 | }, [iframeLoaded, syncStyles]); |
| 70 | |
| 71 | return ( |
| 72 | <iframe |
| 73 | {...rest} |
nothing calls this directly
no outgoing calls
no test coverage detected