
# インタラクティビティ

Blockstudioは[WordPress Interactivity API](https://developer.wordpress.org/block-editor/reference-guides/interactivity-api/)に対応しています。これはブロックにリアクティブなクライアント側の動作を追加する標準的な方法です。`interactivity`をblock.jsonに設定すると、Blockstudioがフロントエンドとエディターの両方でAPIの読み込みを処理します。

## 設定

API を有効にするには、block.json の `blockstudio` キーに `interactivity` を追加します。

```json title="block.json"
{
  "name": "my-theme/interactive-block",
  "title": "Interactive Block",
  "category": "text",
  "icon": "star-filled",
  "description": "A block with interactive behavior.",
  "blockstudio": {
    "interactivity": true
  }
}
```

オブジェクト形式も使用できます：

```json title="block.json"
{
  "blockstudio": {
    "interactivity": {
      "enqueue": true
    }
  }
}
```

どちらの形式も同じです。

## テンプレート

ブロックテンプレートにInteractivity APIディレクティブを追加します。`data-wp-interactive`属性はストアの名前空間を定義し、その他の`data-wp-*`属性はリアクティブな動作を制御します。

```php title="index.php"
<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()`を呼び出します：

```js title="script.js"
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 title="index.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要素にアクセスできます：

```js title="script.js"
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`で定義されたカスタムストアアクションが含まれます。


> **[インタラクティブなコンポーネントを構築する](https://blockstudio.dev/ja/guides/interactive-components/)**
>
> アコーディオン、タブ、モーダル、いいねボタンを使った完全なサンプルです。
