| 1 |
import { useLayoutEffect, useRef, useState } from '@wordpress/element'; |
| 2 |
|
| 3 |
const VIEWPORT_WIDTH = Math.max(window.innerWidth, 1400); |
| 4 |
|
| 5 |
export const useIframeScale = () => { |
| 6 |
const containerRef = useRef(null); |
| 7 |
const bodyObserverRef = useRef(null); |
| 8 |
const [scale, setScale] = useState(1); |
| 9 |
const [contentHeight, setContentHeight] = useState(null); |
| 10 |
|
| 11 |
useLayoutEffect(() => { |
| 12 |
const el = containerRef.current; |
| 13 |
if (!el) return; |
| 14 |
const obs = new ResizeObserver(([entry]) => { |
| 15 |
setScale(entry.contentRect.width / VIEWPORT_WIDTH); |
| 16 |
}); |
| 17 |
obs.observe(el); |
| 18 |
return () => { |
| 19 |
obs.disconnect(); |
| 20 |
bodyObserverRef.current?.disconnect(); |
| 21 |
}; |
| 22 |
}, []); |
| 23 |
|
| 24 |
const handleIframeLoad = (e) => { |
| 25 |
const iframeDoc = e.target.contentDocument; |
| 26 |
if (!iframeDoc?.body) return; |
| 27 |
|
| 28 |
const updateHeight = () => { |
| 29 |
const height = iframeDoc.body.scrollHeight; |
| 30 |
if (height) setContentHeight(height); |
| 31 |
}; |
| 32 |
|
| 33 |
updateHeight(); |
| 34 |
|
| 35 |
bodyObserverRef.current?.disconnect(); |
| 36 |
const obs = new ResizeObserver(updateHeight); |
| 37 |
obs.observe(iframeDoc.body); |
| 38 |
bodyObserverRef.current = obs; |
| 39 |
}; |
| 40 |
|
| 41 |
return { containerRef, scale, contentHeight, handleIframeLoad }; |
| 42 |
}; |
| 43 |
|