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