-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathAutoHeightImage.js
91 lines (81 loc) · 2.17 KB
/
AutoHeightImage.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
/**
* @since 2017-04-11 19:10:08
* @author vivaxy
*/
import React, { useEffect, useState, useRef } from 'react';
import ImagePolyfill from './ImagePolyfill';
import AnimatableImage from './AnimatableImage';
import PropTypes from 'prop-types';
import { getImageSizeFitWidth, getImageSizeFitWidthFromCache } from './cache';
import { NOOP, DEFAULT_HEIGHT } from './helpers';
// remove `resizeMode` props from `Image.propTypes`
const { resizeMode, ...ImagePropTypes } = AnimatableImage.propTypes;
function AutoHeightImage(props) {
const {
onHeightChange,
source,
width,
style,
maxHeight,
onError,
...rest
} = props;
const [height, setHeight] = useState(
getImageSizeFitWidthFromCache(source, width, maxHeight).height ||
DEFAULT_HEIGHT
);
const mountedRef = useRef(false);
useEffect(function () {
mountedRef.current = true;
return function () {
mountedRef.current = false;
};
}, []);
useEffect(
function () {
(async function () {
try {
const { height: newHeight } = await getImageSizeFitWidth(
source,
width,
maxHeight
);
if (mountedRef.current) {
// might trigger `onHeightChange` with same `height` value
// dedupe maybe?
setHeight(newHeight);
onHeightChange(newHeight);
}
} catch (e) {
onError(e);
}
})();
},
[source, onHeightChange, width, maxHeight]
);
// StyleSheet.create will cache styles, not what we want
const imageStyles = { width, height };
// Since it only makes sense to use polyfill with remote images
const ImageComponent = source.uri ? ImagePolyfill : AnimatableImage;
return (
<ImageComponent
source={source}
style={[imageStyles, style]}
onError={onError}
{...rest}
/>
);
}
AutoHeightImage.propTypes = {
...ImagePropTypes,
width: PropTypes.number.isRequired,
maxHeight: PropTypes.number,
onHeightChange: PropTypes.func,
animated: PropTypes.bool
};
AutoHeightImage.defaultProps = {
maxHeight: Infinity,
onHeightChange: NOOP,
animated: false
};
export default AutoHeightImage;