# RichTextEditor

A text field with formatting, for a description, a comment, a note or a post: a toolbar of bold, italic, headings, lists, quotes, code and links over editable text. It takes and gives HTML, keeps Textarea's field box, and posts with a plain form through a hidden input. Only the formats in its toolbar can be applied, typed or pasted.

**Dependencies:** npm: 4 direct, 8 total; registry: 6 direct, 7 total.

## Usage

### When to use

- People write text that keeps its formatting: a description, a note, a post, the body of an email.
- The text is shown back as formatted HTML, with headings, lists, quotes or links.

### When not to use

- Plain text over several lines, such as a comment without formatting. Use Textarea.
- A chat message with send and attachments. Use Composer.
- Code to read or copy. Use CodeBlock.

## Examples

### Description

A labeled field in a form, with the default toolbar.

```tsx
<Field className="w-full max-w-lg">
  <FieldLabel>Description</FieldLabel>
  <FieldControl>
    <RichTextEditor placeholder="What is this project about?" defaultValue="<p>Werewolf is a design system for <strong>teams building with AI</strong>.</p>" />
  </FieldControl>
  <FieldDescription>Markdown shortcuts work too: # for a heading, - for a list.</FieldDescription>
</Field>
```

### Comment

A small toolbar of marks and a link, two rows tall.

```tsx
<RichTextEditor className="max-w-lg" aria-label="Comment" placeholder="Leave a comment" rows={2} toolbar={["bold", "italic", "code", "|", "link"]} />
```

### Character limit

maxLength refuses edits past the limit; showCount shows the count at the bottom end.

```tsx
<RichTextEditor className="max-w-lg" aria-label="Bio" placeholder="A few words about you" rows={3} maxLength={160} showCount toolbar={["bold", "italic", "|", "link"]} />
```

### Document

Every heading level, a tall area that scrolls after 12 lines.

```tsx
<RichTextEditor className="max-w-lg" aria-label="Release notes" rows={8} maxRows={12} toolbar={["bold", "italic", "underline", "strike", "code", "|", "heading1", "heading2", "heading3", "|", "bulletList", "orderedList", "blockquote", "codeBlock", "|", "link", "|", "undo", "redo"]} defaultValue="<h1>Release 1.2</h1><p>Two fixes and one new component.</p><ul><li><p>Faster search</p></li><li><p>Smaller bundle</p></li></ul>" />
```

### Invalid

FieldError marks the field invalid and describes it.

```tsx
<Field className="w-full max-w-lg">
  <FieldLabel>Summary</FieldLabel>
  <FieldControl>
    <RichTextEditor rows={3} />
  </FieldControl>
  <FieldError>Write a summary before you publish.</FieldError>
</Field>
```

### Read only and disabled

readOnly hides the toolbar and keeps the text readable; disabled dims everything.

```tsx
<div className="flex w-full max-w-lg flex-col gap-md">
  <RichTextEditor aria-label="Published note" readOnly rows={2} defaultValue="<p>This note was <strong>published</strong> and can no longer change.</p>" />
  <RichTextEditor aria-label="Draft" disabled rows={2} defaultValue="<p>Editing is off while the draft syncs.</p>" />
</div>
```

## Do and don't

### Do

- Use it where people write text that keeps its formatting: a description, a note, a post, an email body.
- Pick the toolbar for the job: two or three marks and a link for a comment, headings and lists for a document.
- Store the HTML and render it back through the same tags. Sanitize it on the server before showing it to other people.

### Don't

- Do not use it for plain text, such as a name, a message or a code snippet; use Input, Textarea or Composer.
- Do not put it in a dense table row or a toolbar; it needs room for its own toolbar.
- Do not use the placeholder as the label.

## Props

| Name | Type | Values | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `string` |  |  | The document as HTML. "" is an empty document. Use with onValueChange. |
| `defaultValue` | `string` |  |  | The starting document as HTML, when the editor keeps its own value. |
| `onValueChange` | `(html: string) => void` |  |  | Called with the new HTML on every edit; "" when the document is empty. |
| `placeholder` | `string` |  |  | Hint shown while the document is empty. Not a label. |
| `toolbar` | `RichTextToolbarItem[] \| false` |  |  | The toolbar buttons in order, with "\|" for a line between groups. Tools: bold, italic, underline, strike, code, heading1, heading2, heading3, bulletList, orderedList, blockquote, codeBlock, link, undo, redo. Only the formats in it can be applied, typed or pasted. false hides the toolbar and allows every format through shortcuts. Default: marks \| heading2, heading3 \| lists, quote, code block \| link \| undo, redo. |
| `rows` | `number` |  | `4` | Lines of text the editable area shows before it grows. |
| `maxRows` | `number` |  |  | Lines after which the editable area scrolls instead of growing. |
| `disabled` | `boolean` |  | `false` | Can't be focused or edited, and the toolbar is off. Prefer readOnly for text the user should still read and copy. |
| `readOnly` | `boolean` |  | `false` | Can be read, selected and copied, but not edited. The toolbar is hidden. |
| `invalid` | `boolean` |  | `false` | Sets aria-invalid and draws the danger border. Pair it with error text linked through aria-describedby. A FieldError does both. |
| `required` | `boolean` |  | `false` | Sets aria-required on the text. Check for an empty value ("") yourself before submit. |
| `name` | `string` |  |  | Form name: a hidden input with this name carries the HTML, so the editor posts with a plain form. |
| `autoFocus` | `boolean` |  | `false` | Puts the caret at the end of the document on mount. |
| `maxLength` | `number` |  |  | Limit on the characters of text, formatting not counted. Edits that would pass it are refused; a value set through value is never cut. |
| `showCount` | `boolean` |  | `false` | Shows the number of characters at the bottom end, out of maxLength when it is set ("34 / 280"). |
| `countLabel` | `(remaining: number) => string` |  |  | What a screen reader hears near the limit. Defaults to "12 characters left"; pass a translated function on a page in another language. |
| `labels` | `RichTextEditorLabels` |  |  | Names of the toolbar, each tool and the link row, for a translated page: { toolbar, bold, italic, ..., linkUrl, linkPlaceholder, applyLink, removeLink, cancelLink }. |
| `contentClassName` | `string` |  |  | Class of the editable area. className lands on the field box. |

## Anatomy

| Part | Description |
| --- | --- |
| `root` | The field box: Textarea's raised fill, light edge, radius-container and input text. It shows the focus halo while the text has focus, the danger border when invalid and a dashed border when disabled. className lands here. |
| `header` | The toolbar above the text, split from it by a 1px line. It wraps onto more rows when narrow. |
| `tool` | One toolbar button: a sm icon-only Toggle (a plain button for undo and redo) with a tooltip that names it and its shortcut. |
| `separator` | A 1px line between groups of tools. Hidden from screen readers. |
| `row` | The link row under the toolbar, open while a link is edited: an address field with apply, remove and cancel buttons. |
| `content` | The editable text, padded like a Textarea. Its height starts at rows lines and stops growing at maxRows lines, then scrolls. Headings use the type scale one step down, so a heading inside a form never outranks the page title. |
| `hint` | Hint text over the empty document, in secondary text. |
| `count` | The character count at the bottom end, in mono xs text-tertiary with tabular figures. |

## Accessibility

Role: `textbox`

| Keys | Action |
| --- | --- |
| `Tab` | Moves focus into the toolbar (one stop), then into the text, then out. Inside the text, Tab is not captured, except to indent a list item. |
| `ArrowLeft / ArrowRight` | In the toolbar, moves between buttons. Home and End go to the first and last. |
| `Alt+F10` | From the text, moves focus to the toolbar. Escape in the toolbar returns to the text. |
| `Mod+B / Mod+I / Mod+U` | Bold, italic, underline. Mod is Cmd on macOS and iOS, Ctrl elsewhere; every button names its shortcut in its tooltip and aria-keyshortcuts. |
| `Mod+K` | Opens the link row for the selection. Enter applies the address, Escape closes the row and returns to the text. |
| `Mod+Z / Mod+Shift+Z` | Undo and redo. |

- The editable element has role textbox with aria-multiline, and carries the name, description, aria-invalid, aria-required and aria-readonly, so it reads as one field.
- Name it with aria-label, aria-labelledby or a label whose for points at its id. A label for the id names the field and focuses it on press, so FieldLabel and FieldControl work inside a Field.
- The toolbar is a Toolbar with one tab stop over its enabled buttons. Marks and blocks are toggle buttons with aria-pressed; undo and redo are plain buttons, disabled when there is nothing to undo or redo.
- The placeholder is hidden from screen readers and given to the textbox as aria-placeholder instead.
- With showCount, the textbox is described by the count; near maxLength a status region says how many characters are left once typing pauses.
- A link the user adds gets rel="noopener noreferrer nofollow". Script addresses are refused and the address field is marked invalid.

## Install

```bash
npx werewolf-ui add rich-text-editor
```

Run `npx werewolf-ui init` once in your app before adding components. Init sets up tokens, their CSS import and agent rules. Add installs this component and its dependencies while preserving your theme. See [Installation](https://www.werewolf-ui.dev/docs/installation.md) for requirements and the alternative registry setup.
