Skip to content

Instantly share code, notes, and snippets.

@florianbrinkmann

florianbrinkmann/index.js

Last active May 17, 2020
Embed
What would you like to do?
Set attribute `maxWidth` for inner blocks of `slug/slider` block depending on block position in the editor. https://florianbrinkmann.com/block-attribute-abhaengig-block-position-11307/
const {
select,
} = wp.data;
wp.domReady( () => {
/**
* Get the slider blocks.
*
* @param {object} block
* @param {array} sliderBlocks
*/
const getSliderBlocks = ( block, sliderBlocks ) => {
if ( block.innerBlocks.length === 0 ) {
return;
}
// Check if it is a slider block. If so, push innerBlocks to the sliderBlocks array.
if ( block.name === 'slug/slider' ) {
sliderBlocks.push( block );
return;
}
block.innerBlocks.map( innerBlock => getSliderBlocks( innerBlock, sliderBlocks ) );
};
const getBlockList = () => select( 'core/editor' ).getBlocks();
wp.data.subscribe( () => {
let blockList = getBlockList();
if ( blockList ) {
// Get slider blocks.
let sliderBlocks = [];
blockList.map( block => getSliderBlocks( block, sliderBlocks ) );
sliderBlocks.map( sliderBlock => {
// Set maxWidth depending on position and settings of block.
const blockParents = select( 'core/block-editor' ).getBlockParents( sliderBlock.clientId );
let maxWidth;
// Check if the slider block has no parents.
if ( blockParents.length === 0 ) {
const align = sliderBlock.attributes.align;
// Set maxWidth to 100vw if full align.
if ( align !== undefined && align === 'full' ) {
maxWidth = '100vw';
}
// Set maxWidth to 1170 if no align.
if ( align === undefined || align !== 'full' ) {
maxWidth = '1170';
}
} else {
// Get column parents.
const columnParents = select( 'core/block-editor' ).getBlockParentsByBlockName( sliderBlock.clientId, 'core/column' );
if ( columnParents.length > 0 ) {
const columnParent = select( 'core/block-editor' ).getBlock( columnParents[0] );
let columnWidth = columnParent.attributes !== undefined && columnParent.attributes.width !== undefined && columnParent.attributes.width !== '' ? columnParent.attributes.width : 50;
maxWidth = 1170 / 100 * columnWidth;
} else {
maxWidth = '1170';
}
}
// Set the attributes for the slide blocks.
sliderBlock.innerBlocks.map( slideBlock => {
slideBlock.attributes.maxWidth = maxWidth;
} );
} );
}
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.