igmoweb
5/1/2020 - 10:59 AM

Extend block in Gutenberg

/**
 * Add background image selector to certain blocks.
 */
const { createHigherOrderComponent } = wp.compose;

const { Fragment, cloneElement } = wp.element;
const { addFilter } = wp.hooks;

const EXTEND_BLOCKS = [ 'core/paragraph' ];
const NAMESPACE = 'my-plugin/block-extension';

const shouldBeenExtended = ( { name } ) => EXTEND_BLOCKS.includes( name );

// Add extension to the Edit component.
const withExtension = createHigherOrderComponent( ( OriginalComponent ) => {
	return ( props ) => {

		if ( ! shouldBeenExtended( props ) ) {
			return <OriginalComponent { ...props } />;
		}
		
		const { attributes } = props;
		const { newAttribute } = attributes;

		return (
			<Fragment>
				<p>{ newAttribute }</p>
				<OriginalComponent { ...props } />
			</Fragment>
		);
	};
}, 'withExtension' );

addFilter( 'editor.BlockEdit', NAMESPACE, withExtension );

// Extend the attributes
const extendAttributes = ( settings ) => {
	if ( ! shouldBeenExtended( settings ) ) {
		return settings;
	}

	const { attributes } = settings;
	return {
		...settings,
		attributes: {
			...attributes,
			newAttribute: {
				type: 'string',
				default: 'This is a extension for a paragraph',
			},
		},
	};
};

addFilter( 'blocks.registerBlockType', NAMESPACE, extendAttributes );

// Add extension to the Save component.
wp.hooks.addFilter(
	'blocks.getSaveElement',
	NAMESPACE,
	( saveComponent, blockType, attributes ) => {
		if ( ! shouldBeenExtended( blockType ) ) {
			return saveComponent;
		}

		const { newAttribute } = attributes;
		if ( newAttribute === 'This is a extension for a paragraph' ) {
			// Avoid breaking the save check.
			return saveComponent;
		}

		return cloneElement( saveComponent, {
			...saveComponent.props,
		} );
	},
);