1+ /* eslint-disable no-undef */
12/* eslint-disable camelcase */
2- import { withDispatch , withSelect , useDispatch , useSelect } from '@wordpress/data' ;
3+ import {
4+ withDispatch ,
5+ withSelect ,
6+ useDispatch ,
7+ useSelect ,
8+ } from '@wordpress/data' ;
39import { useState , useEffect } from '@wordpress/element' ;
410import { Modal , Button } from '@wordpress/components' ;
511import { compose } from '@wordpress/compose' ;
@@ -12,6 +18,8 @@ import Content from './components/content';
1218import PreviewFrame from '../../assets/src/Components/CloudLibrary/PreviewFrame' ;
1319import { importTemplate } from './data/templates-cloud' ;
1420
21+ const { omit } = lodash ;
22+
1523const Edit = ( {
1624 clientId,
1725 isPreview,
@@ -21,9 +29,7 @@ const Edit = ( {
2129 replaceBlocks,
2230 closePreview,
2331} ) => {
24- const {
25- type,
26- } = useSelect ( ( select ) => ( {
32+ const { type } = useSelect ( ( select ) => ( {
2733 type : select ( 'core/editor' ) . getEditedPostAttribute ( 'type' ) ,
2834 } ) ) ;
2935
@@ -100,14 +106,42 @@ const Edit = ( {
100106 return sortingOrder . library ;
101107 } ;
102108
109+ const tryParseJSON = ( jsonString ) => {
110+ try {
111+ const o = JSON . parse ( jsonString ) ;
112+
113+ // Handle non-exception-throwing cases:
114+ // Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
115+ // but... JSON.parse(null) returns null, and typeof null === "object",
116+ // so we must check for that, too. Thankfully, null is falsey, so this suffices:
117+ // Source: https://stackoverflow.com/a/20392392
118+ if ( o && typeof o === 'object' ) {
119+ return o ;
120+ }
121+ } catch ( e ) { }
122+
123+ return false ;
124+ } ;
125+
103126 const importBlocks = ( content , metaFields = [ ] ) => {
104127 updateLibrary ( [ ] ) ;
105128 updateTemplates ( [ ] ) ;
106129
107- if ( 0 < metaFields . length && [ 'post' , 'page' ] . includes ( type ) ) {
108- editPost ( {
109- meta : { ...JSON . parse ( metaFields ) } ,
110- } ) ;
130+ if (
131+ 0 < Object . keys ( tryParseJSON ( metaFields ) || { } ) . length &&
132+ [ 'post' , 'page' ] . includes ( type )
133+ ) {
134+ const fields = JSON . parse ( metaFields ) ;
135+ const meta = {
136+ ...omit ( { ...fields } , '_wp_page_template' ) ,
137+ } ;
138+ editPost ( { meta } ) ;
139+
140+ if ( 'page' === type && fields . _wp_page_template ) {
141+ editPost ( {
142+ template : fields . _wp_page_template ,
143+ } ) ;
144+ }
111145 }
112146
113147 replaceBlocks ( clientId , parse ( content ) ) ;
0 commit comments