/** * WordPress dependencies */ import { useEffect, useState } from '@safe-wordpress/element'; /** * External dependencies */ import { doesNetworkRequire, doesNetworkSupport, } from '@nelio-content/networks'; import { getAllUrls } from '@nelio-content/utils'; import type { SocialProfile } from '@nelio-content/types'; /** * Internal dependencies */ import { NoPreview } from './no-preview'; import { useActiveSocialNetwork, usePreview, usePreviewAttributes, useSharedLinkLoaderEffect, } from '../../hooks'; import type { PreviewComponent } from './preview-components'; let getPreviewComponent: ( ( activeProfile: SocialProfile ) => PreviewComponent | null ) | undefined; let getPreviewComponentPromise: Promise< typeof getPreviewComponent > | undefined; export const MessagePreview = (): JSX.Element | null => { const [ isVisible ] = usePreview(); const attrs = usePreviewAttributes(); const urls = getAllUrls( attrs.textComputed ); const activeNetwork = useActiveSocialNetwork(); const PreviewComponent = usePreviewComponent( attrs.activeProfile ); useSharedLinkLoaderEffect( urls ); const isRequired = doesNetworkRequire( 'preview', activeNetwork ); if ( ! isRequired ) { if ( ! isVisible ) { return null; } const isSupported = doesNetworkSupport( 'preview', activeNetwork ); if ( ! isSupported ) { return null; } } if ( ! attrs.activeProfile ) { return ; } if ( ! PreviewComponent ) { return null; } return (
); }; // ======= // HELPERS // ======= function usePreviewComponent( activeProfile?: SocialProfile ): PreviewComponent | null | undefined { const [ PreviewComponent, setPreviewComponent ] = useState< PreviewComponent | null | undefined >( () => activeProfile ? getPreviewComponent?.( activeProfile ) : null ); useEffect( () => { if ( ! activeProfile ) { setPreviewComponent( null ); return; } if ( getPreviewComponent ) { setPreviewComponent( () => getPreviewComponent?.( activeProfile ) ); return; } let isMounted = true; getPreviewComponentPromise ??= import( /* webpackChunkName: "social-message-previews" */ './preview-components' ).then( ( module ) => { getPreviewComponent = module.getPreviewComponent; return getPreviewComponent; } ); void getPreviewComponentPromise.then( ( getter ) => { if ( isMounted ) { setPreviewComponent( () => getter?.( activeProfile ) ); } } ); return () => { isMounted = false; }; }, [ activeProfile ] ); return PreviewComponent; }