File size: 2,445 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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 = /(?<protocol>https?:\/\/)?(?<address>.*)/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 (
				<img src={ mShotUrl } alt="Website screenshot preview" className="import__screenshot" />
			);
		}

		return (
			<div className="import__screenshot-loading">
				<LoadingEllipsis />
			</div>
		);
	};

	return (
		<div className="import__preview">
			<div className="import__preview-wrapper">
				<div role="presentation" className="import__preview-bar">
					<div role="presentation" className="import__preview-bar-dot" />
					<div role="presentation" className="import__preview-bar-dot" />
					<div role="presentation" className="import__preview-bar-dot" />
					{ websiteMatch && (
						<div className="import__preview-url-field">
							<div dir="ltr">
								<span>{ websiteMatch?.groups?.protocol }</span>
								{ websiteMatch?.groups?.address }
							</div>
						</div>
					) }
				</div>
				<Screenshot />
			</div>
		</div>
	);
};

export default memo(
	ImportPreview,
	( prevProps: Props, nextProps: Props ) => prevProps?.website === nextProps?.website
);