1 |
|
2 |
|
3 |
|
4 | import { Component } from '@wordpress/element';
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | import { View, Image } from 'react-native';
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | import { calculatePreferedImageSize } from './utils';
|
15 |
|
16 | class ImageSize extends Component {
|
17 | constructor() {
|
18 | super( ...arguments );
|
19 | this.state = {
|
20 | width: undefined,
|
21 | height: undefined,
|
22 | };
|
23 | this.onLayout = this.onLayout.bind( this );
|
24 | }
|
25 |
|
26 | componentDidUpdate( prevProps ) {
|
27 | if ( this.props.src !== prevProps.src ) {
|
28 | this.image = {};
|
29 |
|
30 | this.setState( {
|
31 | width: undefined,
|
32 | height: undefined,
|
33 | } );
|
34 | this.fetchImageSize();
|
35 | }
|
36 |
|
37 | if ( this.props.dirtynessTrigger !== prevProps.dirtynessTrigger ) {
|
38 | this.calculateSize();
|
39 | }
|
40 | }
|
41 |
|
42 | componentDidMount() {
|
43 | this.fetchImageSize();
|
44 | }
|
45 |
|
46 | fetchImageSize() {
|
47 | Image.getSize( this.props.src, ( width, height ) => {
|
48 | this.image = { width, height };
|
49 | this.calculateSize();
|
50 | } );
|
51 | }
|
52 |
|
53 | calculateSize() {
|
54 | if ( this.image === undefined || this.container === undefined ) {
|
55 | return;
|
56 | }
|
57 | const { width, height } = calculatePreferedImageSize( this.image, this.container );
|
58 | this.setState( { width, height } );
|
59 | }
|
60 |
|
61 | onLayout( event ) {
|
62 | const { width, height } = event.nativeEvent.layout;
|
63 | this.container = {
|
64 | clientWidth: width,
|
65 | clientHeight: height,
|
66 | };
|
67 | this.calculateSize();
|
68 | }
|
69 |
|
70 | render() {
|
71 | const sizes = {
|
72 | imageWidth: this.image && this.image.width,
|
73 | imageHeight: this.image && this.image.height,
|
74 | containerWidth: this.container && this.container.width,
|
75 | containerHeight: this.container && this.container.height,
|
76 | imageWidthWithinContainer: this.state.width,
|
77 | imageHeightWithinContainer: this.state.height,
|
78 | };
|
79 | return (
|
80 | <View onLayout={ this.onLayout }>
|
81 | { this.props.children( sizes ) }
|
82 | </View>
|
83 | );
|
84 | }
|
85 | }
|
86 |
|
87 | export default ImageSize;
|