インタラクティビティ
BlockstudioはWordPress Interactivity APIに対応しています。これはブロックにリアクティブなクライアント側の動作を追加する標準的な方法です。interactivityをblock.jsonに設定すると、Blockstudioがフロントエンドとエディターの両方でAPIの読み込みを処理します。
設定
API を有効にするには、block.json の blockstudio キーに interactivity を追加します。
{
"name": "my-theme/interactive-block",
"title": "Interactive Block",
"category": "text",
"icon": "star-filled",
"description": "A block with interactive behavior.",
"blockstudio": {
"interactivity": true
}
}
オブジェクト形式も使用できます:
{
"blockstudio": {
"interactivity": {
"enqueue": true
}
}
}
どちらの形式も同じです。
テンプレート
ブロックテンプレートにInteractivity APIディレクティブを追加します。data-wp-interactive属性はストアの名前空間を定義し、その他のdata-wp-*属性はリアクティブな動作を制御します。
<div useBlockProps
data-wp-interactive="myBlock"
data-wp-context='{ "isOpen": false }'>
<button data-wp-on--click="actions.toggle"
data-wp-bind--aria-expanded="context.isOpen">
Toggle
</button>
<div data-wp-bind--hidden="!context.isOpen">
This content is toggled by the button.
</div>
</div>
スクリプト
ブロックフォルダーにscript.jsファイルを作成し、@wordpress/interactivityからインポートしてストアを初期化します。モジュールのトップレベルでstore()を呼び出します:
import { store, getContext } from '@wordpress/interactivity';
store('myBlock', {
actions: {
toggle: () => {
const context = getContext();
context.isOpen = !context.isOpen;
},
},
});
Blockstudioはscript.jsをESモジュールとして読み込み、@wordpress/interactivityを解決するために必要なimportmapを自動生成します。
ブロックでカスタムアクションまたはコールバックを定義する場合にのみ、script.jsが必要です。data-wp-contextを使った宣言的ディレクティブ(data-wp-bind--hiddenやdata-wp-textなど)のみを使用するブロックは、JavaScriptなしで動作します。
サーバーサイドの状態
テンプレートでwp_interactivity_state()を使って、PHPから状態を初期化できます:
<?php
wp_interactivity_state( 'myBlock', array(
'message' => 'Hello from the server',
'count' => get_comments_number(),
) );
?>
<div useBlockProps
data-wp-interactive="myBlock">
<p data-wp-text="state.message">loading...</p>
<p data-wp-text="state.count">0</p>
</div>
サーバーサイドの状態はフロントエンドでのみ利用できます。WordPressは状態をページ出力内のJSONscriptタグにシリアライズし、Interactivity APIがハイドレーション時に読み取ります。エディターではブロックはREST APIを通じてレンダリングされるため、レスポンスに状態データは含まれません。エディターとフロントエンドの両方で動作させる必要がある状態には、data-wp-contextを使用してください。
コールバックとアクション
アクションはユーザー操作(data-wp-on--clickなど)によって実行されます。コールバックはdata-wp-watchディレクティブを使い、状態またはコンテキストの変更に応じて実行されます。コールバック内ではgetElement()を呼び出して、基になるDOM要素にアクセスできます:
import { store, getContext, getElement } from '@wordpress/interactivity';
store('myBlock', {
callbacks: {
updateWidth: () => {
const { ref } = getElement();
const { isOpen } = getContext();
ref.style.width = isOpen ? '100%' : '0';
},
},
});
エディターのサポート
Interactivity APIはブロックエディターのiframe内で読み込まれるため、プレビュー内でインタラクティブなディレクティブが動作します。これにはdata-wp-context、data-wp-bind--*、data-wp-on--*、data-wp-textと、script.jsで定義されたカスタムストアアクションが含まれます。
アコーディオン、タブ、モーダル、いいねボタンを使った完全なサンプルです。