forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgressiveImage.js
99 lines (86 loc) · 2.07 KB
/
ProgressiveImage.js
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
96
97
98
99
import * as React from 'react';
export class ProgressiveImage extends React.Component {
constructor(props) {
super(props);
this.state = {
image: props.placeholder,
isLoading: true
};
}
componentDidMount() {
const {
src
} = this.props;
if (src) {
this.loadImage(src);
}
}
componentDidUpdate(prevProps) {
const {
src,
placeholder
} = prevProps; // We only invalidate the current image if the src has changed.
if (src && src !== this.props.src) {
this.setState({
image: placeholder,
isLoading: true
}, () => {
this.loadImage(src);
});
}
}
componentWillUnmount() {
if (this.image) {
this.image.onload = null;
this.image.onerror = null;
}
}
loadImage = src => {
// If there is already an image we nullify the onload
// and onerror props so it does not incorrectly set state
// when it resolves
if (this.image) {
this.image.onload = null;
this.image.onerror = null;
}
const image = new Image();
this.image = image;
image.onload = this.onLoad;
image.onerror = this.onError;
image.src = src;
};
onLoad = () => {
const {
naturalWidth,
naturalHeight
} = this.image; // use this.image.src instead of this.props.src to
// avoid the possibility of props being updated and the
// new imageisLoading before the new props are available as
// this.props.
this.setState({
naturalHeight,
naturalWidth,
aspectRatio: naturalHeight / naturalWidth,
orientation: naturalWidth > naturalHeight ? 'landscape' : 'portrait',
image: this.image.src,
isLoading: false
});
};
onError = errorEvent => {
const {
onError
} = this.props;
if (onError) {
onError(errorEvent);
}
};
render() {
const {
children
} = this.props;
if (!children || typeof children !== 'function') {
throw new Error(`ProgressiveImage requires a function as its only child`);
}
return children(this.state);
}
}