import { useWindowDimensions } from '@automattic/viewport'; import { memo, useState } from 'react'; import { LoadingEllipsis } from 'calypso/components/loading-ellipsis'; import { MShotParams } from '../types'; import type { FunctionComponent } from 'react'; /* eslint-disable wpcalypso/jsx-classname-namespace */ interface Props { website: string; } const protocolRgx = /(?https?:\/\/)?(?
.*)/i; const ImportPreview: FunctionComponent< Props > = ( { website } ) => { const [ mShotUrl, setMShotUrl ] = useState( '' ); const { width } = useWindowDimensions(); const mShotParams: MShotParams = { scale: 2, vpw: width <= 640 ? 640 : undefined, }; const websiteMatch = website.match( protocolRgx ); const checkScreenshot = ( screenShotUrl: string ) => { const http = new XMLHttpRequest(); http.open( 'GET', screenShotUrl ); http.onreadystatechange = () => { if ( http.readyState !== http.HEADERS_RECEIVED ) { return; } if ( http.getResponseHeader( 'Content-Type' ) !== 'image/jpeg' ) { setTimeout( () => { checkScreenshot( screenShotUrl ); }, 5000 ); } else { setMShotUrl( screenShotUrl ); } }; http.send(); }; checkScreenshot( `https://s0.wp.com/mshots/v1/${ website }?${ Object.entries( mShotParams ) .filter( ( entry ) => !! entry[ 1 ] ) .map( ( [ key, val ] ) => key + '=' + val ) .join( '&' ) }` ); const Screenshot = () => { if ( mShotUrl !== '' ) { return ( Website screenshot preview ); } return (
); }; return (
{ websiteMatch && (
{ websiteMatch?.groups?.protocol } { websiteMatch?.groups?.address }
) }
); }; export default memo( ImportPreview, ( prevProps: Props, nextProps: Props ) => prevProps?.website === nextProps?.website );