この記事は最後に更新してから1年以上経過しています。

テーブルの1列目をth要素にしてみる

説明

標準の「テーブル」ブロックでは、tbody要素内のセルはすべてtd要素になっている。テーブルの1列目についてはth要素を使いたいケースがあり、「トグル」コントロールを使って切り替え可能にできないか調べてみた。

editor.BlockEditフィルターを使う

前回」は「ツールバー」を使って「段落」ブロックにマーキング(文字修飾)を追加した。ツールバーに関しては何となく使い方がわかってきたので、今回は画面右側に表示される「設定サイドバー」に挑戦したい。その使い方は、ブロックエディターハンドブックの「ブロックコントロール: ブロックツールバーと設定サイドバー」が参考になった。

まずは設定サイドバーにトグルコントロールを追加するところまでを作ってみる。JavaScriptのソースコードは次の通りで、今回もeditor.BlockEditフィルターのお世話になる。

( function ( wp ) {
	var el = wp.element.createElement;

	const extendCoreBlocks = wp.compose.createHigherOrderComponent(
		function ( BlockEdit ) {
			return function ( props ) {
				const {
					name,
					attributes,
					setAttributes,
					isSelected,
				} = props;

				if ( isSelected && 'core/table' === name ) {
					attributes.column1_th = false;

					function onToggleColumn1() {
						setAttributes( {
							column1_th: ! attributes.column1_th,
						} );
					}

					return el(
						wp.element.Fragment,
						{},
						el( BlockEdit, props ),
						el(
							wp.blockEditor.InspectorControls,
							{},
							el(
								wp.components.PanelBody,
								{
									title: 'その他の設定',
									initialOpen: true,
								},
								el(
									wp.components.ToggleControl,
									{
										label: 'tbody内の第1列をth要素にする',
										help: attributes.column1_th?
											'第1列はth要素。': '第1列はtd要素。',
										checked: attributes.column1_th,
										onChange: onToggleColumn1,
									}
								)
							)
						)
					);
				}
				return el( BlockEdit, props );
			};
		},
		'extendCoreBlocksControl'
	);

	wp.hooks.addFilter(
		'editor.BlockEdit',
		'core-extend/table-block',
		extendCoreBlocks
	);
} )( window.wp );

前回から少し変えたところが赤字の部分を追加したこと。これにより、propsの各プロパティを使用する際の記述を短くできる。

処理内容はnameが'core/table'の場合のみ次のような処理を行う。

  1. トグルコントロール用の属性column1_thを用意する。
  2. トグルコントロールのonChangeイベントハンドラonToggleColumn1を定義する。
  3. wp.element.Fragmentを使って現在の「テーブル」ブロックに設定サイドバー部分を追加する。

設定サイドバー部分は「スロット」であるwp.blockEditor.InspectorControlsを指定し、その子要素はwp.components.PanelBody(以下PanelBody)を、さらにその子要素はwp.components.ToggleControl(以下ToggleControl)を指定して要素を作成する。PanelBodyのプロパティは次の通りで、ここではinitialOpenにtrueを指定してあらかじめパネルの内容が開いた状態になるようにした。

キー内容
title文字列パネルのタイトル
initialOpenboolパネル初期時の開閉状態

続いてToggleControlのプロパティは次の通り。helpに指定するテキストはトグルボタンの状態に連動するようにしている。

キー内容
label文字列トグルボタン右に表示されるテキスト
help文字列トグルボタン下に表示されるテキスト
checkedboolトグルボタンのオン・オフ状態
onChange関数オン・オフ状態変更時のコールバック関数

こちらを適用した「テーブル」ブロックの設定サイドバーは次のようになる。

設定サイドバーに「その他の設定」パネルを追加

td要素をth要素に

次はテーブルブロックの内容を更新する。テーブルブロックのデータはattributesのプロパティに格納されている。

