Skip to content

Instantly share code, notes, and snippets.

@dan-westall
Created February 14, 2019 18:14
Show Gist options
  • Save dan-westall/d1dbd4845d482bc4d5006428054ece06 to your computer and use it in GitHub Desktop.
Save dan-westall/d1dbd4845d482bc4d5006428054ece06 to your computer and use it in GitHub Desktop.
None deletable gutenberg blocks plugin
{
supports: {
deletable: false,
...
},
...
}
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