Gutenberg Block入門用のその5です。今回はBlockにでてくるツールバーについてみていきます。

以前の記事はこちら

前回までの内容にプラスで、今回は「BlockControlsとAlignmentToolbar」というコンポーネントをblock.jsの中に実装して、記事を書く時、Blockのツールバーに文字の寄せを選ぶボタンが表示されるようにしていきましょう。

参考にしたサイトは、ここ「Block Controls: Toolbars and Inspector」です。出来上がるとこんな感じのBlockが使えるようになります。

ファイル構成

必要なファイルは「その4」と同じです。block.jsにToolbar用の修正を入れていきます。

(※ 他のファイルでは、block名が関係しているところに修正が必要です。)

block.js

wp.editorの中から、RichTextに加えて、AlignmentToolbar, BlockControlsが追加されます。

const { __, setLocaleData } = wp.i18n;
const { registerBlockType } = wp.blocks;
const {
	RichText,
	AlignmentToolbar,
	BlockControls,
} = wp.editor;

registerBlockType( 'gutenberg-examples/example-04-controls-esnext', {
    title: 'Hello World (Step 4)',
    icon: 'universal-access-alt',
    category: 'layout',
	attributes: {
		content: {
			type: 'array',
			source: 'children',
			selector: 'p',
		},
		alignment: {
			type: 'string',
			default: 'none',
		},
	},
	edit: ( props ) => {
		const {
			attributes: {
				content,
				alignment,
			},
			className,
		} = props;

		const onChangeContent = ( newContent ) => {
			props.setAttributes( { content: newContent } );
		};

		const onChangeAlignment = ( newAlignment ) => {
			props.setAttributes( { alignment: newAlignment === undefined ? 'none' : newAlignment } );
		};

		return (
			<div>
				{
					<BlockControls>
						<AlignmentToolbar
							value={ alignment }
							onChange={ onChangeAlignment }
						/>
					</BlockControls>
				}
				<RichText
					className={ className }
					style={ { textAlign: alignment } }
					tagName="p"
					onChange={ onChangeContent }
					value={ content }
				/>
			</div>
		);
	},
	save: ( props ) => {
		return (
			<RichText.Content
				className={ `gutenberg-examples-align-${ props.attributes.alignment }` }
				tagName="p"
				value={ props.attributes.content }
			/>
		);
	},
} );

動作確認

今回もesnextでソースをかいているので、buildしてから試します。

npm install
npm run build

PluginをActivate した後、このBlockが表示されたらOK.



補足: 他のファイル

index.php

<?php
/**
 * Plugin Name: Gutenberg Examples Controls EsNext
 * Plugin URI: https://github.com/WordPress/gutenberg-examples
 * Description: This is a plugin demonstrating how to register new blocks for the Gutenberg editor.
 * Version: 1.0.2
 * Author: the Gutenberg Team
 *
 * @package gutenberg-examples
 */
defined( 'ABSPATH' ) || exit;
/**
 * Load all translations for our plugin from the MO file.
*/
add_action( 'init', 'gutenberg_examples_04_esnext_load_textdomain' );
function gutenberg_examples_04_esnext_load_textdomain() {
	load_plugin_textdomain( 'gutenberg-examples', false, basename( __DIR__ ) . '/languages' );
}
/**
 * Registers all block assets so that they can be enqueued through Gutenberg in
 * the corresponding context.
 *
 * Passes translations to JavaScript.
 */
function gutenberg_examples_04_esnext_register_block() {
	if ( ! function_exists( 'register_block_type' ) ) {
		// Gutenberg is not active.
		return;
	}
	wp_register_script(
		'gutenberg-examples-04-esnext',
		plugins_url( 'block.build.js', __FILE__ ),
		array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' ),
		filemtime( plugin_dir_path( __FILE__ ) . 'block.build.js' )
	);
	wp_register_style(
		'gutenberg-examples-04-esnext-editor',
		plugins_url( 'editor.css', __FILE__ ),
		array( 'wp-edit-blocks' ),
		filemtime( plugin_dir_path( __FILE__ ) . 'editor.css' )
	);
	wp_register_style(
		'gutenberg-examples-04-esnext',
		plugins_url( 'style.css', __FILE__ ),
		array( ),
		filemtime( plugin_dir_path( __FILE__ ) . 'style.css' )
	);
	register_block_type( 'gutenberg-examples/example-04-controls-esnext', array(
		'style' => 'gutenberg-examples-04-esnext',
		'editor_style' => 'gutenberg-examples-04-esnext-editor',
		'editor_script' => 'gutenberg-examples-04-esnext',
	) );
  if ( function_exists( 'wp_set_script_translations' ) ) {
    /**
     * May be extended to wp_set_script_translations( 'my-handle', 'my-domain',
     * plugin_dir_path( MY_PLUGIN ) . 'languages' ) ). For details see
     * https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/
     */
    wp_set_script_translations( 'gutenberg-examples-04-esnext', 'gutenberg-examples' );
  }
}
add_action( 'init', 'gutenberg_examples_04_esnext_register_block' );

style.css

.wp-block-gutenberg-examples-example-04-controls-esnext {
	color: darkred;
	background: #fcc;
	border: 2px solid #c99;
	padding: 20px;
}

editor.css

.wp-block-gutenberg-examples-example-04-controls-esnext {
	color: green;
	background: #cfc;
	border: 2px solid #9c9;
	padding: 20px;
}

webpack.config.js

module.exports = {
    entry: './block.js',
    output: {
        path: __dirname,
        filename: 'block.build.js',
    },
    module: {
        loaders: [
            {
                test: /.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
            },
        ],
    },
};

.babelrc

{
     "presets": [
         [ "env", {
             "modules": false,
             "targets": {
                 "browsers": [
                     "last 2 Chrome versions",
                     "last 2 Firefox versions",
                     "last 2 Safari versions",
                     "last 2 iOS versions",
                     "last 1 Android version",
                     "last 1 ChromeAndroid version",
                     "ie 11"
                 ]
             }
         } ]
     ],
     "plugins": [
         [ "transform-react-jsx", {
             "pragma": "wp.element.createElement"
         } ]
     ]
 }

package.json

{
   "name": "01-basic-esnext",
   "version": "1.0.0",
   "license": "GPL-2.0-or-later",
   "main": "block.js",
   "devDependencies": {
     "babel-core": "^6.25.0",
     "babel-loader": "^7.1.1",
     "babel-plugin-transform-react-jsx": "^6.24.1",
     "babel-preset-env": "^1.6.0",
     "cross-env": "^5.0.1",
     "webpack": "^3.1.0"
   },
   "scripts": {
     "build": "cross-env BABEL_ENV=default NODE_ENV=production webpack",
     "dev": "cross-env BABEL_ENV=default webpack --watch"
   }
 }