inject-css.js (1581B)
1 /** 2 * WordPress dependencies. 3 */ 4 const { __ } = wp.i18n; 5 6 const { parse } = wp.blocks; 7 8 const { 9 select, 10 subscribe 11 } = wp.data; 12 13 const addStyle = style => { 14 let element = document.getElementById( 'redux-css-editor-styles' ); 15 16 if ( null === element ) { 17 element = document.createElement( 'style' ); 18 element.setAttribute( 'type', 'text/css' ); 19 element.setAttribute( 'id', 'redux-css-editor-styles' ); 20 document.getElementsByTagName( 'head' )[0].appendChild( element ); 21 } 22 23 if ( element.textContent === style ) { 24 return null; 25 } 26 27 return element.textContent = style; 28 }; 29 30 let style = ''; 31 32 const cycleBlocks = ( blocks, reusableBlocks ) => { 33 blocks.forEach( block => { 34 if ( block.attributes.hasCustomCSS ) { 35 if ( block.attributes.customCSS && ( null !== block.attributes.customCSS ) ) { 36 style += block.attributes.customCSS + '\n'; 37 } 38 } 39 40 if ( 'core/block' === block.name && null !== reusableBlocks ) { 41 let reBlocks = reusableBlocks.find( i => block.attributes.ref === i.id ); 42 if ( reBlocks ) { 43 reBlocks = parse( reBlocks.content.raw ); 44 cycleBlocks( reBlocks, reusableBlocks ); 45 }; 46 } 47 48 if ( undefined !== block.innerBlocks && 0 < ( block.innerBlocks ).length ) { 49 cycleBlocks( block.innerBlocks, reusableBlocks ); 50 } 51 }); 52 }; 53 54 const subscribed = subscribe( () => { 55 style = ''; 56 const { getBlocks } = select( 'core/block-editor' ) || select( 'core/editor' ); 57 const blocks = getBlocks(); 58 const reusableBlocks = select( 'core' ).getEntityRecords( 'postType', 'wp_block' ); 59 cycleBlocks( blocks, reusableBlocks ); 60 addStyle( style ); 61 });