@@ -4,30 +4,52 @@ import { Props } from "./Visualization";
44export function HTMLVisualization ( { content } : Props ) {
55 const iframeRef = useRef < HTMLIFrameElement > ( null ) ;
66
7- const handleIframeLoad = ( ) => {
8- if ( iframeRef . current ) {
9- const contentHeight = iframeRef . current . contentWindow ?. document . documentElement . scrollHeight ;
10- iframeRef . current . height = contentHeight ? `${ contentHeight } px` : "100%" ;
11- }
12- } ;
13-
147 useEffect ( ( ) => {
15- handleIframeLoad ( ) ;
16- window . addEventListener ( "resize" , handleIframeLoad ) ;
8+ const iframe = iframeRef . current ;
9+ if ( ! iframe ) return ;
10+
11+ let resizeObserver : ResizeObserver | null = null ;
12+
13+ const adjustHeight = ( ) => {
14+ if ( iframe . contentWindow ) {
15+ const contentHeight = iframe . contentWindow . document . documentElement . scrollHeight ;
16+ iframe . style . height = contentHeight ? `${ contentHeight } px` : "100%" ;
17+ }
18+ } ;
19+
20+ const handleLoad = ( ) => {
21+ // Disconnect previous observer if it exists
22+ if ( resizeObserver ) {
23+ resizeObserver . disconnect ( ) ;
24+ }
25+
26+ const iframeDoc = iframe . contentWindow ?. document . documentElement ;
27+ if ( ! iframeDoc ) return ;
28+
29+ // ResizeObserver watches for any size changes in the iframe content
30+ resizeObserver = new ResizeObserver ( ( ) => {
31+ adjustHeight ( ) ;
32+ } ) ;
33+
34+ resizeObserver . observe ( iframeDoc ) ;
35+
36+ // Initial height adjustment
37+ adjustHeight ( ) ;
38+ } ;
39+
40+ iframe . addEventListener ( "load" , handleLoad ) ;
41+
1742 return ( ) => {
18- window . removeEventListener ( "resize" , handleIframeLoad ) ;
43+ iframe . removeEventListener ( "load" , handleLoad ) ;
44+ if ( resizeObserver ) {
45+ resizeObserver . disconnect ( ) ;
46+ }
1947 } ;
2048 } , [ ] ) ;
2149
2250 return (
2351 < div >
24- < iframe
25- className = "w-full"
26- title = "Secure HTML Content"
27- ref = { iframeRef }
28- srcDoc = { content }
29- onLoad = { handleIframeLoad }
30- />
52+ < iframe className = "w-full" title = "Secure HTML Content" ref = { iframeRef } srcDoc = { content } />
3153 </ div >
3254 ) ;
3355}
0 commit comments