プロパティ(キー)内容
head配列thead要素の内容
body配列tbody要素の内容
foot配列tfoot要素の内容
caption文字列キャプションテキスト

head、body、footはそれぞれ1行分の配列となっており、例えばtbody要素内の各セルはbody[0~n].cells[0~n]に連想配列として格納されている。各セル情報を示す連想配列の内容は次の通り。

プロパティ(キー)内容
content文字列セルの内容('')
tag文字列セルの要素名('td')
align文字列セルの配置(undefined)
scope文字列th要素時のscope属性(undefined)

実際にtbody要素内の第1列のセルをtd要素をth要素に切り替えるため、青字の部分を追加する。

if ( 0 < attributes.body.length && 'string' === typeof attributes.body[0].cells[0].tag ) {
	attributes.column1_th = ( 'th' === attributes.body[0].cells[0].tag );
}

function onToggleColumn1() {
	let newBody = attributes.body;
	for ( let row = 0; row < newBody.length; row++ ) {
		if ( attributes.column1_th ) {
			newBody[row].cells[0].tag = 'td';
			newBody[row].cells[0].scope = undefined;
		} else {
			newBody[row].cells[0].tag = 'th';
			newBody[row].cells[0].scope = 'row';
		}
	}

	setAttributes( {
		column1_th: ! attributes.column1_th,
		body: newBody,
	} );
}

こちらを適用し、トグルコントロールをクリック。無事、表の第1列がth要素に切り替わった。

トグルコントロールをクリックして第1列をth要素に切り替えた

InspectorAdvancedControlsを使ってみる

設定サイドバーに関連するスロットにはwp.blockEditor.InspectorAdvancedControls(以下InspectorAdvancedControls)もある。このスロットはその子要素を「高度な設定」パネルに追加するもので、使い方は次の通りだ。

return el(
	wp.element.Fragment,
	{},
	el( BlockEdit, props ),
	el(
		wp.blockEditor.InspectorAdvancedControls,
		{},
		el(
			wp.components.ToggleControl,
			{
				label: 'tbody内の第1列をth要素にする',
				help: attributes.column1_th?
					'第1列はth要素。': '第1列はtd要素。',
				checked: attributes.column1_th,
				onChange: onToggleColumn1,
			}
		)
	)
);

InspectorAdvancedControlsを使う場合、InspectorControlsのようにPanelBodyを使う必要はない(PanelBodyを使うと、InspectorControlsを使った場合と同じように表示される)。実際に上記を適用した「高度な設定」パネル(設定サイドバー)は次のようになる。

「高度な設定」パネルにトグルコントロールが追加された


今回は「テーブル」ブロックの設定サイドバーを拡張し、tbody要素の第1列をth要素に切り替えできるようにした。正直なところ、わずかなコードでtd要素とth要素の切り替えが可能になったことにちょっと驚いた。InspectorControlsとInspectorAdvancedControlsについては、追加するコントロールの数やそのブロックの設定サイドバーの長さなどを考慮して使い分けたい。


【改訂】2021/12/21 attributes.column1_thを変更する前の条件に 0 < attributes.body.length && を追加した。


最終更新 : 2021年12月21日 12:00

お勧め

parse_blocks(2024年7月24日 更新)

array[] parse_blocks( string $content )
投稿コンテンツをパースする。

single_post_title(2012年9月6日 更新)

string single_post_title( [ string $prefix = '' [ , bool $display = true ] ] )
投稿ページのタイトルを表示する。

timer_stop(2021年7月23日 更新)

string timer_stop( [ int $display = 0 [ , int $precision = 3 ] ] )
タイマー開始時からの経過時間を取得する。

is_ssl(2022年7月2日 更新)

bool is_ssl( )
リクエストがSSLかどうか調べる。

wp_title_rss(2014年4月10日 更新)

void wp_title_rss( [ string $sep = '&#187;' ] )
フィード向けのページタイトルを出力する。