From 275cdd4db947f7a26104584c03666f1782a3a2ff Mon Sep 17 00:00:00 2001 From: Ronald Langeveld Date: Thu, 14 Dec 2023 06:54:39 +0200 Subject: [PATCH] Added performance adjustments to Portal iFrames (#19373) refs PROD-4 --- .../membership/portal/PortalFrame.tsx | 43 +++++++++++++------ 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/apps/admin-x-settings/src/components/settings/membership/portal/PortalFrame.tsx b/apps/admin-x-settings/src/components/settings/membership/portal/PortalFrame.tsx index 47cbf6185e..ae9cacf78f 100644 --- a/apps/admin-x-settings/src/components/settings/membership/portal/PortalFrame.tsx +++ b/apps/admin-x-settings/src/components/settings/membership/portal/PortalFrame.tsx @@ -1,37 +1,51 @@ -import React, {useEffect, useRef, useState} from 'react'; +import React, {useCallback, useEffect, useRef, useState} from 'react'; type PortalFrameProps = { - selectedTab?: string; href: string; + onLoaded?: (iframe: HTMLIFrameElement) => void; + onDestroyed?: () => void; + selectedTab?: string; } -// we should refactor this to be reused in offers as well -const PortalFrame: React.FC = ({selectedTab, href}) => { +const PortalFrame: React.FC = ({href, onLoaded, onDestroyed, selectedTab}) => { if (!selectedTab) { selectedTab = 'signup'; } - const iframeRef = useRef(null); - const [portalReady, setPortalReady] = useState(false); + const [isInvisible, setIsInvisible] = useState(true); + // Handler for making the iframe visible, memoized with useCallback + const makeVisible = useCallback(() => { + setTimeout(() => { + setIsInvisible(false); + if (onLoaded && iframeRef.current) { + onLoaded(iframeRef.current); + } + }, 100); // Delay to allow scripts to render + }, [onLoaded]); // Dependencies for useCallback + + // Effect for attaching message listener useEffect(() => { - const messageListener = (event: MessageEvent<'portal-ready' | {type: string}>) => { + const messageListener = (event: MessageEvent) => { if (!href) { return; } - const srcURL = new URL(href); const originURL = new URL(event.origin); - if (originURL.origin === srcURL.origin) { + if (originURL.origin === new URL(href).origin) { if (event.data === 'portal-ready' || event.data.type === 'portal-ready') { - setPortalReady(true); + makeVisible(); } } }; window.addEventListener('message', messageListener, true); - return () => window.removeEventListener('message', messageListener, true); - }, [href]); + + return () => { + window.removeEventListener('message', messageListener, true); + onDestroyed?.(); + }; + }, [href, onDestroyed, makeVisible]); if (!href) { return null; @@ -41,13 +55,14 @@ const PortalFrame: React.FC = ({selectedTab, href}) => { <> + onLoad={makeVisible} + /> ); };