File size: 2,389 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
91
92
93
94
95
import { css } from '@emotion/css';
import clsx from 'clsx';
import { ReactNode } from 'react';
import './style.scss';
import { MShotsOptions, useMshotsImg } from './use-mshots-img';
import { getTextColorFromBackground } from './utils';

export type SizeCss = { width: number; height: number };

export const DEFAULT_THUMBNAIL_SIZE = { width: 106, height: 76.55 };

const DEFAULT_CLASSNAME = css( DEFAULT_THUMBNAIL_SIZE );

const VIEWPORT_BASE = 1200;

type Props = {
	alt: string;
	backgroundColor?: string;
	className?: string;
	mShotsUrl?: string;
	width?: number;
	height?: number;
	dimensionsSrcset?: Array< SizeCss >;
	sizesAttr?: string;
	children?: ReactNode;
	bgColorImgUrl?: string;
	viewport?: number;
	mshotsOption?: MShotsOptions;
};

export const SiteThumbnail = ( {
	backgroundColor,
	children,
	className,
	alt,
	mShotsUrl = '',
	bgColorImgUrl,
	width = DEFAULT_THUMBNAIL_SIZE.width,
	height = DEFAULT_THUMBNAIL_SIZE.height,
	dimensionsSrcset = [],
	sizesAttr = '',
	viewport = VIEWPORT_BASE,
	mshotsOption,
}: Props ) => {
	const options: MShotsOptions = {
		vpw: viewport,
		vph: viewport,
		w: width,
		h: height,
		...mshotsOption,
	};
	const { imgProps, isLoading, isError } = useMshotsImg( mShotsUrl, options, [
		...dimensionsSrcset,
		{ width, height },
	] );

	const color = backgroundColor && getTextColorFromBackground( backgroundColor );

	const classes = clsx(
		'site-thumbnail',
		isLoading ? 'site-thumbnail-loading' : 'site-thumbnail-visible',
		DEFAULT_CLASSNAME,
		className
	);

	const showLoader = mShotsUrl && ! isError;
	const mshotIsFullyLoaded = imgProps.src && ! isError && ! isLoading;

	const blurSize = width > DEFAULT_THUMBNAIL_SIZE.width ? 'medium' : 'small';

	return (
		<div className={ classes } style={ { backgroundColor, color } }>
			{ !! bgColorImgUrl && ! mshotIsFullyLoaded && (
				<div
					className={ `site-thumbnail__image-bg site-thumbnail__image-blur-${ blurSize }` }
					style={ { backgroundImage: `url(${ bgColorImgUrl })` } }
				></div>
			) }
			{ ( isLoading || isError ) && (
				<div className={ clsx( { 'site-thumbnail-loader': showLoader }, 'site-thumbnail-icon' ) }>
					{ children }
				</div>
			) }
			{ imgProps.src && ! isLoading && ! isError && (
				<img
					className="site-thumbnail__image"
					alt={ alt }
					sizes={ sizesAttr || `${ width }px` }
					{ ...imgProps }
				/>
			) }
		</div>
	);
};