( function ( blocks, blockEditor, element ) {
var el = element.createElement;
var RichText = blockEditor.RichText;
var AlignmentToolbar = blockEditor.AlignmentToolbar;
var BlockControls = blockEditor.BlockControls;
var useBlockProps = blockEditor.useBlockProps;
blocks.registerBlockType( 'softhunt/controls-example', {
title: 'Controls',
icon: 'universal-access-alt',
category: 'design',
attributes: {
content: {
type: 'array',
source: 'children',
selector: 'p',
},
alignment: {
type: 'string',
default: 'none',
},
},
example: {
attributes: {
content: 'Hello World',
alignment: 'right',
},
},
edit: function ( props ) {
var content = props.attributes.content;
var alignment = props.attributes.alignment;
function onChangeContent( newContent ) {
props.setAttributes( { content: newContent } );
}
function onChangeAlignment( newAlignment ) {
props.setAttributes( {
alignment:
newAlignment === undefined ? 'none' : newAlignment,
} );
}
return el(
'div',
useBlockProps(),
el(
BlockControls,
{ key: 'controls' },
el( AlignmentToolbar, {
value: alignment,
onChange: onChangeAlignment,
} )
),
el( RichText, {
key: 'richtext',
tagName: 'p',
style: { textAlign: alignment },
onChange: onChangeContent,
value: content,
} )
);
},
save: function ( props ) {
var blockProps = useBlockProps.save();
return el(
'div',
blockProps,
el( RichText.Content, {
tagName: 'p',
className:
'softhunt-gutenberg-examples-align-' +
props.attributes.alignment,
value: props.attributes.content,
} )
);
},
} );
} )( window.wp.blocks, window.wp.blockEditor, window.wp.element );
import { registerBlockType } from '@wordpress/blocks';
import {
useBlockProps,
RichText,
AlignmentToolbar,
BlockControls,
} from '@wordpress/block-editor';
registerBlockType( 'softhunt/controls-example', {
apiVersion: 2,
title: 'Controls',
icon: 'universal-access-alt',
category: 'design',
attributes: {
content: {
type: 'array',
source: 'children',
selector: 'p',
},
alignment: {
type: 'string',
default: 'none',
},
},
example: {
attributes: {
content: 'Hello World',
alignment: 'right',
},
},
edit: ( { attributes, setAttributes } ) => {
const onChangeContent = ( newContent ) => {
setAttributes( { content: newContent } );
};
const onChangeAlignment = ( newAlignment ) => {
setAttributes( {
alignment: newAlignment === undefined ? 'none' : newAlignment,
} );
};
return (
<div { ...useBlockProps() }>
{
<BlockControls>
<AlignmentToolbar
value={ attributes.alignment }
onChange={ onChangeAlignment }
/>
</BlockControls>
}
<RichText
className={ attributes.className }
style={ { textAlign: attributes.alignment } }
tagName="p"
onChange={ onChangeContent }
value={ attributes.content }
/>
</div>
);
},
save: ( props ) => {
const blockProps = useBlockProps.save();
return (
<div { ...blockProps }>
<RichText.Content
className={ `softhunt-gutenberg-examples-align-${ props.attributes.alignment }` }
tagName="p"
value={ props.attributes.content }
/>
</div>
);
},
} );