Skip to content

Instantly share code, notes, and snippets.

@florianbrinkmann
Last active May 17, 2020 15:40
Show Gist options
  • Save florianbrinkmann/4e7d81b5401632c09e84a6bc786084b1 to your computer and use it in GitHub Desktop.
Save florianbrinkmann/4e7d81b5401632c09e84a6bc786084b1 to your computer and use it in GitHub Desktop.
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