
# RichText

RichText の編集内容はブロックの属性に即座に保存され、リピーター行内の RichText を含め、Gutenberg の取り消し・やり直し履歴に反映されます。複数のブロックを選択した状態で保存しても、各ブロック固有のコンテンツと属性が保持されます。

`RichText`コンポーネントを使うと、エディター内に編集可能な入力欄を、フロントエンドに静的なHTML要素をレンダリングできます。[RichText](https://developer.wordpress.org/block-editor/reference-guides/richtext/)コンポーネントWordPressを基にしています。

## 基本的な使い方

`RichText`を最も基本的な形で使うには、block.jsonに適切な属性を追加し、ブロックに`RichText`コンポーネントを追加します。

```json title="block.json"
{
  "$schema": "https://blockstudio.dev/schema/block",
  "name": "blockstudio/rich-text",
  "title": "Native Block",
  "category": "text",
  "icon": "star-filled",
  "description": "Native Blockstudio RichText block.",
  "blockstudio": {
    "attributes": [
      {
        "id": "myRichText",
        "type": "richtext"
      }
    ]
  }
}
```

```php title="index.php"
<RichText attribute="myRichText" />
```

ブロック内では RichText コンポーネントをいくつでも使用できます。

## プロパティ

### allowedFormats

`allowedFormats`プロパティを使うと、RichText コンポーネントで使用できる書式を制限できます。


#### PHP

```php title="index.php"
<RichText attribute="myRichText" allowedFormats="<?php echo esc_attr(wp_json_encode(['core/bold', 'core/italic'])); ?>" />
```

#### Twig

```twig title="index.twig"
<RichText attribute="myRichText" allowedFormats="{{ ['core/bold', 'core/italic']|json_encode|escape('html_attr') }}" />
```

### プレースホルダー

`placeholder`プロパティを使って、RichText コンポーネントのプレースホルダーを設定できます。

```php title="index.php"
<RichText attribute="myRichText" placeholder="Enter some text" />
```

### preserveWhiteSpace

値に含まれる空白文字を保持するかどうかを指定します。通常、タブ、改行、スペースは1つのスペースにまとめられます。有効にすると、ソフト改行は改行要素ではなく、改行文字として保存されます。

```php title="index.php"
<RichText attribute="myRichText" preserveWhiteSpace="true" />
```

### タグ

既定では、`RichText`コンテンツは`p`要素内にレンダリングされます。`tag`プロパティを使って変更できます。

```php title="index.php"
<RichText attribute="myRichText" tag="h1" />
```

### withoutInteractiveFormatting

既定では、すべての書式設定コントロールが表示されます。この設定を使うと、コンテンツをインタラクティブにする書式設定コントロールを削除できます。

```php title="index.php"
<RichText attribute="myRichText" withoutInteractiveFormatting="true" />
```

## リピーターフィールド

RichText はリピーターフィールド内で使用できます。ブラケット記法とループインデックスを使って、対象の行を指定します。

```json title="block.json"
{
  "blockstudio": {
    "attributes": [
      {
        "id": "items",
        "type": "repeater",
        "attributes": [
          {
            "id": "heading",
            "type": "richtext"
          }
        ]
      }
    ]
  }
}
```

```php title="index.php"
<?php foreach ($a['items'] as $index => $item) : ?>
  <RichText tag="h2" attribute="items[<?php echo $index; ?>].heading" placeholder="Enter heading" />
<?php endforeach; ?>
```

```twig title="index.twig"
{% for item in a.items %}
  <RichText tag="h2" attribute="items[{{ loop.index0 }}].heading" placeholder="Enter heading" />
{% endfor %}
```

`attribute`の値は`repeaterId[index].fieldId`のパターンに従います。`index`はループ内の0始まりの行番号です。
