🐛 Fixed iFrame not keeping scroll position on update (#19725)

no issue

- Added position tracking in the iFrame to allow it to remain in the
same place in the preview after making changes.
This commit is contained in:
Ronald Langeveld 2024-02-21 17:28:47 +02:00 committed by GitHub
parent c64c0c2123
commit ef1c19820b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -12,7 +12,8 @@ type IframeBufferingProps = {
const IframeBuffering: React.FC<IframeBufferingProps> = ({generateContent, className, height, width, parentClassName, testId, addDelay = false}) => {
const [visibleIframeIndex, setVisibleIframeIndex] = useState(0);
const iframes = [useRef<HTMLIFrameElement>(null), useRef<HTMLIFrameElement>(null)];
const iframes = [useRef<HTMLIFrameElement>(null), useRef<HTMLIFrameElement>(null)]; // eslint-disable-line
const [scrollPosition, setScrollPosition] = useState(0);
useEffect(() => {
const invisibleIframeIndex = visibleIframeIndex === 0 ? 1 : 0;
@ -44,11 +45,32 @@ const IframeBuffering: React.FC<IframeBufferingProps> = ({generateContent, class
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [generateContent]);
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 iframe = iframes[visibleIframeIndex].current;
if (iframe) {
iframe.contentWindow?.scrollTo(0, scrollPosition);
}
}, [scrollPosition, visibleIframeIndex, iframes]);
return (
<div className={parentClassName} data-testid={testId}>
<iframe
ref={iframes[0]}
className={`${className} ${visibleIframeIndex !== 0 ? 'z-10 opacity-0' : 'z-20 opacity-100'}`}
className={`${className} ${visibleIframeIndex !== 0 ? 'invisible z-10' : 'z-20'}`}
data-visible={visibleIframeIndex === 0}
frameBorder="0"
height={height}
@ -58,7 +80,7 @@ const IframeBuffering: React.FC<IframeBufferingProps> = ({generateContent, class
<iframe
ref={iframes[1]}
className={`${className} ${visibleIframeIndex !== 1 ? 'z-10 opacity-0' : 'z-20 opacity-100'}`}
className={`${className} ${visibleIframeIndex !== 1 ? 'invisible z-10' : 'z-20'}`}
data-visible={visibleIframeIndex === 1}
frameBorder="0"
height={height}