From 532703a04caa5661c8209a12ed8a2dd53b557b10 Mon Sep 17 00:00:00 2001 From: Ronald Langeveld Date: Wed, 21 Feb 2024 17:08:56 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fixed=20iFrame=20not=20keeping?= =?UTF-8?q?=20scroll=20position?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit no issue - Added position tracking in the iFrame to allow it to remain in the same place in the preview after making changes. --- .../src/utils/IframeBuffering.tsx | 30 +++++++++++++++++-- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/apps/admin-x-settings/src/utils/IframeBuffering.tsx b/apps/admin-x-settings/src/utils/IframeBuffering.tsx index 9ca8b52ff4..0e7b3c136a 100644 --- a/apps/admin-x-settings/src/utils/IframeBuffering.tsx +++ b/apps/admin-x-settings/src/utils/IframeBuffering.tsx @@ -12,7 +12,8 @@ type IframeBufferingProps = { const IframeBuffering: React.FC = ({generateContent, className, height, width, parentClassName, testId, addDelay = false}) => { const [visibleIframeIndex, setVisibleIframeIndex] = useState(0); - const iframes = [useRef(null), useRef(null)]; + const iframes = [useRef(null), useRef(null)]; // eslint-disable-line + const [scrollPosition, setScrollPosition] = useState(0); useEffect(() => { const invisibleIframeIndex = visibleIframeIndex === 0 ? 1 : 0; @@ -44,11 +45,34 @@ const IframeBuffering: React.FC = ({generateContent, class // eslint-disable-next-line react-hooks/exhaustive-deps }, [generateContent]); + // track the scroll position of the visible iframe and set scroll position of the invisible iframe + useEffect(() => { + const iframe = iframes[visibleIframeIndex].current; + const onScroll = () => { + setScrollPosition(iframe?.contentWindow?.scrollY || 0); + }; + + iframe?.contentWindow?.addEventListener('scroll', onScroll); + + return () => { + iframe?.contentWindow?.removeEventListener('scroll', onScroll); + }; + }, [visibleIframeIndex, iframes]); + + useEffect(() => { + const invisibleIframeIndex = visibleIframeIndex === 0 ? 1 : 0; + const iframe = iframes[invisibleIframeIndex].current; + + if (iframe) { + iframe.contentWindow?.scrollTo(0, scrollPosition); + } + }, [scrollPosition, visibleIframeIndex, iframes]); + return (