import.js (2093B)
1 /** 2 * External dependencies 3 */ 4 import { isString } from 'lodash'; 5 6 /** 7 * Internal dependencies 8 */ 9 import { readTextFile } from './file'; 10 const { dispatch, select } = wp.data; 11 const { editPost } = dispatch('core/editor'); 12 13 /** 14 * Import a reusable block from a JSON file. 15 * 16 * @param {File} file File. 17 * @return {Promise} Promise returning the imported reusable block. 18 */ 19 async function importReusableBlock( file ) { 20 const fileContent = await readTextFile( file ); 21 let parsedContent; 22 try { 23 parsedContent = JSON.parse(JSON.parse(JSON.stringify(fileContent))); 24 } catch ( e ) { 25 throw new Error( 'Invalid JSON file' ); 26 } 27 28 if ( parsedContent.__file === 'redux_template' ) { 29 editPost( { 'template': 'redux-templates_full_width' } ); 30 return parsedContent.content; 31 } 32 33 if ( 34 parsedContent.__file !== 'wp_block' || 35 ! parsedContent.title || 36 ! parsedContent.content || 37 ! isString( parsedContent.title ) || 38 ! isString( parsedContent.content ) 39 ) { 40 if ( '' === select( 'core/editor' ).getEditedPostAttribute( 'template' ) ) { 41 editPost({'template': 'redux-templates_contained'}); 42 } 43 return importCoreBlocks( parsedContent ); 44 } 45 46 const postType = await wp.apiFetch( { path: '/wp/v2/types/wp_block' } ); 47 const reusableBlock = await wp.apiFetch( { 48 path: `/wp/v2/${ postType.rest_base }`, 49 data: { 50 title: parsedContent.title, 51 content: parsedContent.content, 52 status: 'publish', 53 }, 54 method: 'POST', 55 } ); 56 57 if ( reusableBlock.id ) { 58 return '<!-- wp:block {"ref":' + reusableBlock.id + '} /-->'; 59 } 60 throw new Error( 'Invalid Reusable Block JSON file contents' ); 61 } 62 63 function importCoreBlocks( parsedContent ) { 64 if ( 65 parsedContent.__file !== 'core_block' || 66 ! parsedContent.content || 67 ! isString( parsedContent.content ) 68 ) { 69 throw new Error( 'Invalid JSON file' ); 70 } 71 72 return parsedContent.content; 73 } 74 75 export default importReusableBlock;