Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Image block: fix resize listener #22277

Merged
merged 3 commits into from
May 19, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess there's no meaningful difference between addEventListener( 'load', fn ) and onload = fn ? (Aside from the ability to have multiple event handlers in the former, which doesn't apply here anyways)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exactly. I like the consistency and it's clearer how the listener is removed.

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 );