Skip to content

Commit

Permalink
Image block: fix resize listener (#22277)
Browse files Browse the repository at this point in the history
* New hook: useGlobalEvent

* Add docs

* Remove useGlobalEvent
  • Loading branch information
ellatrix authored May 19, 2020
1 parent 532844f commit 4bb758d
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions packages/block-library/src/image/image-size.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
/**
* WordPress dependencies
*/
import { withGlobalEvents } from '@wordpress/compose';
import { useRef, useState, useEffect } from '@wordpress/element';

/**
* Internal dependencies
*/
import { calculatePreferedImageSize } from './utils';

function ImageSize( { src, dirtynessTrigger, children } ) {
export default function ImageSize( { src, dirtynessTrigger, children } ) {
const ref = useRef();
const [ state, setState ] = useState( {
imageWidth: null,
Expand All @@ -21,9 +20,10 @@ function ImageSize( { src, dirtynessTrigger, children } ) {
} );

useEffect( () => {
const image = new window.Image();
const { defaultView } = ref.current.ownerDocument;
const image = new defaultView.Image();

image.onload = () => {
function calculateSize() {
const { width, height } = calculatePreferedImageSize(
image,
ref.current
Expand All @@ -37,18 +37,17 @@ function ImageSize( { src, dirtynessTrigger, children } ) {
imageWidthWithinContainer: width,
imageHeightWithinContainer: height,
} );
};
}

defaultView.addEventListener( 'resize', calculateSize );
image.addEventListener( 'load', calculateSize );
image.src = src;

return () => {
image.onload = undefined;
defaultView.removeEventListener( 'resize', calculateSize );
image.removeEventListener( 'load', calculateSize );
};
}, [ src, dirtynessTrigger ] );

return <div ref={ ref }>{ children( state ) }</div>;
}

export default withGlobalEvents( {
resize: 'calculateSize',
} )( ImageSize );

0 comments on commit 4bb758d

Please sign in to comment.