Automatically resizing form previews

This commit is contained in:
2022-01-19 21:45:46 -05:00
parent 9268d3880f
commit 52c75c8a43
3 changed files with 97 additions and 14 deletions

View File

@@ -0,0 +1,77 @@
/**
* WordPress dependencies
*/
import * as React from 'react';
import * as _ from 'lodash';
import { baseUrl } from '@/globals';
type PreviewProps = {
formId: string;
embedCode: string;
};
type PreviewState = {
uniqueId: string;
};
class PreviewForm extends React.Component<PreviewProps, PreviewState> {
constructor( props: any ) {
super( props );
// Generate a unique identifier, so that the embed script can be identified
// and removed from the page once it is no longer needed.
this.state = {
uniqueId: _.uniqueId(),
};
}
componentDidMount() {
this.loadEmbedScript();
}
componentWillUnmount() {
this.removeEmbedScript();
}
// Force the embed script to load, which makes Iframes in the editor resize properly.
loadEmbedScript( callback?: Function ) {
const existingScript = document.getElementById( `cog-embed-script-${ this.state.uniqueId }` );
if ( ! existingScript ) {
const script = document.createElement( 'script' );
script.src = `${ baseUrl }/f/iframe.js`;
script.id = `cog-embed-script-${ this.state.uniqueId }`;
document.body.appendChild( script );
script.onload = () => {
if ( callback ) callback();
};
}
if ( existingScript && callback ) callback();
}
// Clean up before block is removed
removeEmbedScript() {
const existingScript = document.getElementById( `cog-embed-script-${ this.state.uniqueId }` );
if ( existingScript ) {
existingScript.remove();
}
}
render() {
return (
<div>
<div className="focus-grabber"></div>
<div
className="cog-wp-embed cog-wp-embed__preview"
dangerouslySetInnerHTML={ { __html: this.props.embedCode } } // Must be Iframe embed code as others do not work in Gutenberg
></div>
</div>
);
}
}
export default PreviewForm;