insert.js (1077B)
1 /** 2 * WordPress dependencies 3 */ 4 const { select, dispatch } = wp.data; 5 const { parse, createBlock } = wp.blocks; 6 7 export default function insertImportedBlocks( clientId, blocks, onClose ) { 8 blocks = parse( blocks ); 9 const toSelect = []; 10 const blockIndex = select( 'core/block-editor' ).getBlockInsertionPoint(); 11 if ( blocks.length > 0 ) { 12 for ( const block in blocks ) { 13 const created = createBlock( blocks[ block ].name, blocks[ block ].attributes, blocks[ block ].innerBlocks ); 14 dispatch( 'core/block-editor' ).insertBlocks( created, parseInt( blockIndex.index ) + parseInt( block ) ); 15 16 if ( typeof created !== 'undefined' ) { 17 toSelect.push( created.clientId ); 18 } 19 } 20 21 //remove insertion point if empty 22 dispatch( 'core/block-editor' ).removeBlock( clientId ); 23 24 //select inserted blocks 25 if ( toSelect.length > 0 ) { 26 dispatch( 'core/block-editor' ).multiSelect( toSelect[ 0 ], toSelect.reverse()[ 0 ] ); 27 } 28 } 29 30 onClose(); 31 }