# RichTextEditor

Crate: `libero`
Import: `use libero::components::{RichTextEditor, rich_text::Doc};`
Feature: `rich-text-editor` (off by default, turns on `toolbar`, `text-field`, `menu`, `code`, `mark`, `modal`, `action-icon`, `button`, `dialog`, `icon`, `shortcut-help`, `text`, `flex`, `use-history`; [features.md](features.md))
Source: <https://github.com/tdymel/libero/tree/main/libero/src/components/form/rich_text_editor/view.rs>
Index: [index.md](index.md) lists every other page
Description: A rich text field over a `Doc`: headings, lists, quotes, code blocks and marks, with undo, shortcuts and Markdown typing.

A rich text field over a `Doc`: paragraphs, headings, lists, quotes, code blocks
and marks, with undo, the usual shortcuts and Markdown typing shortcuts.
`Doc::to_markdown` and `Doc::from_markdown` convert it; the types live in
`libero::components::rich_text`. Typing `# ` starts a heading, `- ` a list,
`1. ` a numbered list, `> ` a quote, `---` and a space a rule, and three
backticks a code block. Closing `**bold**`, `*italic*`, `~~strike~~` or
`` `code` `` marks the span.

## Usage

```rust
use dioxus::prelude::*;
use libero::components::{RichTextEditor, rich_text};

#[component]
fn Demo() -> Element {
    let mut doc = use_signal(|| rich_text::Doc::from_markdown("## Release notes"));

    rsx! {
        RichTextEditor {
            value: doc(),
            onchange: move |next| doc.set(next),
            label: "Notes",
            placeholder: "Start writing",
        }
    }
}
```

## Accessibility

### Keyboard

`Mod` in a `Keymap` is Cmd on Apple platforms and Ctrl elsewhere; the table
shows Ctrl.

| Key | Action |
|---|---|
| `Ctrl+B` | Bold. |
| `Ctrl+I` | Italic. |
| `Ctrl+U` | Underline. |
| `Ctrl+Shift+S` or `Ctrl+Shift+X` | Strikethrough. |
| `Ctrl+E` | Inline code. |
| `Ctrl+Alt+0` | Paragraph. |
| `Ctrl+Alt+1` | Heading 1. `Ctrl+Alt+2` to `Ctrl+Alt+6` make headings 2 to 6. |
| `Ctrl+Alt+C` | Code block. |
| `Ctrl+Shift+L` | In a code block: opens its language menu. Choosing or Escape returns to the caret. |
| `Ctrl+Shift+8` | Bulleted list. |
| `Ctrl+Shift+7` | Numbered list. |
| `Ctrl+Shift+9` | Task list: turns the list items at the caret into tasks, or back. Outside a list it starts one. Typing `[ ] ` or `[x] ` at the start of a list item does the same. |
| `Ctrl+Alt+Enter` | In a task item: checks it, or unchecks it. With a selection, every task in it. |
| `Ctrl+Shift+B` | Quote. |
| `Ctrl+Shift+Enter` | Horizontal rule. |
| `Ctrl+Enter` | In a code block: leaves it for a new paragraph after it. Elsewhere the key passes on, so your own `Ctrl+Enter` still runs, or sends with `onsubmit` and `SubmitOn::ModEnter`. |
| `ArrowDown` | On the last line of a code block that ends the document: leaves it for a new paragraph. Clicking below the last block does the same. |
| `Enter` | Twice at the end of a code block: the second drops the empty line and leaves the block, also on a touch keyboard. With `onsubmit` (the default `SubmitOn::Enter`) it sends the document instead, except in a code block and in an empty document. |
| `Tab` or `Shift+Tab` | In a list item: nests it under the item before, or moves it out. Elsewhere Tab moves focus on as usual. |
| `Escape`, then `Tab` | Escape, then Tab or Shift+Tab: leaves the editor, also from a list item. |
| `Shift+Enter` | Line break inside the block. |
| `Ctrl+Backspace` or `Ctrl+Delete` | Deletes the word before or after the caret (`Alt` on a Mac). |
| `Cmd+Backspace` or `Cmd+Delete` | On a Mac: deletes to the start or end of the line, which ends at a line break or the block's edge. |
| `Ctrl+Z` | Undo. |
| `Ctrl+Shift+Z` or `Ctrl+Y` | Redo. |
| `Ctrl+K` | Opens the link dialog: links the selection, or edits or removes the link at the caret. |
| `Ctrl+Shift+U` | Removes the link at the caret. |
| `Ctrl+/` | Lists the editor's shortcuts, from the live keymap. Where `/` is `Shift+7`, as on a German layout, `Ctrl+Shift+7` stays the numbered list and the keypad `/` opens the list. |
| `Alt+F10` | Moves focus to the toolbar; the arrow keys move through it, Escape returns to the text. |

### Libero handles

- The text is a multiline `role="textbox"`, named by `label` and described by
  `description`, `helper` and a hint read on focus: in a list Tab indents, and
  Escape, then Tab leaves (`RichTextEditorLabels::leave_hint`).
- The toolbar is one tab stop, moved through with the arrows. Clicking it
  keeps focus and the selection in the text. Each mark and block button
  reports `aria-pressed`, shows its name and chord in a tooltip on hover and
  focus, and carries the chord as `aria-keyshortcuts`.
- In a narrow column the toolbar stays one row: the less used buttons move
  into a "More formatting" menu, so the arrows only reach what is shown. Bold,
  italic and the text type menu always stay.
- A shortcut that toggles a mark, list, quote or block type is said in a
  polite live region, "Bold on", "Heading 2".
- The text type menu and a code block's language menu are menu buttons whose
  name includes the current choice, "Code language: Rust". The language button
  on the fence is not a tab stop; `Ctrl+Shift+L` reaches it.
- The link dialog focuses its labelled URL field and shows a refused scheme as
  that field's error. Closing or saving returns focus to what opened it: the
  text after `Ctrl+K` or a click while typing, else the Link button. A toolbar
  menu's Escape returns the same way.
- With `onsubmit` the text carries the send key as `aria-keyshortcuts`
  (`Enter`, or `Control+Enter`, `Meta+Enter` on Apple platforms, for
  `SubmitOn::ModEnter`), and with `SubmitOn::Enter` also
  `enterkeyhint="send"`, so a phone keyboard labels its Enter key. A send
  leaves focus in the text, and the handle's `clear` keeps it there.
- With `max_length`, typing or a paste that reaches the limit says "Character
  limit reached" in the live region (`RichTextEditorLabels::limit_reached`),
  once until the text or the caret moves, so further refused keys stay quiet.
- A task item's box is a `role="checkbox"` with `aria-checked`, named by its
  item's text through `aria-labelledby` (an empty item falls back to "Task
  done", `RichTextEditorLabels::toggle_task`). It is not a tab stop and the caret never lands in it: `Ctrl+Alt+Enter`
  toggles the items at the caret, a click toggles its own item without moving
  the caret, and both say "Task done on" or "off". In `RichTextView` the box
  is `aria-readonly`.
- Every edit goes through the document model, so undo, the `onchange` value
  and the screen stay in step. Input methods (IME) compose natively.
- While `overlay` is set, the text carries `aria-controls`,
  `aria-autocomplete="list"` and `aria-activedescendant` from
  `active_descendant`, so a screen reader reads the highlighted option.
  `overlay_results` says the option count, "2 results", in the live region
  when it changes.

### You must

- Leave `label` unset only when something else names the editor, such as an
  `aria_label`.
- Tell your users about the chords you bind in `keymap`.
- Bind only chords the browser leaves to the page. `Ctrl+N`, `Ctrl+T`,
  `Ctrl+W`, `Ctrl+Tab` and their Shift forms never reach it (on a Mac also
  `Cmd+Q`, `Cmd+H`, `Cmd+M`), and `Ctrl+P`, `Ctrl+S`, `Ctrl+D`, `Ctrl+F`,
  `Ctrl+L` and `Ctrl+Shift+I`/`J`/`C` belong to the browser too. A chord you
  unbind goes back to the browser: without Underline, `Ctrl+U` opens the page
  source. On Windows `Ctrl+Alt` is AltGr, and where it types a character the
  character wins (`Ctrl+Alt+2` types `²` on a German layout).
- Make a `NodeViews` atom show its node's name as text (a mention shows
  `@name`). A screen reader reads the non-editable island as it is.
- Give an `overlay` list `role="listbox"` with an id per `role="option"`, pass
  the highlighted one as `active_descendant` and the count as
  `overlay_results`, and steer it with the keyboard through `intercept`.
  Escape should close it.
- Name each `RichTextTool` with its `label`: the button shows only its icon.
- Say in the `helper` that Enter sends and how many characters `max_length`
  allows: the editor says only when the limit is reached.

### Example

Release notes with `label: "Notes"`: a screen reader reads a multiline "Notes"
text box. `Ctrl+B` says "Bold on", and `Alt+F10` moves to the toolbar, where
the Bold button reads as pressed.

### Limits

- On Blitz (native) the document is shown read-only, through `RichTextView`.
- Copy and cut write the selection as Markdown, as plain text and as
  `text/markdown`: a quote as `>`, a code block fenced with its language,
  lists, headings, rules, marks and links as written. Custom nodes write
  through their `NodeSpec::markdown` (pass `registry`). Cut is one undo step.
- Paste reads Markdown back into formatted blocks; custom nodes stay text.
  Text from elsewhere is read the same way, one paragraph per line. In a code
  block it is pasted as is. A pasted web address alone links the selection, or
  becomes a link at the caret.
- A typed `http`, `https` or `mailto` address followed by a space or Enter
  becomes a link, a closing full stop or comma left outside, and undo brings
  the text back; `[text](address)` links the text. Other schemes stay text, as
  does a `www.` address without a scheme.
- Drag and drop of text is ignored. A replacement with no word to replace (no
  target range, collapsed caret) is ignored too.
- Headings render as `h1` to `h6` as stored, so a `RichTextView` in a comment
  list adds them to the page's heading outline; give it a `heading_offset` to
  lower them below the page's own.
- `spellcheck` is off by default: Chromium shows no squiggles for text the
  editor writes. Firefox and Safari are not verified.

## Props

### `RichTextEditor`

| Prop | Type | Default | Description |
|---|---|---|---|
| `value` | `Option<Doc>` | - | The document. Leave it out and the editor keeps its own. An echo of a document the editor sent is not a reset. |
| `onchange` | `EventHandler<Doc>` | - | Fires with the new document after every edit. Moving the caret does not fire. |
| `validate` | `Validators<Doc>` | - | Rules over the document, shown once the field loses focus or its form is submitted. |
| `name` | `FieldName<Doc>` | - | A path such as `Post::FIELDS.body()` binds the document to the surrounding `Form`'s value when the editor has no `onchange`. |
| `placeholder` | `String` | - | Shown while the document is a single empty block, a code block aside. |
| `onsubmit` | `EventHandler<Doc>` | - | Sends the document when `submit_on` is pressed, as in a chat or comment box. The editor keeps its text: clear it with the handle's `clear` or a new `value`. Nothing is sent from an empty document, a code block or while an `overlay` takes the key; there Enter does its usual job. With `SubmitOn::Enter` the Enter key shows as "send" on phones, and Enter pressed in a word the keyboard is still composing sends the document with that word in it. |
| `submit_on` | `SubmitOn` | `SubmitOn::Enter` | The key that fires `onsubmit`: `Enter` (Shift+Enter breaks the line) or `ModEnter` (Ctrl+Enter, Cmd+Enter on Apple platforms; Enter stays a new paragraph). Mod+Enter in a code block still leaves it. |
| `max_length` | `usize` | - | The most characters of plain text the document holds, counted as `Doc::plain_text` does (a line break between blocks counts one). Typing and paste stop at it, and reaching it is said in the editor's live region. A phone keyboard's composed text cannot be refused, so there the limit is soft: the surplus is cut when the word is committed. |
| `spellcheck` | `bool` | `false` | Lets the browser spell check the text. A replacement the browser offers (a spelling suggestion, autocorrect) applies to its word as one undo step. Chromium marks no text the editor writes, so there it shows no squiggles. |
| `toolbar` | `bool` | `true` | Shows the formatting toolbar above the text: marks, link, text type menu, lists, quote, code block, undo and redo. A narrow toolbar moves what does not fit into a More menu. |
| `keymap` | `Keymap` | `Keymap::default()` | Which chords run which commands. `Mod` is Cmd on Apple platforms and Ctrl elsewhere. |
| `commands` | `Commands` | `Commands::default()` | What the keymap and the toolbar run. Register your own command under a name and bind a chord to it. |
| `handle` | `RichTextHandle` | - | From `use_rich_text_editor()`: runs commands from your own toolbar (`run`) and reads the state reactively (`is_active`, `block_kind`, `list_kind`, `in_quote`, `can_undo`, `can_redo`, `is_empty`, `plain_text`). `clear()` empties the editor and keeps focus in it (undo starts over), `focus()` puts the caret back. One handle drives one editor. |
| `nodes` | `NodeViews` | `NodeViews::new()` | Your component per custom node name, e.g. a mention. It gets `NodeViewProps { name, attrs, children }` and renders `children` exactly once. Built-ins (`paragraph`, `heading` with `level`, `quote`, `list` with `ordered` and `start`, `list_item`, `rule`) take a view under their name too; `code_block` stays fixed. |
| `registry` | `NodeRegistry` | - | Your node types. Copy and cut write your nodes through their `to_markdown`, and a debug build warns about a `nodes` name that is not registered, such as a typo. |
| `intercept` | `Callback<EditorInput, bool>` | - | Sees each key press (`EditorInput::Key`, before the keymap) and typed text (`EditorInput::Text`) first; return `true` to take it over, and the editor does nothing with it. Android soft keyboards report most keys as `Unidentified` and compose their text, which never arrives as `Text`; Enter still arrives as a key. Read typed text through the handle's `with_state` instead. |
| `overlay` | `Element` | - | Floats at the caret while `Some`, such as a mention list: under the caret's line, above it near the window's bottom edge, mirrored in right-to-left text. It renders in the page's portal, so a parent's `overflow` does not clip it and it does not inherit the editor's CSS context. Focus stays in the text; pressing the overlay does not take it. |
| `active_descendant` | `String` | - | The id of the overlay's highlighted option. While `overlay` is `Some` the text carries it as `aria-activedescendant`, with `aria-controls` naming the overlay and `aria-autocomplete="list"`. |
| `overlay_results` | `usize` | - | How many options the overlay lists. While `overlay` is `Some`, a change is announced through the editor's polite live region ("2 results", or "No results" at 0; `RichTextEditorLabels::results` and `nothing_found`). |
| `tools` | `Vec<RichTextTool>` | `vec![]` | Your toolbar buttons, after the block buttons: `RichTextTool::new(command, label, icon)` runs the command by name; `.active(fn)` makes it a toggle with `aria-pressed`. They never move into the More menu. |
| `size` | `Responsive<Size>` | `md` | Padding and font size. Or one per breakpoint, `size: responsive(Size::Sm).md(Size::Lg)`. |
| `radius` | `Responsive<ThemeAwareValue>` | `sm` | Corner radius, independent of `size`. Or any CSS, e.g. `radius: "0"`. Or one per breakpoint, `radius: responsive(Size::Sm).md(Size::Xl)`. |
| `label` | `Caption` | - | The field's caption, above the toolbar. It names the text. |
| `description` | `Caption` | - | Between the label and the control. What to enter. |
| `label_trailing` | `Caption` | - | Content in the label row, outside the `<label>`, at the row's end: a button cannot sit inside the label. Takes a string or an `Element`. |
| `description_position` | `DescriptionPosition` | `Above` | Where the description sits: `above` the control, or `below` it. `below` keeps the controls of side-by-side fields level when only some have a description; give the row `align: "flex-start"`. Unset, the theme's `field.description_position`. A checkbox, switch or radio draws its description under the label either way. |
| `helper` | `Caption` | - | Under the control. Formatting rules or limits. |
| `status` | `FieldStatus` | `Valid` | Validation state, under the helper. A bare `&str` is an error; an empty one or `None` is `Valid`. |
| `required` | `bool` | `false` | Marks the field required and adds an asterisk to the label; a field without a visible `label` shows no mark. Inside a `Form`, an empty one fails the submit. |
| `disabled` | `bool` | `false` | Disables and dims the field and hides the toolbar. |
| `readonly` | `bool` | `false` | Shows the document, focusable but not editable, without the toolbar. |

`RichTextEditor` also takes the `<div>` HTML attributes and, like every
component, the shared props `sx`, `class`, `style`, `states`, `hidden_from`, `visible_from`, and any extra
HTML attributes.

### `RichTextView`

| Prop | Type | Default | Description |
|---|---|---|---|
| `value` | `Doc` | required | The document to show. |
| `nodes` | `NodeViews` | `NodeViews::new()` | Your component per custom node name, as the editor's `nodes`. Built-ins take a view under their name too; `code_block` stays fixed. |
| `heading_offset` | `u8` | `0` | Added to every heading's level, clamped at `h6`, so a comment's `#` sits below the host page's headings: `1` draws `h1` as `h2`. |

`RichTextView` also takes the `<div>` HTML attributes and, like every
component, the shared props `sx`, `class`, `style`, `states`, `hidden_from`, `visible_from`, and any extra
HTML attributes.

## Style API

Style a part with the `parts` prop, or address it as `[data-slot='…']` in your
own CSS. The names are stable. [Style API in Styling](styling.md#style-api)
explains how parts work.

| Part | `data-slot` | Description |
|---|---|---|
| `FieldPart::Label` | `label` | The label above the toolbar. |
| `FieldPart::Required` | `required` | The required asterisk, in the label. |
| `FieldPart::LabelRow` | `label-row` | The row holding the label and its `label_trailing`; drawn only with a trailing slot. |
| `FieldPart::LabelTrailing` | `label-trailing` | The `label_trailing` slot, at the end of the label row. |
| `FieldPart::Description` | `description` | The caption between the label and the control. |
| `FieldPart::Frame` | `frame` | The bordered box around the text. |
| `FieldPart::Control` | `control` | The editable text the label names. |
| `FieldPart::Helper` | `helper` | The caption under the control. |
| `FieldPart::Status` | `status` | The validation message. |

## Theme defaults

It shares `FieldDefaults` with every field and starts at `Textarea`'s `size`
and `radius`.

| Field | Type | Description |
|---|---|---|
| `textarea.size` | `Size` | Default `size` when the prop is omitted, `md`. |
| `textarea.radius` | `Size` | Default `radius` when the prop is omitted, `sm`. |

The `--lsx-field-*` variables are [TextField](text_field.md)'s, shared unchanged.

## Data attributes

The same as [TextField](text_field.md). The wrapper's and the frame's
`data-state` carry `size-<size>`, `radius-<size>`, `disabled`, `required`,
`warning` and `error`, and the caption slots carry `data-slot`. The text
carries `data-empty` while the document is a single empty block, a code block aside.
