Skip to content

Commit

Permalink
Fix legacy widget previews (#32260)
Browse files Browse the repository at this point in the history
* Fix legacy widget block previews being set to zero height

* Use intersection observer with load event

* Use or instead of nullish-coalescing operator
  • Loading branch information
talldan authored and youknowriad committed May 31, 2021
1 parent a44a226 commit a712639
Showing 1 changed file with 34 additions and 7 deletions.
41 changes: 34 additions & 7 deletions packages/block-library/src/legacy-widget/edit/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,44 @@ import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { useRefEffect } from '@wordpress/compose';
import { addQueryArgs } from '@wordpress/url';
import { useState } from '@wordpress/element';
import { Placeholder, Spinner, Disabled } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

export default function Preview( { idBase, instance, isVisible } ) {
const [ iframeHeight, setIframeHeight ] = useState( null );
const [ iframeHeight, setIframeHeight ] = useState();

// Resize the iframe on either the load event, or when the iframe becomes visible.
const ref = useRefEffect( ( iframe ) => {
function onChange() {
const boundingRect = iframe?.contentDocument?.body?.getBoundingClientRect();
if ( boundingRect ) {
// Include `top` in the height calculation to avoid the bottom
// of widget previews being cut-off. Most widgets have a
// heading at the top that has top margin, and the `height`
// alone doesn't take that margin into account.
setIframeHeight( boundingRect.top + boundingRect.height );
}
}

const { IntersectionObserver } = iframe.ownerDocument.defaultView;

// Observe for intersections that might cause a change in the height of
// the iframe, e.g. a Widget Area becoming expanded.
const intersectionObserver = new IntersectionObserver( onChange, {
threshold: 1,
} );
intersectionObserver.observe( iframe );

iframe.addEventListener( 'load', onChange );

return () => {
iframe.removeEventListener( 'load', onChange );
};
}, [] );

return (
<>
{ /*
Expand Down Expand Up @@ -41,6 +72,7 @@ export default function Preview( { idBase, instance, isVisible } ) {
load scripts and styles that it needs to run.
*/ }
<iframe
ref={ ref }
className="wp-block-legacy-widget__edit-preview-iframe"
title={ __( 'Legacy Widget Preview' ) }
// TODO: This chokes when the query param is too big.
Expand All @@ -53,12 +85,7 @@ export default function Preview( { idBase, instance, isVisible } ) {
instance,
},
} ) }
height={ iframeHeight ?? 100 }
onLoad={ ( event ) => {
setIframeHeight(
event.target.contentDocument.body.scrollHeight
);
} }
height={ iframeHeight || 100 }
/>
</Disabled>
</div>
Expand Down

0 comments on commit a712639

Please sign in to comment.