> Markdown version of [Rich Text Editor](https://vaadin.com/docs/latest/it/components/rich-text-editor). Section index: [llms.txt](https://vaadin.com/docs/latest/it/components/llms.txt)

# Rich Text Editor

> **Note: Funzionalità commerciale**
>
> Per utilizzare Rich Text Editor nel Suo progetto è necessario un abbonamento commerciale Vaadin.
>
> - [Start Free Trial](https://vaadin.com/trial)
>
> - [See Pricing](https://vaadin.com/pricing)

Rich Text Editor consente all’utente di creare testo con formattazione avanzata. Consente di formattare e applicare stili al Suo testo usando grassetto, corsivo, intestazioni, elenchi, immagini, link, ecc.

**Lit** — `rich-text-editor-basic.ts`

```html
<vaadin-rich-text-editor
  style="max-height: 400px"
  value="${this.richText}"
></vaadin-rich-text-editor>
```

**Flow** — `RichTextEditorBasic.java`

```java
RichTextEditor rte = new RichTextEditor();
rte.setMaxHeight("400px");
String valueAsHtml = DataService.getTemplates().getRichTextHtml();
rte.setValue(valueAsHtml);
add(rte);
```

**React** — `rich-text-editor-basic.tsx`

```tsx
<RichTextEditor
  style={{ maxHeight: '400px' }}
  value={richText.value}
  onValueChanged={(event) => {
    richText.value = event.detail.value;
  }}
/>
```

## <a id="formato-del-valore"></a>Formato del valore

Rich Text Editor supporta il formato HTML e il [formato Quill Delta](https://github.com/quilljs/delta) per leggere e impostare il Suo valore.

Dettagli del formato HTML

Rich Text Editor supporta valori nel formato HTML, con le seguenti restrizioni:

- È supportato solo un sottoinsieme di tag HTML, elencati nella tabella seguente;

- Gli elementi di blocco, come paragrafi, elenchi, o citazioni in blocco, non possono essere annidati; e

- I tag non supportati, come `<b>`, vengono sostituiti con un tag supportato equivalente, come `<strong>`, oppure con un paragrafo (`<p>`).

Table 1. Tag HTML supportati

| Funzionalità                                                                   | Tag                              |
| ------------------------------------------------------------------------------ | -------------------------------- |
| Paragrafi e interruzioni di riga                                               | `<p>`, `<br>`                    |
| Intestazioni                                                                   | `<h1>`, `<h2>`, …​, `<h6>`       |
| Testo in grassetto, corsivo, sottolineato e barrato                            | `<strong>`, `<em>`, `<u>`, `<s>` |
| Link                                                                           | `<a href="…​">…​</a>`            |
| Allineamento del testo tramite la proprietà CSS `text-align`                   | `<p style="text-align: center">` |
| Elenchi ordinati, non ordinati, e voci di elenco (non possono essere annidati) | `<ol>`, `<ul>`, `<li>`           |
| Citazioni in blocco                                                            | `<blockquote>`                   |
| Testo preformattato                                                            | `<pre>`                          |
| Immagini, usando un data URL codificato in Base64                              | `<img src="…​">`                 |

> **Note:** Per le immagini sono supportati solo data URL codificati in Base64. Le URL web non sono supportate.

Il seguente snippet contiene un documento HTML supportato dal componente. Dimostra l’uso di diversi tag. Provi a incollare lo snippet nell’area di testo `HTML Value` nell’esempio qui sotto e osservi come l’editor si aggiorna. Poi provi a modificare il valore, usando le funzionalità dell’editor, oppure cambiando direttamente il valore HTML.

```html
<h2>High quality rich text editor for the web</h2>
<p>Rich text editor handles the following formatting:</p>
<ul>
  <li><strong>Bold</strong></li>
  <li><em>Italic</em></li>
  <li><u>Underline</u></li>
  <li><s>Strike-through</s></li>
</ul><h3>Blockquotes</h3>
<blockquote>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
  dolore magna aliqua.
</blockquote><h3>Code blocks</h3>
<pre spellcheck='false'>&lt;body&gt;
  &lt;vaadin-rich-text-editor&gt;&lt;/vaadin-rich-text-editor&gt;
&lt;/body&gt;
</pre>
```

Dettagli del formato Delta

Il formato Delta, basato su JSON, consiste in un array di operazioni da applicare a un documento. Rich Text Editor usa nello specifico solo operazioni di inserimento, in cui ogni operazione aggiunge contenuto al documento in modo sequenziale. Le operazioni possono avere attributi, ad esempio se rendere un contenuto con uno specifico stile di testo, oppure come link. Per la specifica completa del formato, veda il [repository GitHub di Quill Delta](https://github.com/quilljs/delta).

Il seguente snippet contiene un documento Delta che dimostra alcune funzionalità del formato. Provi a incollare lo snippet nell’area di testo `Delta Value` nell’esempio qui sotto e osservi come l’editor si aggiorna. Poi provi a modificare il valore, usando le funzionalità dell’editor, oppure cambiando direttamente il valore Delta.

```json
[
  {"insert": "High quality rich text editor for the web\n", "attributes": {"header":  2}},
  {"insert": "Rich text editor handles the following formatting:\n"},
  {"insert": "Bold\n","attributes": { "bold": true, "list": "bullet" }},
  {"insert": "Italic\n", "attributes": { "italic": true, "list": "bullet" }},
  {"insert": "Underline\n", "attributes": { "underline": true, "list": "bullet" }},
  {"insert": "Strike-through\n", "attributes": { "strike": true, "list": "bullet" }},
  {"insert": "Blockquotes\n", "attributes": { "header": 3 }},
  {"insert": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n", "attributes": { "blockquote": true }},
  {"insert": "Code blocks\n", "attributes": { "header": 3 }},
  {"insert": "<vaadin-rich-text-editor></vaadin-rich-text-editor>\n", "attributes": { "code-block": true }}
]
```

Per il componente Flow, l’impostazione predefinita è il formato HTML, che viene usato automaticamente anche quando si effettua il binding del componente con `Binder`.

Per leggere, scrivere, o effettuare il binding del valore del componente usando il formato Delta, usi il wrapper [`RichTextEditor.asDelta()`](https://vaadin.com/api/platform/25.2.14/com/vaadin/flow/component/richtexteditor/RichTextEditor.html#asDelta\(\)).

> **Note: Uso con Binder**
>
> Poiché il componente usa un valore HTML complesso, il validatore predefinito `asRequired` non funziona come previsto con `Binder`. Fornisca invece un validatore personalizzato:
>
> ```java
> binder.forField(richTextEditor)
>     .asRequired(Validator.from(value -> !richTextEditor.isEmpty(), "Required"))
> ```

Per il web component, per leggere o scrivere il valore nel formato Delta, usi la proprietà `value`.

Per leggere o scrivere il valore nel formato HTML, usi la proprietà `htmlValue` e il metodo `dangerouslySetHtmlValue`.

> **Note: Sanitizzazione HTML**
>
> Per prevenire l’iniezione di contenuti malevoli, si assicuri di sanitizzare le stringhe HTML prima di passarle al web component usando `dangerouslySetHtmlValue`. Un esempio è l’uso di una libreria come [dompurify](https://www.npmjs.com/package/dompurify).

**Lit** — `rich-text-editor-set-get-value.ts`

```typescript
<vaadin-rich-text-editor
  style="height: 400px;"
  .value="${this.deltaValue}"
  @value-changed="${(event: RichTextEditorValueChangedEvent) => {
    this.deltaValue = event.detail.value;
  }}"
  @html-value-changed="${(event: RichTextEditorHtmlValueChangedEvent) => {
    this.htmlValue = event.detail.value;
  }}"
></vaadin-rich-text-editor>

<vaadin-text-area
  label="HTML Value"
  helper-text="Shows the HTML representation of the edited document. You can also modify or paste HTML here to see the changes reflected in the editor above. Note that you have to leave (blur) this field in order for the editor to update."
  style="width: 100%;"
  .value="${this.htmlValue}"
  @change="${(e: TextAreaChangeEvent) => this.setHtmlValue(e.target.value)}"
></vaadin-text-area>

<vaadin-text-area
  label="Delta Value"
  helper-text="Shows the Delta representation of the edited document. You can also modify or paste the Delta JSON here to see the changes reflected in the editor above. Note that you have to leave (blur) this field in order for the editor to update."
  style="width: 100%;"
  .value="${this.deltaValue}"
  @change="${(e: TextAreaChangeEvent) => {
    this.deltaValue = e.target.value;
  }}"
></vaadin-text-area>

...

setHtmlValue(htmlValue: string) {
  this.htmlValue = htmlValue;
  this.richTextEditor.dangerouslySetHtmlValue(htmlValue);
}
```

**Flow** — `RichTextEditorSetGetValue.java`

```java
RichTextEditor rte = new RichTextEditor();
rte.getStyle().set("height", "400px");
rte.setValueChangeMode(ValueChangeMode.TIMEOUT);

// HTML value
TextArea htmlTextArea = new TextArea("HTML Value");
htmlTextArea.setHelperText(
        "Shows the HTML representation of the edited document. You can also modify or paste HTML here to see the changes reflected in the editor above. Note that you have to leave (blur) this field in order for the editor to update.");
htmlTextArea.setWidthFull();
rte.addValueChangeListener(e -> htmlTextArea.setValue(e.getValue()));
htmlTextArea.addValueChangeListener(e -> {
    if (!rte.getValue().equals(e.getValue())) {
        rte.setValue(e.getValue());
    }
});

// Delta value
TextArea deltaTextArea = new TextArea("Delta Value");
deltaTextArea.setHelperText(
        "Shows the Delta representation of the edited document. You can also modify or paste the Delta JSON here to see the changes reflected in the editor above. Note that you have to leave (blur) this field in order for the editor to update.");
deltaTextArea.setWidthFull();
rte.asDelta().addValueChangeListener(
        e -> deltaTextArea.setValue(e.getValue()));
deltaTextArea.addValueChangeListener(e -> {
    if (!rte.asDelta().getValue().equals(e.getValue())) {
        rte.asDelta().setValue(e.getValue());
    }
});

add(rte, htmlTextArea, deltaTextArea);
```

**React** — `rich-text-editor-set-get-value.tsx`

```tsx
const htmlValue = useSignal('');
const deltaValue = useSignal('');

const richTextEditorRef = useRef<RichTextEditorElement>(null);

const handleEditorChange = (event: RichTextEditorValueChangedEvent) => {
  deltaValue.value = event.detail.value;
};

const handleHtmlChange = (event: TextAreaChangeEvent) => {
  const { value } = event.target;
  htmlValue.value = value;
  if (richTextEditorRef.current) {
    richTextEditorRef.current.dangerouslySetHtmlValue(value);
  }
};

return (
  <>
    <RichTextEditor
      style={{ height: '400px' }}
      value={deltaValue.value}
      onValueChanged={handleEditorChange}
      onHtmlValueChanged={(e) => {
        htmlValue.value = e.detail.value;
      }}
      ref={richTextEditorRef}
    />

    <TextArea
      label="HTML Value"
      helperText="Shows the HTML representation of the edited document. You can also modify or paste HTML here to see the changes reflected in the editor above. Note that you have to leave (blur) this field in order for the editor to update."
      style={{ width: '100%' }}
      value={htmlValue.value}
      onChange={handleHtmlChange}
    />

    <TextArea
      label="Delta Value"
      helperText="Shows the Delta representation of the edited document. You can also modify or paste the Delta JSON here to see the changes reflected in the editor above. Note that you have to leave (blur) this field in order for the editor to update."
      style={{ width: '100%' }}
      value={deltaValue.value}
      onChange={(e) => {
        deltaValue.value = e.target.value;
      }}
    />
  </>
);
```

## <a id="sola-lettura"></a>Sola lettura

Impostare il componente in sola lettura nasconde la toolbar e rende il contenuto non modificabile.

**Lit** — `rich-text-editor-readonly.ts`

```html
<vaadin-rich-text-editor
  style="height: 400px;"
  readonly
  .value="${this.richText}"
></vaadin-rich-text-editor>
```

**Flow** — `RichTextEditorReadonly.java`

```java
RichTextEditor rte = new RichTextEditor();
rte.setMaxHeight("400px");
String valueAsHtml = DataService.getTemplates().getRichTextHtml();
rte.setValue(valueAsHtml);
rte.setReadOnly(true);
add(rte);
```

**React** — `rich-text-editor-readonly.tsx`

```tsx
<RichTextEditor style={{ height: '400px' }} readonly value={templates.richTextDelta} />
```

## <a id="regolazione-automatica-dellaltezza"></a>Regolazione automatica dell’altezza

A meno che non sia impostato a un’altezza fissa, Rich Text Area regola automaticamente la propria altezza in base al contenuto.

### <a id="altezza-minima-e-massima"></a>Altezza minima e massima

Il ridimensionamento automatico può essere limitato a un’altezza minima e massima.

**Lit** — `rich-text-editor-min-max-height.ts`

```html
<vaadin-rich-text-editor
  style="min-height:200px; max-height: 400px;"
  .value="${this.richText}"
></vaadin-rich-text-editor>
```

**Flow** — `RichTextEditorMinMaxHeight.java`

```java
RichTextEditor rte = new RichTextEditor();
rte.setMaxHeight("400px");
rte.setMinHeight("200px");
String valueAsHtml = DataService.getTemplates().getRichTextHtml();
rte.setValue(valueAsHtml);
add(rte);
```

**React** — `rich-text-editor-min-max-height.tsx`

```tsx
<RichTextEditor
  style={{ minHeight: '200px', maxHeight: '400px' }}
  value={richText.value}
  onValueChanged={(event) => {
    richText.value = event.detail.value;
  }}
/>
```

## <a id="modalità-di-modifica-del-valore-flow"></a>Modalità di Modifica del Valore Flow

Con la Flow Java API, è possibile definire quando le modifiche del valore lato client vengono sincronizzate con il server. L’enum `ValueChangeMode` fornisce le seguenti modalità:

| Mode                      | Tempistica di sincronizzazione                                                                                                                                                              | Intervallo di timeout personalizzato |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| `EAGER`                   | Sincronizza il valore ogni volta che cambia lato client, ad esempio a ogni pressione di tasto.                                                                                              | No                                   |
| `LAZY`                    | Sincronizza il valore dopo che è trascorso un intervallo definito senza ulteriori modifiche. Se si verifica un’altra modifica prima della fine dell’intervallo, il timeout viene riavviato. | Sì                                   |
| `TIMEOUT`                 | Sincronizza il valore a intervalli definiti mentre il valore continua a cambiare.                                                                                                           | Sì                                   |
| `ON_CHANGE` (predefinito) | Sincronizza il valore sull’evento `change`, quando il valore del componente viene confermato.                                                                                               | No                                   |

Per le modalità che supportano un intervallo di timeout personalizzato, è possibile modificare l’intervallo con il metodo `setValueChangeTimeout()`. L’intervallo predefinito è 400 millisecondi.

**Flow** — `RichTextEditorValueChangeMode.java`

```java
var rte = new RichTextEditor();
rte.setMaxHeight("300px");
var modeSelector = new Select<>("Value Change Mode", valueChangeModes);
modeSelector.setValue(rte.getValueChangeMode());
modeSelector.addValueChangeListener(e -> {
    rte.setValue("");
    rte.setValueChangeMode(e.getValue());
});
var serverSideContent = new Span();
rte.addValueChangeListener(
        e -> serverSideContent.setText(e.getValue()));
```

## <a id="azioni-della-toolbar"></a>Azioni della toolbar

### <a id="cronologia"></a>Cronologia

| Pulsante | Titolo | Descrizione                               |
| -------- | ------ | ----------------------------------------- |
|          | Undo   | Annulla l’azione precedente.              |
|          | Redo   | Ripristina le azioni annullate da `Undo`. |

### <a id="enfasi"></a>Enfasi

| Pulsante | Titolo        | Descrizione                      |
| -------- | ------------- | -------------------------------- |
| B        | Bold          | **Rende il testo in grassetto.** |
| I        | Italic        | *Rende il testo in corsivo.*     |
| U        | Underline     | Sottolinea il testo.             |
| T        | Strikethrough | Barra il testo.                  |

### <a id="colore"></a>Colore

| Pulsante | Titolo          | Descrizione                 |
| -------- | --------------- | --------------------------- |
| A        | Text color      | Cambia il colore del testo. |
| A        | Text background | Cambia lo sfondo del testo. |

È possibile fornire una palette personalizzata per i selettori di colore usati da Rich Text Editor. La palette deve essere una lista di stringhe nel formato colore esadecimale.

**Lit**

```html
<vaadin-rich-text-editor
  .colorOptions="${['#000000', '#0066cc', '#ffffff']}"
></vaadin-rich-text-editor>
```

**Flow**

```java
RichTextEditor editor = new RichTextEditor();
editor.setColorOptions(List.of("#000000", "#0066cc", "#ffffff"));
```

**React**

```tsx
<RichTextEditor colorOptions={['#000000', '#0066cc', '#ffffff']} />
```

### <a id="intestazioni"></a>Intestazioni

Sono disponibili tre diverse intestazioni in Rich Text Editor: H1, H2, e H3. Le usi per indicare la struttura, così come l’importanza.

| Pulsante | Titolo | Descrizione             |
| -------- | ------ | ----------------------- |
| H1       | H1     | Intestazione livello 1. |
| H2       | H2     | Intestazione livello 2. |
| H3       | H3     | Intestazione livello 3. |

### <a id="pedice-e-apice"></a>Pedice e apice

| Pulsante | Titolo      | Descrizione                                                                                                |
| -------- | ----------- | ---------------------------------------------------------------------------------------------------------- |
| X        | Subscript   | Il testo in pedice è posizionato sotto la linea di base normale e con una dimensione del font più piccola. |
| X        | Superscript | Il testo in apice è posizionato sopra la linea di base normale e con una dimensione del font più piccola.  |

### <a id="elenco"></a>Elenco

| Pulsante | Titolo         | Descrizione                |
| -------- | -------------- | -------------------------- |
|          | Ordered list   | • Crea un elenco numerato. |
|          | Unordered list | • Crea un elenco puntato.  |

### <a id="allineamento"></a>Allineamento

| Pulsante | Titolo       | Descrizione                                |
| -------- | ------------ | ------------------------------------------ |
|          | Left align   | Allinea il testo a sinistra (predefinito). |
|          | Center align | Allinea il testo al centro.                |
|          | Right align  | Allinea il testo a destra.                 |

### <a id="immagine-e-link"></a>Immagine e link

| Pulsante | Titolo | Descrizione                                               |
| -------- | ------ | --------------------------------------------------------- |
|          | Image  | Carica e inserisce un’immagine dal Suo dispositivo.       |
|          | Link   | [Crea un collegamento ipertestuale](https://vaadin.com/). |

### <a id="blocchi"></a>Blocchi

| Pulsante | Titolo      | Descrizione                                |
| -------- | ----------- | ------------------------------------------ |
| ”        | Block quote | Crea una sezione citata da un’altra fonte. |
| <>       | Code block  | Crea un blocco formattato come codice.     |

### <a id="cancella"></a>Cancella

| Pulsante | Titolo           | Descrizione                                           |
| -------- | ---------------- | ----------------------------------------------------- |
|          | Clear formatting | Rimuove tutta la formattazione del testo selezionato. |

## <a id="componenti-correlati"></a>Componenti correlati

| Component                                                                | Raccomandazioni d’uso                       |
| ------------------------------------------------------------------------ | ------------------------------------------- |
| [Text Field](https://vaadin.com/docs/latest/it/components/text-field.md) | Input di testo di base su una singola riga. |
| [Text Area](https://vaadin.com/docs/latest/it/components/text-area.md)   | Input di testo di base su più righe.        |

`DC8286C2-D152-4234-831F-F90A00B97305`
