Skip to content

Instantly share code, notes, and snippets.

@mattheu
Created November 13, 2018 12:10
Show Gist options
  • Save mattheu/063c44c990374e3f0d2d087782785ef5 to your computer and use it in GitHub Desktop.
Save mattheu/063c44c990374e3f0d2d087782785ef5 to your computer and use it in GitHub Desktop.
const { subscribe } = wp.data;
const { createBlock } = wp.blocks;
const createAdBlock = () => createBlock( AdBlock.name, { size: 'mpu' } );
subscribe( e => {
const {
getBlocks,
} = wp.data.select( 'core/editor' );
const {
insertBlock,
moveBlockToPosition,
} = wp.data.dispatch( 'core/editor' );
const blocks = getBlocks();
const firstAdIndex = blocks.findIndex( b => b.name === AdBlock.name );
const targetIndex = 3;
const targetRange = 5;
if ( blocks.length >= targetIndex ) {
if ( firstAdIndex < 0 ) {
insertBlock( createAdBlock(), targetIndex );
return;
} else if ( firstAdIndex < targetIndex ) {
moveBlockToPosition( blocks[ firstAdIndex ].clientId, '', '', targetIndex );
return;
} else if ( firstAdIndex > ( targetIndex + targetRange ) ) {
moveBlockToPosition( blocks[ firstAdIndex ].clientId, '', '', targetIndex + targetRange );
return;
}
}
const secondAdIndex = blocks.findIndex( ( b, i ) => b.name === AdBlock.name && i !== firstAdIndex );
const secondTargetIndex = 8 + 1 + ( firstAdIndex - targetIndex );
if ( blocks.length >= secondTargetIndex ) {
if ( secondAdIndex < 0 ) {
console.log( 'inserting ad' );
insertBlock( createAdBlock(), secondTargetIndex );
return;
} else if ( secondAdIndex < secondTargetIndex ) {
console.log( 'moving ad to start', {
firstAdIndex,
secondTargetIndex,
} );
moveBlockToPosition( blocks[ secondAdIndex ].clientId, '', '', secondTargetIndex );
return;
} else if ( secondAdIndex > ( secondTargetIndex + targetRange ) ) {
console.log( 'moving ad to end', {
firstAdIndex,
targetIndex,
secondAdIndex,
secondTargetIndex,
targetRange,
} );
moveBlockToPosition( blocks[ secondAdIndex ].clientId, '', '', secondTargetIndex + targetRange );
return;
}
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment