Skip to content

Commit

Permalink
Fix sandbox html refresh bug (#20176)
Browse files Browse the repository at this point in the history
* Force rerender of Sandbox component when html prop changes
  • Loading branch information
glendaviesnz authored Feb 13, 2020
1 parent c5eb962 commit 5a5564b
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 4 deletions.
13 changes: 9 additions & 4 deletions packages/components/src/sandbox/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ class Sandbox extends Component {
this.trySandbox();
}

componentDidUpdate() {
this.trySandbox();
componentDidUpdate( prevProps ) {
const forceRerender = prevProps.html !== this.props.html;

this.trySandbox( forceRerender );
}

isFrameAccessible() {
Expand Down Expand Up @@ -69,13 +71,16 @@ class Sandbox extends Component {
}
}

trySandbox() {
trySandbox( forceRerender = false ) {
if ( ! this.isFrameAccessible() ) {
return;
}

const body = this.iframe.current.contentDocument.body;
if ( null !== body.getAttribute( 'data-resizable-iframe-connected' ) ) {
if (
! forceRerender &&
null !== body.getAttribute( 'data-resizable-iframe-connected' )
) {
return;
}

Expand Down
75 changes: 75 additions & 0 deletions packages/components/src/sandbox/test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* External dependencies
*/
import ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';

/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';

/**
* Internal dependencies
*/
import Sandbox from '../';

let container;

const TestWrapper = () => {
const [ html, setHtml ] = useState(
'<iframe class="mock-iframe" src="https://super.embed"></iframe>'
);

const updateHtml = () => {
setHtml(
'<iframe class="mock-iframe" src="https://another.super.embed"></iframe>'
);
};

return (
<div>
<button onClick={ updateHtml } className="mock-button">
Mock Button
</button>
<Sandbox html={ html } />
</div>
);
};

beforeEach( () => {
container = document.createElement( 'div' );
document.body.appendChild( container );
} );

afterEach( () => {
document.body.removeChild( container );
container = null;
} );

it( 'should rerender with new emdeded content if html prop changes', () => {
act( () => {
ReactDOM.render( <TestWrapper />, container );
} );

const button = container.querySelector( '.mock-button' );
const iframe = container.querySelector( '.components-sandbox' );

let sandboxedIframe = iframe.contentWindow.document.body.querySelector(
'.mock-iframe'
);

expect( sandboxedIframe.src ).toEqual( 'https://super.embed/' );

act( () => {
button.dispatchEvent(
new window.MouseEvent( 'click', { bubbles: true } )
);
} );

sandboxedIframe = iframe.contentWindow.document.body.querySelector(
'.mock-iframe'
);

expect( sandboxedIframe.src ).toEqual( 'https://another.super.embed/' );
} );

0 comments on commit 5a5564b

Please sign in to comment.