Skip to content

Commit

Permalink
Fix the preview of function-based widgets
Browse files Browse the repository at this point in the history
  • Loading branch information
adamziel committed Aug 27, 2020
1 parent 6c6eb26 commit 92463cd
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2 deletions.
3 changes: 3 additions & 0 deletions packages/block-library/src/legacy-widget/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"widgetClass": {
"type": "string"
},
"id": {
"type": "string"
},
"idBase": {
"type": "string"
},
Expand Down
3 changes: 3 additions & 0 deletions packages/block-library/src/legacy-widget/edit/dom-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ class LegacyWidgetEditDomManager extends Component {

componentDidMount() {
this.triggerWidgetEvent( 'widget-added' );
if ( this.props.onMount ) {
this.props.onMount( this.getFormData() );
}
}

shouldComponentUpdate( nextProps ) {
Expand Down
1 change: 1 addition & 0 deletions packages/block-library/src/legacy-widget/edit/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ class LegacyWidgetEditHandler extends Component {
this.widgetEditDomManagerRef = ref;
} }
onInstanceChange={ this.onInstanceChange }
onMount={ this.props.onFormMount }
number={ number ? number : instanceId * -1 }
id={ id }
idBase={ idBase }
Expand Down
19 changes: 17 additions & 2 deletions packages/block-library/src/legacy-widget/edit/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,18 @@ class LegacyWidgetEdit extends Component {
widgetName={ get( widgetObject, [ 'name' ] ) }
widgetClass={ attributes.widgetClass }
instance={ attributes.instance }
onFormMount={ ( formData ) => {
// Function-based widgets don't come with an object of settings, only
// with a pre-rendered HTML form. Extracting settings from that HTML
// before this stage is not trivial (think embedded <script>). An alternative
// proposed here serializes the form back into widget settings immediately after
// it's mounted.
if ( ! attributes.widgetClass ) {
this.props.setAttributes( {
instance: formData,
} );
}
} }
onInstanceChange={ ( newInstance, newHasEditForm ) => {
if ( newInstance ) {
this.props.setAttributes( {
Expand Down Expand Up @@ -172,12 +184,15 @@ class LegacyWidgetEdit extends Component {
}

renderWidgetPreview() {
const { attributes } = this.props;
const { widgetId, attributes } = this.props;
return (
<ServerSideRender
className="wp-block-legacy-widget__preview"
block="core/legacy-widget"
attributes={ omit( attributes, 'id' ) }
attributes={ {
id: widgetId,
...omit( attributes, 'id' ),
} }
/>
);
}
Expand Down

0 comments on commit 92463cd

Please sign in to comment.