| 1 |
/** |
| 2 |
* Creates sidebar blocks. |
| 3 |
*/ |
| 4 |
import { useSelect } from '@wordpress/data'; |
| 5 |
import { createBlock, getBlockTypes } from '@wordpress/blocks'; |
| 6 |
import DraggableBlock from './draggable-block'; |
| 7 |
import DragAndDropComponent from './move-up-down'; |
| 8 |
|
| 9 |
const Blocks = ( { |
| 10 |
defaultAllowedQuickSidebarBlocks, |
| 11 |
updateDefaultAllowedQuickSidebarBlocks, |
| 12 |
saveOptionToDatabase, |
| 13 |
enableRearrange, |
| 14 |
} ) => { |
| 15 |
const blocks = getBlockTypes(); |
| 16 |
const { |
| 17 |
blockInsertionPoint, |
| 18 |
getBlockRootClientId, |
| 19 |
getSelectedBlockAllowedBlocks, |
| 20 |
getSelectedBlockClientId, |
| 21 |
} = useSelect( ( select ) => { |
| 22 |
const blockEditor = select( 'core/block-editor' ); |
| 23 |
const { index } = blockEditor.getBlockInsertionPoint(); |
| 24 |
const clientId = blockEditor.getSelectedBlockClientId(); |
| 25 |
const rootClientId = blockEditor.getBlockRootClientId( |
| 26 |
getSelectedBlockClientId |
| 27 |
); |
| 28 |
const allowedBlocks = blockEditor.getAllowedBlocks( clientId ); |
| 29 |
return { |
| 30 |
blockInsertionPoint: index, |
| 31 |
getBlockRootClientId: rootClientId, |
| 32 |
getSelectedBlockClientId: clientId, |
| 33 |
getSelectedBlockAllowedBlocks: allowedBlocks || [], |
| 34 |
}; |
| 35 |
} ); |
| 36 |
const srfmBlocks = blocks.filter( ( block ) => { |
| 37 |
return defaultAllowedQuickSidebarBlocks.includes( block.name ); |
| 38 |
} ); |
| 39 |
const create = ( name ) => { |
| 40 |
return createBlock( name ); |
| 41 |
}; |
| 42 |
|
| 43 |
// Loop through each object and add id |
| 44 |
srfmBlocks.forEach( ( item, index ) => { |
| 45 |
item.id = `${ index + 1 }`; |
| 46 |
} ); |
| 47 |
|
| 48 |
const sortedY = defaultAllowedQuickSidebarBlocks |
| 49 |
.filter( ( item ) => item !== undefined && item !== null ) |
| 50 |
.map( ( item ) => srfmBlocks.find( ( { name } ) => name === item ) ) |
| 51 |
.filter( ( item ) => item !== undefined ); // Remove undefined objects |
| 52 |
|
| 53 |
return ( |
| 54 |
<> |
| 55 |
{ ! enableRearrange && |
| 56 |
sortedY.map( ( block, index ) => ( |
| 57 |
<DraggableBlock |
| 58 |
key={ index } |
| 59 |
id={ index } |
| 60 |
{ ...{ |
| 61 |
block, |
| 62 |
create, |
| 63 |
blockInsertionPoint, |
| 64 |
getBlockRootClientId, |
| 65 |
getSelectedBlockClientId, |
| 66 |
getSelectedBlockAllowedBlocks, |
| 67 |
defaultAllowedQuickSidebarBlocks, |
| 68 |
updateDefaultAllowedQuickSidebarBlocks, |
| 69 |
saveOptionToDatabase, |
| 70 |
} } |
| 71 |
/> |
| 72 |
) ) } |
| 73 |
{ enableRearrange && ( |
| 74 |
<DragAndDropComponent |
| 75 |
initialItems={ sortedY } |
| 76 |
updateDefaultAllowedQuickSidebarBlocks={ |
| 77 |
updateDefaultAllowedQuickSidebarBlocks |
| 78 |
} |
| 79 |
saveOptionToDatabase={ saveOptionToDatabase } |
| 80 |
/> |
| 81 |
) } |
| 82 |
</> |
| 83 |
); |
| 84 |
}; |
| 85 |
|
| 86 |
export default Blocks; |
| 87 |
|