Created
February 14, 2019 18:14
-
-
Save dan-westall/d1dbd4845d482bc4d5006428054ece06 to your computer and use it in GitHub Desktop.
None deletable gutenberg blocks plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
supports: { | |
deletable: false, | |
... | |
}, | |
... | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _differenceBy from 'lodash/differenceBy'; | |
const { subscribe } = wp.data; | |
const { createBlock, getBlockTypes } = wp.blocks; | |
export const initialize = () => { | |
let currentBlockCount = []; | |
let removedBlocks = []; | |
const getNonDeletableBlocks = () => { | |
const types = getBlockTypes(); | |
const permanentBlocks = types.filter( ( block ) => { | |
if ( ! Object.prototype.hasOwnProperty.call( block, 'supports' ) ) { | |
return false; | |
} | |
if ( ! Object.prototype.hasOwnProperty.call( block.supports, 'deletable' ) ) { | |
return false; | |
} | |
return true; | |
} ); | |
return permanentBlocks.reduce( ( blockNames, currentBlock ) => { | |
return [ ...blockNames, currentBlock.name ]; | |
}, [] ); | |
}; | |
subscribe( ( e ) => { | |
const { getBlocks } = wp.data.select( 'core/editor' ); | |
const { insertBlock } = wp.data.dispatch( 'core/editor' ); | |
const blocks = getBlocks(); | |
const cantDelete = getNonDeletableBlocks(); | |
if ( currentBlockCount.length > blocks.length ) { | |
removedBlocks = _differenceBy( currentBlockCount, blocks, 'clientId' ); | |
removedBlocks.forEach( ( block ) => { | |
if ( cantDelete.includes( block.name ) ) { | |
const oldPosition = currentBlockCount.findIndex( ( b, i ) => b.clientId === block.clientId ); | |
insertBlock( createBlock( block.name ), oldPosition ); | |
} | |
} ); | |
} | |
currentBlockCount = blocks; | |
} ); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment