File size: 1,435 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
import PropTypes from 'prop-types';
import { Component } from 'react';

/**
 * Module variables
 */
const LoadStatus = {
	PENDING: 'PENDING',
	LOADING: 'LOADING',
	LOADED: 'LOADED',
	FAILED: 'FAILED',
};
const noop = () => {};

export class ImageLoader extends Component {
	static propTypes = {
		src: PropTypes.string.isRequired,
		placeholder: PropTypes.element.isRequired,
		children: PropTypes.node,
	};

	constructor( props ) {
		super( props );

		this.image = new Image();
		this.image.src = props.src;
		this.image.onload = this.onLoadComplete;
		this.image.onerror = this.onLoadComplete;

		this.state = {
			status: LoadStatus.LOADING,
		};
	}

	componentWillUnmount() {
		this.destroyLoader();
	}

	destroyLoader = () => {
		if ( ! this.image ) {
			return;
		}

		this.image.onload = noop;
		this.image.onerror = noop;
		delete this.image;
	};

	onLoadComplete = ( event ) => {
		this.destroyLoader();

		this.setState( {
			status: 'load' === event.type ? LoadStatus.LOADED : LoadStatus.FAILED,
		} );
	};

	render() {
		const { children, placeholder, src } = this.props;
		const { status } = this.state;

		return (
			<div className="image-preloader">
				{ status === LoadStatus.LOADING && placeholder }
				{ /* eslint-disable-next-line jsx-a11y/alt-text */ }
				{ status === LoadStatus.LOADED && <img src={ src } /> }
				{ status === LoadStatus.FAILED && children }
			</div>
		);
	}
}

export default ImageLoader;