Font Awesome Build Awesome
Search ⌘KCtrl+K
Light Dark System Docs Color Scheme: System \ Default Awesome Shoelace Active Brutalist Glossy Matter Mellow Playful Premium Tailspin Docs Theme: Default Icon Style: Classic Regular
Solid Regular Light Thin Classic Sharp Duotone Sharp Duotone
Docs Most styles require Font Awesome Pro.
Server-Side Rendering: Off Server-Side Rendering Docs
View on GitHub
Start Components Docs Help Pro
Login Log into your account
Web Awesome Font Awesome Build Awesome
Search this site… /
Light Dark System Docs Color Scheme: System \ Default Awesome Shoelace Active Brutalist Glossy Matter Mellow Playful Premium Tailspin Docs Theme: Default Icon Style: Classic Regular
Solid Regular Light Thin Classic Sharp Duotone Sharp Duotone
Docs Most styles require Font Awesome Pro.
Server-Side Rendering: Off Server-Side Rendering Docs
View on GitHub
Components Pro

Getting Started

  • Installation
  • Usage
  • Forms
  • Localization
  • Frameworks
  • Using with AI
  • Figma Design Kit ProThis requires access to Web Awesome Pro
  • Server Rendering

Resources

  • Accessibility
  • Browser Support
  • Contributing
  • Patterns ProPatterns require access to Web Awesome Pro
  • Migrating from Shoelace
  • Visual Tests
  • Changelog
  • Help & Support

Theming & Utilities

  • Overview
  • Built-in Themes
  • Color Palettes
  • Design Tokens
  • Customizing & Theming
  • CSS Utilities

Actions

  • Button
  • Button Group
  • Copy Button
  • Dropdown
    • Dropdown Item

Forms

  • Checkbox
  • Checkbox Group
  • Color Picker
  • Combobox ProThis requires access to Web Awesome Pro
  • Date Input ProThis requires access to Web Awesome Pro
  • Date Picker ProThis requires access to Web Awesome Pro
  • File Input ProThis requires access to Web Awesome Pro
  • Input
  • Known Date
  • Number Input
  • OTP Input
  • Radio Group
    • Radio
  • Rating
  • Rich Text Editor ProThis requires access to Web Awesome Pro
  • Select
    • Option
  • Slider
  • Switch
  • Tag Input
  • Textarea
  • Time Input

Layout

  • Accordion
    • Accordion Item
  • Card
  • Details
  • Dialog
  • Divider
  • Drawer
  • Page
  • Scroller
  • Split Panel

Navigation

  • Breadcrumb
    • Breadcrumb Item
  • Pagination
  • Stepper
    • Step
  • Tab Group
    • Tab
    • Tab Panel
  • Tree
    • Tree Item

Feedback

  • Badge
  • Callout
  • Progress Bar
  • Progress Ring
  • Skeleton
  • Spinner
  • Tag
  • Toast
    • Toast Item
  • Tooltip

Media

  • Animated Image
  • Avatar
  • Carousel
    • Carousel Item
  • Code Highlighter
  • Comparison
  • Icon
  • Lightbox
    • Lightbox Item
  • Markdown
  • QR Code
  • Video ProThis requires access to Web Awesome Pro
  • Video Playlist ProThis requires access to Web Awesome Pro
  • Zoomable Frame

Data Viz ProThis requires access to Web Awesome Pro

  • Bar Chart
  • Bubble Chart
  • Data Grid
  • Doughnut Chart
  • Line Chart
  • Pie Chart
  • Polar Area Chart
  • Radar Chart
  • Scatter Chart
  • Sparkline
  • Advanced Usage

Helpers

  • Animation
  • Counter
  • Format Bytes
  • Format Date
  • Format Number
  • Include
  • Intersection Observer
  • Mutation Observer
  • Number Ticker
  • Popover
  • Popup
  • Random Content
  • Relative Time
  • Resize Observer

Rich Text Editor

  • Examples
  • Label
  • Hint
  • Placeholder
  • Initial Value
  • Displaying the Content
  • Appearance
  • Size
  • Disabled
  • Readonly
  • Character Count
  • Validation
  • Input Behavior
  • Markdown
  • Customizing the Toolbar
  • Disabling Features
  • Heading Levels
  • Links
  • Images
  • Embeds
  • Tables
  • Colors
  • Keyboard & Markdown Shortcuts
  • Suggestions
  • Reacting to Changes
  • Tracking Unsaved Changes
  • Controlling the Editor with JavaScript
  • Styling the Editor
  • What's Not Included
  • Accessibility Considerations
  • API
  • Importing
  • Slots
  • Attributes & Properties
  • Methods
  • Events
  • CSS Custom Properties
  • Custom States
  • CSS Parts
  • Dependencies
On This Page...
  • Examples
  • Label
  • Hint
  • Placeholder
  • Initial Value
  • Displaying the Content
  • Appearance
  • Size
  • Disabled
  • Readonly
  • Character Count
  • Validation
  • Input Behavior
  • Markdown
  • Customizing the Toolbar
  • Disabling Features
  • Heading Levels
  • Links
  • Images
  • Embeds
  • Tables
  • Colors
  • Keyboard & Markdown Shortcuts
  • Suggestions
  • Reacting to Changes
  • Tracking Unsaved Changes
  • Controlling the Editor with JavaScript
  • Styling the Editor
  • What's Not Included
  • Accessibility Considerations
  • API
  • Importing
  • Slots
  • Attributes & Properties
  • Methods
  • Events
  • CSS Custom Properties
  • Custom States
  • CSS Parts
  • Dependencies

Rich Text Editor

<wa-rich-text-editor>
ProIncluded with Web Awesome Pro Experimental Forms Since 3.15

Rich text editors let users write and format content with a toolbar and keyboard shortcuts, and submit the result as HTML like a textarea.

Get Rich Text Editor with Web Awesome Pro! Already have Pro? Log In
Subscribing to Web Awesome Pro gives you every Pro component, plus premium themes, color tools, team collaboration, and more.
  • Pro Components
  • Native Styles
  • CSS + Layout Utilities
  • Ever-Growing Pattern Library
  • Unlimited Hosted Projects
  • Pre-Built Pro Themes
  • Pro Theme Builder
  • Pro Color Tools
  • Official Figma Design Kit
  • WA Pro Perpetual License
  • Actual Human™ Support
Get Web Awesome Pro + Rich Text Editor!

Writers choose styles that describe what text is, not how it looks. There are no font or size controls, so content takes on the typography of wherever it's displayed. The color and alignment tools aren't in the default toolbar, but can be added when you need them.

<wa-rich-text-editor label="Description" placeholder="Describe the project"></wa-rich-text-editor>

Exports now include custom fields and respect the active filters.

<wa-rich-text-editor label="Release Notes" hint="Summarize what changed in this version.">
  <p>Exports now include <strong>custom fields</strong> and respect the active filters.</p>
</wa-rich-text-editor>

This component works with standard <form> elements. See form controls for form submission and client-side validation.

Examples

Link to This Section

Label

Link to This Section

Use the label attribute to give the editor an accessible label. For labels that contain HTML, use the label slot instead.

<wa-rich-text-editor label="Comment"></wa-rich-text-editor>

Hint

Link to This Section

Add a descriptive hint to an editor with the hint attribute. For hints that contain HTML, use the hint slot instead.

<wa-rich-text-editor label="Bio" hint="A few sentences about your background and interests."></wa-rich-text-editor>

Placeholder

Link to This Section

Use the placeholder attribute to add a placeholder. It shows when the editor is empty.

<wa-rich-text-editor label="Reply" placeholder="Write a reply"></wa-rich-text-editor>

Initial Value

Link to This Section

Like a <textarea>, the editor reads its initial value from the HTML between its tags. Resetting the containing form will restore it. To write the initial value in Markdown instead, set the format attribute to markdown.

Decisions

  • Ship the import tool in the next release.
  • Move the weekly check-in to Thursdays.

Next review is scheduled for the end of the month.

<wa-rich-text-editor label="Meeting Notes">
  <h2>Decisions</h2>
  <ul>
    <li>Ship the import tool in the next release.</li>
    <li>Move the weekly check-in to <strong>Thursdays</strong>.</li>
  </ul>
  <p>Next review is scheduled for <em>the end of the month</em>.</p>
</wa-rich-text-editor>

You can also use the value attribute with escaped HTML, or set the value property. When the value attribute is present, content between the tags is ignored.

<wa-rich-text-editor
  label="Product Summary"
  value="&lt;p&gt;Lightweight, water-resistant, and built for &lt;strong&gt;everyday carry&lt;/strong&gt;.&lt;/p&gt;"
></wa-rich-text-editor>

Only place trusted markup between the tags.
The browser runs any scripts in it before the editor reads it. For content users wrote, use the value attribute or property instead.

The value is serialized from the editor's content, so it can differ from the markup you set. Unsupported markup is dropped, headings outside heading-levels move to the nearest allowed level, and disabled features are removed. For the full list of what the value keeps, see Displaying the Content.

Displaying the Content

Link to This Section

The value is HTML made of the elements below. Classes, IDs, scripts, event handlers, and unknown elements are stripped, but their text content is kept. Equivalent markup is converted as it's read. For example, <b> becomes <strong> and text-align: right becomes end. Pasted content and insertHtml() follow the same rules.

Content Elements and attributes
Blocks <p>, <h1> to <h6> (limited by heading-levels), <blockquote>, <pre><code>, <hr>
Text formatting <strong>, <em>, <u>, <s>, <code>, <sub>, <sup>, <br>, <mark>, <mark style="background-color: …">, <span style="color: …">
Alignment style="text-align: center", end, or justify on paragraphs and headings
Lists <ul>, <ol> with start, <li>. Each item's text is wrapped in a <p>
Links <a> with href, title, target, and rel
Images <img> with src, alt, title, width, and an alignment style; <figure> with an alignment style, holding an <img> and a <figcaption>
Embeds <iframe> with src, title, width, height, allowfullscreen, and loading="lazy"
Tables <table>, <tbody>, <tr>, <th>, <td> with colspan, rowspan, and data-colwidth. Each cell's text is wrapped in a <p>
Mentions <span data-mention="…"> with the mention's label as its text (see Suggestions)

Whitespace is normalized, and an empty editor's value is an empty string ("").

Sanitize the HTML on your server before you store or display it.
The editor rejects unsafe URLs, but a form submission can be crafted without it.

You can use the table above as your sanitizer's allowlist. The only style properties the value uses are color, background-color, text-align, float, margin-inline, margin-inline-start, margin-inline-end, display, and width. Allow <iframe> only for the hosts you trust, since embeds load third-party pages wherever the content is displayed. Removing a tool from the toolbar doesn't shrink this list; only disabled-features does.

The editor's styles don't travel with the value, so the page that displays it may need some custom CSS. Web Awesome's native styles cover headings, paragraphs, lists, blockquotes, code, tables, and <mark>, and wa-prose adds rhythm. The editor styles its content with the same tokens as the native styles, with tighter spacing between paragraphs. You'll probably want a few rules like these, too:

.user-content {
  /* Contains images that text wraps around */
  display: flow-root;
}

/* List items and table cells wrap their text in a paragraph */
.user-content :is(li, th, td) > p {
  margin: 0;
}

/* Resized images stay inside their container */
.user-content img {
  max-width: 100%;
  height: auto;
}

/* The paragraph after a wrapped image starts below it */
.user-content :has(img[style*='float']) + *,
.user-content figure[style*='float'] + * + * {
  clear: both;
}

/* Embeds without a size fill the width at 16:9 */
.user-content iframe:not([width]) {
  width: 100%;
  aspect-ratio: 16 / 9;
  border: 0;
}

/* Keeps colored highlights from taking the native <mark> text color */
.user-content mark[style] {
  color: inherit;
}

.user-content [data-mention] {
  padding-inline: 0.25em;
  border-radius: var(--wa-border-radius-s);
  background-color: var(--wa-color-brand-fill-quiet);
  color: var(--wa-color-brand-on-quiet);
}

Column widths are stored in a data-colwidth attribute on each table cell. Browsers ignore this attribute, so outside the editor, columns size to fit their content. To keep the widths, convert them to a <colgroup>.

The default text colors use light-dark(), so each color has a light and a dark version. The dark version only appears on pages that set color-scheme. If the content will be shown outside your site, see Colors before choosing a palette.

Appearance

Link to This Section

Use the appearance attribute to change the editor's visual appearance.

<div class="wa-stack">
  <wa-rich-text-editor appearance="outlined" label="Outlined" toolbar="bold italic underline"></wa-rich-text-editor>
  <wa-rich-text-editor appearance="filled" label="Filled" toolbar="bold italic underline"></wa-rich-text-editor>
  <wa-rich-text-editor
    appearance="filled-outlined"
    label="Filled outlined"
    toolbar="bold italic underline"
  ></wa-rich-text-editor>
</div>

Size

Link to This Section

Use the size attribute to change the editor's size. The toolbar, content, and menus scale together.

<div class="wa-stack">
  <wa-rich-text-editor size="xs" label="Extra small" toolbar="bold italic underline"></wa-rich-text-editor>
  <wa-rich-text-editor size="s" label="Small" toolbar="bold italic underline"></wa-rich-text-editor>
  <wa-rich-text-editor size="m" label="Medium" toolbar="bold italic underline"></wa-rich-text-editor>
  <wa-rich-text-editor size="l" label="Large" toolbar="bold italic underline"></wa-rich-text-editor>
  <wa-rich-text-editor size="xl" label="Extra large" toolbar="bold italic underline"></wa-rich-text-editor>
</div>

Disabled

Link to This Section

Use the disabled attribute to disable the editor.

This content can't be edited or focused.

<wa-rich-text-editor label="Notes" disabled>
  <p>This content can't be edited or focused.</p>
</wa-rich-text-editor>

Readonly

Link to This Section

Use the readonly attribute to keep content visible but uneditable. Unlike disabled, a readonly editor stays focusable and its value is still submitted with the form. The toolbar is hidden while the editor is readonly.

Subscriptions renew automatically at the end of each billing period. You can cancel at any time from your account settings.

<wa-rich-text-editor label="Terms" readonly>
  <p>
    Subscriptions renew automatically at the end of each billing period. You can cancel at any time from your
    <strong>account settings</strong>.
  </p>
</wa-rich-text-editor>

Character Count

Link to This Section

Add the with-count attribute to show a character count below the editor. When combined with maxlength, the count shows remaining characters instead.

<div class="wa-stack">
  <wa-rich-text-editor label="Comment" hint="Share your feedback." with-count></wa-rich-text-editor>
  <wa-rich-text-editor label="Summary" hint="Keep it short." with-count maxlength="140"></wa-rich-text-editor>
</div>

The count is the length of textValue: the text without markup, with one character for each line break or block boundary. Mentions count as their label. If your server enforces maxlength, make sure it counts the same way.

Unlike a <textarea>, the editor doesn't stop typing at maxlength, so pasted content is never cut off. Instead, the count goes negative and the editor is invalid until the text is shortened.

Validation

Link to This Section

Add the required attribute to make the editor mandatory. A blank editor is invalid, and so is one whose text is shorter than minlength or longer than maxlength. Form submission is blocked until the editor is valid.

Submit Reset
<form id="rich-text-editor__form" class="wa-stack">
  <wa-rich-text-editor
    name="feedback"
    label="Feedback"
    hint="At least 20 characters."
    toolbar="bold italic | bullet-list ordered-list | link"
    required
    minlength="20"
    maxlength="500"
    with-count
  ></wa-rich-text-editor>
  <div class="wa-cluster">
    <wa-button type="submit" variant="brand">Submit</wa-button>
    <wa-button type="reset">Reset</wa-button>
  </div>
</form>

<script type="module">
  const form = document.getElementById('rich-text-editor__form');

  form.addEventListener('submit', event => {
    event.preventDefault();
    alert(`Submitted HTML:\n\n${new FormData(form).get('feedback')}`);
  });
</script>

Input Behavior

Link to This Section

Like <wa-textarea>, the editor passes the spellcheck, autocapitalize, autocorrect, enterkeyhint, and inputmode attributes to its editable content.

Rename fetchUsr to fetchUserById and drop the cachd flag.

<wa-rich-text-editor label="Commit Message" spellcheck="false" autocorrect="off" autocapitalize="off">
  <p>Rename fetchUsr to fetchUserById and drop the cachd flag.</p>
</wa-rich-text-editor>

Markdown

Link to This Section

Set the format attribute to markdown to read and write the value as Markdown. This applies to the value property and attribute, content between the tags, and form submissions.

The editor uses GitHub Flavored Markdown, plus ==text== for highlights. Indentation shared by every line between the tags is ignored, so the Markdown can be indented to match the surrounding HTML.

## What's New - **Faster sync** for large libraries - Export to ==CSV== and ~~XML~~ JSON Read the [full changelog](https://example.com/changelog).
<div id="rich-text-editor__markdown" class="wa-stack">
  <wa-rich-text-editor label="Release Notes" format="markdown">
    ## What's New

    - **Faster sync** for large libraries
    - Export to ==CSV== and ~~XML~~ JSON

    Read the [full changelog](https://example.com/changelog).
  </wa-rich-text-editor>
  <wa-textarea label="Markdown" rows="8" readonly></wa-textarea>
</div>

<script type="module">
  const container = document.getElementById('rich-text-editor__markdown');
  const editor = container.querySelector('wa-rich-text-editor');
  const output = container.querySelector('wa-textarea');

  function showValue() {
    output.value = editor.value;
  }

  editor.addEventListener('input', showValue);
  await customElements.whenDefined('wa-rich-text-editor');
  await editor.updateComplete;
  showValue();
</script>

Changing format re-expresses the same content in the new format. Commands, insertHtml(), textValue, and selectedText work the same in both formats.

Markdown can't express everything the editor can, so what it can't express is kept as inline HTML. If your Markdown renderer strips HTML, avoid that content:

Content Written as To avoid it
Colors, alignment, underline, subscript, superscript, and embeds Inline HTML List them in disabled-features
Links with a target or rel Inline HTML Leave link-target and link-rel unset
Mentions Inline HTML Return suggestion items without a value
Captions and resized images Inline HTML Disable image
Tables with merged cells, no header row, resized columns, or more than one paragraph or a list in a cell Inline HTML Disable table
Highlights ==text== Disable highlight, since many renderers don't support this syntax

Some Markdown is changed as it's read, so loading and saving a document can rewrite it:

  • A code block's language is dropped, so ```js is written back as a plain fence.
  • Task lists lose their checkboxes and become plain list items.
  • Footnotes aren't supported. [^1] is kept as text.
  • Headings outside heading-levels move to the nearest allowed level.
  • Raw HTML follows the rules for HTML: unsupported elements are dropped and their text is kept.

Customizing the Toolbar

Link to This Section

Three attributes control what users can do. Use the first one that fits your needs:

To Use
Show, hide, or rearrange buttons toolbar. Removing a button doesn't remove its feature: shortcuts, pasted content, and the initial value can still bring it in
Remove a feature entirely, including from pasted content and the value disabled-features
Limit which heading levels are available heading-levels

Set the toolbar attribute to a space-separated list of tools. A | draws a divider and starts a new group. Unknown tokens are ignored, and so are tools for disabled features. The default toolbar is:

block | bold italic format-menu | link image table | lists | undo redo
Token Tool
block Menu of paragraph, heading, and code block formats, with an icon that shows the current format
bold Bold
italic Italic
underline Underline
strikethrough Strikethrough
highlight Default highlight
code Inline code
subscript Subscript
superscript Superscript
color Text and highlight color menu (see Colors)
format-menu Menu of the text formats that don't have their own button, plus clear formatting
align Menu of start, center, end, and justify alignment
lists Menu of bulleted list, numbered list, indent, and outdent
bullet-list Bulleted list
ordered-list Numbered list
indent Indent the list item
outdent Outdent the list item
blockquote Blockquote
code-block Code block
link Link editor (see Links)
image Image editor (see Images)
embed Embed editor (see Embeds)
table Table size picker, or the table options menu when the caret is in a table (see Tables)
horizontal-rule Horizontal rule
clear-formatting Remove all text formatting from the selection
paste-plain-text Toggle that strips formatting from pasted content while it's on
undo Undo
redo Redo
actions Where the actions slot goes (see Custom Toolbar Buttons)

A | draws a divider and starts a new group. This toolbar keeps the text formats together and separates the link from the history tools.

The groups in this toolbar follow the style guide.

<wa-rich-text-editor label="Comment" toolbar="bold italic underline | link | undo redo">
  <p>
    The <strong>groups</strong> in this toolbar follow the <a href="https://example.com/style-guide">style guide</a>.
  </p>
</wa-rich-text-editor>

Menus never repeat a tool that has its own button. Adding underline and strikethrough to the second toolbar drops them from its format-menu. A menu left with one item becomes a plain button, and an empty menu disappears.

Open the menu to see every text format without a button of its own.

Underline and strikethrough have left this menu.

<div class="wa-stack">
  <wa-rich-text-editor label="Format menu" toolbar="bold italic format-menu">
    <p>Open the menu to see every text format without a button of its own.</p>
  </wa-rich-text-editor>
  <wa-rich-text-editor
    label="Format menu with underline and strikethrough buttons"
    toolbar="bold italic underline strikethrough format-menu"
  >
    <p>Underline and strikethrough have left this menu.</p>
  </wa-rich-text-editor>
</div>

This example puts every tool in the toolbar. By default, a toolbar that's wider than the editor scrolls horizontally. This one wraps instead, because flex-wrap: wrap is set on the toolbar part. Move the caret through the content to see the tools reflect the format at the caret.

Field Notes

The north trail reopens Friday. Bring water; the pump at mile 3 is working offline.

  • Permits are issued at the ranger station.
  • Dogs stay leashed past the ridge.
<wa-rich-text-editor
  id="rich-text-editor__every-tool"
  label="Article"
  toolbar="block | bold italic underline strikethrough highlight code subscript superscript | color clear-formatting | align bullet-list ordered-list indent outdent | blockquote code-block horizontal-rule | link image embed table | paste-plain-text | undo redo"
>
  <h2>Field Notes</h2>
  <p>
    The <strong>north trail</strong> reopens <em>Friday</em>. Bring <mark>water</mark>; the pump at mile 3 is
    <s>working</s> offline.
  </p>
  <ul>
    <li>Permits are issued at the <a href="https://example.com/permits">ranger station</a>.</li>
    <li>Dogs stay leashed past the ridge.</li>
  </ul>
</wa-rich-text-editor>

<style>
  #rich-text-editor__every-tool::part(toolbar) {
    flex-wrap: wrap;
  }
</style>

To remove the toolbar, set toolbar to an empty string. Keyboard shortcuts and Markdown-style typing still work.

<wa-rich-text-editor
  label="Quick Note"
  toolbar=""
  placeholder="Type # and a space to start a heading"
></wa-rich-text-editor>

Toolbar Placement

Link to This Section

Use the toolbar-placement attribute to move the toolbar below the content. With a few tools, a short --content-min-height, and the other features disabled, it makes a compact composer for chat and comment boxes. Enter starts a new paragraph; there's no shortcut to submit.

<wa-rich-text-editor
  label="Message"
  placeholder="Write a message"
  toolbar-placement="bottom"
  toolbar="bold italic | link"
  disabled-features="image embed table color align"
  style="--content-min-height: 3em"
></wa-rich-text-editor>

Custom Toolbar Buttons

Link to This Section

Place buttons in the actions slot to add them to the toolbar, after the built-in tools or wherever the actions token appears. Pressing them keeps the selection in the content, and they join the toolbar's arrow-key navigation.

Thanks for reaching out.

<wa-rich-text-editor
  id="rich-text-editor__actions"
  label="Support Reply"
  toolbar="bold italic link | actions | undo redo"
>
  <p>Thanks for reaching out.</p>
  <wa-button slot="actions" appearance="plain" size="s" data-action="ticket">
    <wa-icon name="ticket" label="Insert ticket link"></wa-icon>
  </wa-button>
  <wa-button slot="actions" appearance="plain" size="s" data-action="date">
    <wa-icon name="calendar-day" label="Insert today's date"></wa-icon>
  </wa-button>
</wa-rich-text-editor>

<script type="module">
  const editor = document.getElementById('rich-text-editor__actions');

  editor.addEventListener('click', event => {
    const action = event.target.closest('[data-action]')?.dataset.action;

    if (action === 'ticket') {
      editor.insertHtml('<a href="https://example.com/tickets/4821">ticket #4821</a>');
    } else if (action === 'date') {
      editor.insertText(new Date().toLocaleDateString());
    }
  });
</script>

To keep a custom button in step with the selection, such as disabling it until there's a link to remove, listen for the selectionchange event as shown in Controlling the Editor with JavaScript.

Icon Library

Link to This Section

The editor's icons come from the system icon library. Use the icon-library attribute to draw them from another registered library, such as default. Icon names follow Font Awesome.

<script src="bundle.js" data-fa-kit-code="abc123"></script>

<wa-rich-text-editor label="Notes" icon-library="default"></wa-rich-text-editor>
The default library needs a Font Awesome Pro Kit code.
The heading, code block, link, and image alignment icons are Pro icons. Provide a Kit code to load them.

Disabling Features

Link to This Section

The toolbar attribute only controls which buttons appear. Content can still arrive through pasting, shortcuts, and the initial value. To remove a feature entirely, list it in the disabled-features attribute.

A disabled feature's tools, shortcuts, and commands are turned off, and it's stripped from the value and from pasted content. Formatting is removed, but the text is kept.

You'll usually want to trim the toolbar to match. This comment box offers a few formats and keeps everything else out of the value, whether it's typed, pasted, or set.

<wa-rich-text-editor
  label="Comment"
  toolbar="bold italic underline strikethrough | bullet-list ordered-list | link"
  disabled-features="image embed table color align"
></wa-rich-text-editor>

Blocks from disabled features are replaced by their content.

The table and code block below are reduced to paragraphs because tables and code blocks are disabled.

Plan Seats
Team 10
npm install
<wa-rich-text-editor label="Support Reply" disabled-features="table image embed code-block">
  <p>The table and code block below are reduced to paragraphs because tables and code blocks are disabled.</p>
  <table>
    <tr>
      <th>Plan</th>
      <th>Seats</th>
    </tr>
    <tr>
      <td>Team</td>
      <td>10</td>
    </tr>
  </table>
  <pre><code>npm install</code></pre>
</wa-rich-text-editor>

The available tokens are bold, italic, underline, strikethrough, highlight, code, subscript, superscript, color, link, image, embed, table, blockquote, code-block, bullet-list, ordered-list, horizontal-rule, and align. Use lists to disable both list types. align covers text alignment only, since image alignment belongs to image. Headings are controlled by heading-levels.

Heading Levels

Link to This Section

Use the heading-levels attribute to choose which heading levels users can apply, as space-separated numbers from 1 to 6. The default is 1 2 3. Set it to an empty string to remove headings.

Headings at other levels in the initial value, pasted content, and insertHtml() are converted to the nearest allowed level, so saving the content rewrites them. The keyboard shortcuts and the # typing shortcut only cover the allowed levels.

Pages often reserve <h1> for their own title, so content that's displayed within a page usually starts at level 2.

This heading becomes level 2

Open the block menu to see the available levels.

<wa-rich-text-editor label="Section" heading-levels="2 3">
  <h1>This heading becomes level 2</h1>
  <p>Open the block menu to see the available levels.</p>
</wa-rich-text-editor>

Links

Link to This Section

The link tool and Ctrl + K open the link editor. If nothing is selected, the link applies to the word at the caret. Click a link to change or remove it, or Ctrl/Cmd + click to open it in a new tab. Pasting a URL over selected text links the text.

Use the link-target attribute to set the target of new links. Setting it to _blank also adds rel="noopener noreferrer". Use the link-rel attribute to set a different rel, such as nofollow ugc for content from untrusted users. Both attributes only apply to links created in the editor. Links in pasted content and the initial value keep their own target and rel, so enforce them on the server if they matter to you.

URLs that start with https://, http://, or www. are linked automatically when you type a space or press Enter after them. Trailing punctuation stays outside the link, and pressing Backspace immediately afterward undoes it. Add the without-autolink attribute to turn this off.

Select this text and press the link button to try it.

<wa-rich-text-editor label="Resources" link-target="_blank" toolbar="bold italic | link | undo redo">
  <p>Select this text and press the link button to try it.</p>
</wa-rich-text-editor>

Unsafe URL schemes are rejected, but you should still sanitize on the server.

Images

Link to This Section

The image tool opens the image editor, which asks for a URL, alt text, and an optional caption. Click an image, or press Enter on a selected one, to change or remove it. Pasting an image URL inserts the image.

Click the image button and enter the URL of an image.

<wa-rich-text-editor label="Post" toolbar="block | bold italic | image | undo redo">
  <p>Click the image button and enter the URL of an image.</p>
</wa-rich-text-editor>

Alt text is optional in the image editor. An image saved without it gets alt="", which screen readers treat as decorative, so encourage users to describe images that carry meaning.

To resize an image, select it and drag its handle. The width snaps to the image's natural width, half of it (the display size of a high-density screenshot), and the editor's full width. Hold Shift, Ctrl, or Cmd to resize freely, or press Shift + Left / Right.

Resizing sets the image's width attribute. Turning on the caption wraps the image in a <figure> with a <figcaption>. Wherever you display the content, use the rules in Displaying the Content to keep resized images inside their container.

Aligning Images

Link to This Section

The image editor's alignment options put the image on its own line at the start, center, or end, or wrap text around it. Choose "In line with text" to return the image to the flow of text.

Wrapped text runs to the end of the image's paragraph, and the next paragraph starts below the image. For a figure, it runs through the paragraph that follows.

Downloading kits Click the image and choose an alignment. Wrapped images float beside the text of their paragraph, so long paragraphs flow around them while the next paragraph starts below.

This paragraph starts below the image.

<wa-rich-text-editor label="Story" toolbar="bold italic | image | undo redo">
  <p>
    <img
      src="/assets/images/kits.jpg"
      alt="Downloading kits"
      width="160"
      style="float: inline-start; margin-inline-end: 1em"
    />
    Click the image and choose an alignment. Wrapped images float beside the text of their paragraph, so long paragraphs
    flow around them while the next paragraph starts below.
  </p>
  <p>This paragraph starts below the image.</p>
</wa-rich-text-editor>

Alignment is saved as inline styles, so it survives most sanitizers and displays the same outside the editor. Legacy align attributes and physical floats and margins are converted as content is read.

Alignment Element Style
start <img> display: block; margin-inline: 0 auto
<figure> margin-inline: 0 auto; width: fit-content
center <img> display: block; margin-inline: auto
<figure> margin-inline: auto; width: fit-content
end <img> display: block; margin-inline: auto 0
<figure> margin-inline: auto 0; width: fit-content
wrap-start <img> float: inline-start; margin-inline-end: 1em
<figure> float: inline-start; margin-inline: 0 1em
wrap-end <img> float: inline-end; margin-inline-start: 1em
<figure> float: inline-end; margin-inline: 1em 0

Wherever you display the content, use the rules in Displaying the Content to contain floats and start the next paragraph below them.

Uploading Images

Link to This Section

By default, pasted and dropped image files are embedded as data: URLs. That works without a server, but it makes the value about a third larger than the file, so it's best for small images and prototypes.

To store images elsewhere, set the imageProvider property to an async function. The image tool calls it with no arguments instead of opening the image editor, and pasted or dropped files are passed to it as a File to upload. The function should resolve with the image's URL, an object with src and alt, or null to cancel.

<wa-rich-text-editor
  id="rich-text-editor__image-provider"
  label="Post"
  hint="Choose an image with the image button, or paste or drop one."
  toolbar="bold italic | image | undo redo"
></wa-rich-text-editor>

<script type="module">
  const editor = document.getElementById('rich-text-editor__image-provider');

  // Opens the browser's file picker and resolves with the chosen file, or null when it's canceled
  function chooseImage() {
    return new Promise(resolve => {
      const input = Object.assign(document.createElement('input'), { type: 'file', accept: 'image/*' });
      input.addEventListener('change', () => resolve(input.files[0] ?? null));
      input.addEventListener('cancel', () => resolve(null));
      input.click();
    });
  }

  editor.imageProvider = async file => {
    file ??= await chooseImage();
    if (!file) return null;

    // Upload the file to your server here and return its permanent URL. An object URL only lasts until the page closes.
    return URL.createObjectURL(file);
  };
</script>

An imageProvider skips the image editor and its alt text field, so resolve with { src, alt } when you know the alt text. Users can still click the image to add or change it.

Embeds

Link to This Section

Embeds add videos, audio, and other pages in an <iframe>. The embed tool isn't in the default toolbar, so add it to the toolbar attribute if you want to offer it. Its editor accepts a URL or <iframe> code, plus a title for assistive technologies.

Click the embed button and paste a video link or embed code.

<wa-rich-text-editor label="Lesson" toolbar="block | bold italic | link embed | undo redo">
  <p>Click the embed button and paste a video link or embed code.</p>
</wa-rich-text-editor>

Links to YouTube, Vimeo, Spotify, SoundCloud, Dailymotion, Loom, and Wistia are converted to player URLs, and other http: and https: URLs are embedded as-is. From embed code, only the src, title, width, and height are kept, so embeds are always serialized the same way:

<iframe src="…" title="…" width="…" height="…" allowfullscreen loading="lazy"></iframe>

Embed code that builds its player with a <script> isn't supported. Embeds without a width and height fill the content's width at 16:9. Selected embeds resize like images.

To accept other URLs or restrict which ones are allowed, set the embedProvider property to an async function that receives what the user entered. The function should resolve with a URL, an object with src, title, width, and height, null to reject the input, or undefined to use the built-in conversion.

const editor = document.querySelector('wa-rich-text-editor');

editor.embedProvider = async input => {
  // Convert links to your own video pages into player URLs
  const match = input.trim().match(/^https:\/\/videos\.example\.com\/watch\/([\w-]+)$/);
  if (match) {
    return { src: `https://videos.example.com/player/${match[1]}`, title: 'Video' };
  }

  // Reject other links to your domain, and let the built-in conversion handle everything else
  return input.includes('example.com') ? null : undefined;
};

An embedProvider only filters what's entered in the embed editor. Pasted iframes and crafted submissions skip it, so allow only trusted hosts on the server.

Tables

Link to This Section

Outside a table, the table tool opens a size picker. Choose a size with the pointer or arrow keys, then click or press Enter. Tables with more than one row start with a header row.

Inside a table, the tool becomes the table options menu, and an options button appears at the start of the current cell. The menu has Row, Column, and Cell submenus for adding, moving, deleting, and merging, plus commands to select or delete the whole table.

Plan Seats Support
Starter 3 Email
Team 25 Priority
<wa-rich-text-editor label="Pricing Notes" toolbar="bold italic | table | undo redo">
  <table>
    <tr>
      <th>Plan</th>
      <th>Seats</th>
      <th>Support</th>
    </tr>
    <tr>
      <td>Starter</td>
      <td>3</td>
      <td>Email</td>
    </tr>
    <tr>
      <td>Team</td>
      <td>25</td>
      <td>Priority</td>
    </tr>
  </table>
</wa-rich-text-editor>

Press Tab and Shift + Tab to move between cells. Tab in the last cell adds a row. In left-to-right content, drag a column border to resize it. Widths are saved on each cell as data-colwidth, which only applies inside the editor.

If tables are enabled, keep the table tool in custom toolbars. Its menu is the most direct way to reach table options from the keyboard.

Colors

Link to This Section

The color tool opens a menu with a row of text colors and a row of highlight colors. The first swatch in each row removes that kind of color. It isn't in the default toolbar, so add it to the toolbar attribute if you want to offer it.

Each row offers eight colors that adapt to light and dark color schemes. Use the text-colors and highlight-colors attributes to set your own as semicolon-separated lists of CSS colors. Set either one to an empty string to remove its row. This example uses a common eight-color palette with solid text colors and translucent highlights.

The redesign is on track for Friday, but the icon audit is blocked. Sign-off is due Thursday, and the launch checklist is ready for review.

<wa-rich-text-editor
  label="Status Update"
  toolbar="bold italic color | undo redo"
  text-colors="rgb(220 38 38); rgb(234 88 12); rgb(202 138 4); rgb(22 163 74); rgb(37 99 235); rgb(147 51 234); rgb(219 39 119); rgb(75 85 99)"
  highlight-colors="rgb(248 113 113 / 40%); rgb(251 146 60 / 40%); rgb(250 204 21 / 40%); rgb(74 222 128 / 40%); rgb(96 165 250 / 40%); rgb(192 132 252 / 40%); rgb(244 114 182 / 40%); rgb(156 163 175 / 40%)"
>
  <p>
    The redesign is <span style="color: rgb(22 163 74)">on track</span> for Friday, but the icon audit is
    <span style="color: rgb(220 38 38)">blocked</span>.
    <mark style="background-color: rgb(250 204 21 / 40%)">Sign-off is due Thursday</mark>, and the
    <mark style="background-color: rgb(96 165 250 / 40%)">launch checklist</mark> is ready for review.
  </p>
</wa-rich-text-editor>

Each swatch's accessible name defaults to its color value. To give swatches readable names, set the textColors or highlightColors property to an array of { color, label } objects.

Select some text, then choose a color. Hover a swatch to see its name.

<wa-rich-text-editor id="rich-text-editor__colors" label="Announcement" toolbar="bold italic color | undo redo">
  <p>Select some text, then choose a color. Hover a swatch to see its name.</p>
</wa-rich-text-editor>

<script type="module">
  const editor = document.getElementById('rich-text-editor__colors');
  const palette = [
    ['Red', '220 38 38', '248 113 113'],
    ['Orange', '234 88 12', '251 146 60'],
    ['Yellow', '202 138 4', '250 204 21'],
    ['Green', '22 163 74', '74 222 128'],
    ['Blue', '37 99 235', '96 165 250'],
    ['Purple', '147 51 234', '192 132 252'],
    ['Pink', '219 39 119', '244 114 182'],
    ['Gray', '75 85 99', '156 163 175'],
  ];

  editor.textColors = palette.map(([label, text]) => ({ color: `rgb(${text})`, label }));
  editor.highlightColors = palette.map(([label, , highlight]) => ({ color: `rgb(${highlight} / 40%)`, label }));
</script>

Colors are saved as inline styles, so they travel with the content:

<span style="color: rgb(37, 99, 235);">Text color</span>
<mark style="background-color: rgba(74, 222, 128, 0.4);">Highlight</mark>

Since the content can be displayed anywhere, choose colors that read well on any page.

  • Translucent highlights work on any background.
  • light-dark() only switches between its two colors on pages that set color-scheme. Many sanitizers, including most email clients, remove it entirely. Use plain colors for content that will be shown outside your site.
  • Avoid custom properties like var(--brand). They only work on pages that define them.

The highlight tool and the default yellow swatch produce a plain <mark>, so the page that displays the content decides how it looks.

Keyboard & Markdown Shortcuts

Link to This Section

The editor supports the following keyboard shortcuts. On macOS, use Cmd in place of Ctrl and Option in place of Alt. Shortcuts for disabled features and heading levels outside heading-levels are left out.

Shortcut Action
Ctrl + B Bold
Ctrl + I Italic
Ctrl + U Underline
Ctrl + Shift + X Strikethrough
Ctrl + E Inline code
Ctrl + K Open the link editor
Ctrl + Alt + 0 Paragraph
Ctrl + Alt + 1 to 6 Heading level 1 to 6
Ctrl + Shift + 7 Numbered list
Ctrl + Shift + 8 Bulleted list
Ctrl + Shift + B Blockquote
Shift + Enter or Ctrl + Enter Line break, or leave a code block
Tab / Shift + Tab Next or previous table cell, or indent or outdent a list item
Ctrl + Z Undo
Ctrl + Shift + Z or Ctrl + Y Redo (Ctrl + Y isn't available on macOS)
Backspace Right after a typing shortcut below, undoes it
Enter On a selected image or embed, opens its editor
Shift + Left / Right On a selected image or embed, resizes it
Escape Closes the open menu, editor, or suggestions

If your page has its own keyboard shortcuts, ignore keydown events where event.defaultPrevented is true. Otherwise, shortcuts like Ctrl + K will trigger both the editor and your page.

Typing these Markdown-style shortcuts at the start of a paragraph converts it. Highlights and typographic replacements work anywhere.

Type Result
# to ######, then a space Heading at the nearest allowed level. Only works up to the largest level in heading-levels
-, *, or +, then a space Bulleted list
1., then a space Numbered list starting at that number
>, then a space Blockquote
``` Code block
--- or ___ Horizontal rule
==text== Highlight
-- Em dash (—)
... Ellipsis (…)
" and ' Curly quotes

Add the without-smart-punctuation attribute to keep quotes, --, and ... as typed, which is useful for code or technical writing. Add the without-markdown-shortcuts attribute to turn off the other typing shortcuts. Keyboard shortcuts still work.

Smart punctuation Markdown shortcuts
<div class="wa-stack">
  <wa-rich-text-editor
    id="rich-text-editor__shortcuts"
    label="Release Notes"
    placeholder='Try typing "# Heading", "- item", "--", or "..."'
  ></wa-rich-text-editor>

  <div class="wa-cluster">
    <wa-switch id="rich-text-editor__smart-punctuation" checked>Smart punctuation</wa-switch>
    <wa-switch id="rich-text-editor__markdown-shortcuts" checked>Markdown shortcuts</wa-switch>
  </div>
</div>

<script type="module">
  const editor = document.getElementById('rich-text-editor__shortcuts');
  const smartPunctuation = document.getElementById('rich-text-editor__smart-punctuation');
  const markdownShortcuts = document.getElementById('rich-text-editor__markdown-shortcuts');

  smartPunctuation.addEventListener('change', () => {
    editor.withoutSmartPunctuation = !smartPunctuation.checked;
  });

  markdownShortcuts.addEventListener('change', () => {
    editor.withoutMarkdownShortcuts = !markdownShortcuts.checked;
  });
</script>

Suggestions

Link to This Section

Suggestions open a menu under the caret when the user types a trigger character, such as @ for mentions or # for tags. Set the suggestions property to an array of sources, each with a single-character trigger and a dataSource function that returns items for the text typed after the trigger.

Items with a value are inserted as mentions, which are serialized as <span data-mention="value">label</span> and edited as a single unit. Items without a value insert their label as plain text. The trigger and query are replaced, so if you want the trigger to appear, include it in the label. An optional description shows below the label.

<wa-rich-text-editor
  id="rich-text-editor__suggestions"
  label="Comment"
  hint="Type @ to mention a teammate or # to add a tag."
  toolbar="bold italic | link"
></wa-rich-text-editor>

<script type="module">
  const editor = document.getElementById('rich-text-editor__suggestions');

  const people = [
    { value: 'u-104', label: '@Avery Chen', description: 'Design' },
    { value: 'u-215', label: '@Jordan Patel', description: 'Engineering' },
    { value: 'u-322', label: '@Maya Okafor', description: 'Product' },
    { value: 'u-418', label: '@Sam Rivera', description: 'Support' },
  ];

  const tags = ['accessibility', 'bug', 'design', 'docs', 'performance'];

  const matches = (text, query) => text.toLowerCase().includes(query.toLowerCase());

  editor.suggestions = [
    {
      trigger: '@',
      dataSource: ({ query }) => people.filter(person => matches(person.label, query)),
    },
    {
      trigger: '#',
      dataSource: ({ query }) => tags.filter(tag => matches(tag, query)).map(tag => ({ label: `#${tag}` })),
    },
  ];
</script>

The menu requests items after a short pause in typing. dataSource can be async and receives an AbortSignal that aborts when a newer request replaces it or the menu closes, so you can pass it straight to fetch():

editor.suggestions = [
  {
    trigger: '@',
    dataSource: async ({ query, signal }) => {
      const response = await fetch(`/api/people?q=${encodeURIComponent(query)}`, { signal });
      return response.json(); // [{ value: 'u-104', label: '@Avery Chen', description: 'Design' }, ...]
    },
  },
];

If dataSource rejects, the menu shows an error and the editor emits the wa-suggestions-error event. Its detail holds the error and the failed request, with its trigger and query. Requests replaced by newer ones aren't failures.

To customize how items look in the menu, add a formatter function to the source. Return an HTML string, a DOM node, or a Lit html template. Page styles don't reach the menu, so style the markup inline. This example shows an avatar beside each name.

<wa-rich-text-editor
  id="rich-text-editor__formatter"
  label="Comment"
  hint="Type @ to mention a teammate."
  toolbar="bold italic | link"
  data-wa-preload="wa-avatar"
></wa-rich-text-editor>

<script type="module">
  const editor = document.getElementById('rich-text-editor__formatter');

  const people = [
    { value: 'u-104', label: '@Avery Chen', initials: 'AC', role: 'Design' },
    { value: 'u-215', label: '@Jordan Patel', initials: 'JP', role: 'Engineering' },
    { value: 'u-322', label: '@Maya Okafor', initials: 'MO', role: 'Product' },
    { value: 'u-418', label: '@Sam Rivera', initials: 'SR', role: 'Support' },
  ];

  // Escapes values before they go into the HTML string
  const escapeHtml = text => String(text).replace(/[&<>"']/g, char => `&#${char.charCodeAt(0)};`);

  editor.suggestions = [
    {
      trigger: '@',
      dataSource: ({ query }) => people.filter(person => person.label.toLowerCase().includes(query.toLowerCase())),
      formatter: person => `
        <div style="display: flex; align-items: center; gap: 0.75em; line-height: var(--wa-line-height-condensed)">
          <wa-avatar initials="${escapeHtml(person.initials)}" style="--size: 2.25em; font-size: 0.875em"></wa-avatar>
          <div>
            <div style="font-weight: var(--wa-font-weight-semibold)">${escapeHtml(person.label)}</div>
            <div style="font-size: 0.875em">${escapeHtml(person.role)}</div>
          </div>
        </div>
      `,
    },
  ];
</script>

Escape values in formatter strings.
Strings are inserted as HTML, so an unescaped name from a user or your database can inject scripts. Lit templates escape values for you.

Formatter content renders in the editor's shadow DOM, where the autoloader can't see it. List the components your formatters use in a data-wa-preload attribute, as the example above does, or import them yourself.

You can style the menu with the suggestion-menu and suggestion-item parts. The highlighted item also exposes the suggestion-item-active part. Mentions are styled as chips inside the editor, but wherever you display the content, you'll need to style [data-mention] yourself, as shown in Displaying the Content.

Reacting to Changes

Link to This Section

The editor emits input when its content changes and change when focus leaves after a change. Read the HTML from the value property, or plain text from the textValue property, which separates blocks with line breaks. input also fires for runCommand(), insertHtml(), and insertText(), but not when you set value.

Edit this text to see the value change.


<div class="wa-stack">
  <wa-rich-text-editor
    id="rich-text-editor__watch"
    label="Draft"
    toolbar="block | bold italic | bullet-list | undo redo"
  >
    <p>Edit this text to see the value change.</p>
  </wa-rich-text-editor>
  <pre id="rich-text-editor__watch-output" style="white-space: pre-wrap; margin: 0"></pre>
</div>

<script type="module">
  const editor = document.getElementById('rich-text-editor__watch');
  const output = document.getElementById('rich-text-editor__watch-output');

  function showValue() {
    output.textContent = `value: ${editor.value}\n\ntextValue: ${editor.textValue}`;
  }

  editor.addEventListener('input', showValue);
  await customElements.whenDefined('wa-rich-text-editor');
  await editor.updateComplete;
  showValue();
</script>

In a framework, bind value as a property and listen for input.
In Vue, that's :value="draft" with @input="draft = $event.target.value".

Tracking Unsaved Changes

Link to This Section

The read-only dirty property is true when the value differs from the default value, and the editor matches :state(dirty) while it is. Differences in markup alone, such as text with or without a <p>, don't count. After saving, set defaultValue to the current value to mark the editor clean.

Edit this text, then save it.

Save All changes saved
<div class="wa-stack">
  <wa-rich-text-editor id="rich-text-editor__dirty" label="Notes" toolbar="bold italic | bullet-list | undo redo">
    <p>Edit this text, then save it.</p>
  </wa-rich-text-editor>
  <div class="wa-cluster">
    <wa-button id="rich-text-editor__dirty-save" size="s" disabled>Save</wa-button>
    <span id="rich-text-editor__dirty-status">All changes saved</span>
  </div>
</div>

<script type="module">
  const editor = document.getElementById('rich-text-editor__dirty');
  const save = document.getElementById('rich-text-editor__dirty-save');
  const status = document.getElementById('rich-text-editor__dirty-status');

  function showStatus() {
    save.disabled = !editor.dirty;
    status.textContent = editor.dirty ? 'Unsaved changes' : 'All changes saved';
  }

  editor.addEventListener('input', showStatus);
  save.addEventListener('click', () => {
    // Send editor.value to your server here, then mark the editor clean
    editor.defaultValue = editor.value;
    showStatus();
  });
</script>

Controlling the Editor with JavaScript

Link to This Section

Use the runCommand() method to format content the way the toolbar does. Pass a command name and, for some commands, an options object. It returns false when the command doesn't apply, such as when its feature is disabled or the editor is readonly.

Command Options Effect
bold, italic, underline, strikethrough, highlight, code, subscript, superscript Toggles the format
color color, highlight Sets the text color and highlight color. null removes a color, an omitted option keeps it, and highlight: true applies the default highlight
link href, target, rel Links the selection or the word at the caret. target and rel default to link-target and link-rel
unlink Removes the link at the caret or in the selection
paragraph Converts the selected blocks to paragraphs
heading level Converts the selected blocks to headings. heading-1 to heading-6 work without options
code-block Converts the selected blocks to a code block
blockquote Toggles a blockquote
align align Aligns the selected paragraphs and headings to start, center, end, or justify
bullet-list, ordered-list Toggles the list type
indent, outdent Indents or outdents the list item
image src, alt, title, caption, align Inserts an image, or updates the selected one. caption: true makes it a figure, and a string caption also sets its text. align is start, center, end, wrap-start, wrap-end, or null to clear it, and works without src on the selected image
embed src, title, width, height Inserts an embed, or updates the selected one. src goes through the built-in URL resolver only; embedProvider applies to the embed editor popover. width and height are in pixels and override the resolved size
table rows, columns Inserts a table, 3 by 3 by default
table-add-row-above, table-add-row-below, table-add-column-before, table-add-column-after Inserts a row or column next to the current cell
table-move-row-up, table-move-row-down, table-move-column-before, table-move-column-after Moves the current row or column
table-delete-row, table-delete-column, table-delete Deletes the current row, column, or table
table-merge-cells, table-split-cell Merges the selected cells, or splits a merged cell
table-toggle-header-row, table-toggle-header-column Toggles the header row or header column
table-select-cell, table-select Selects the current cell or the whole table
horizontal-rule Inserts a horizontal rule
clear-formatting Removes all text formatting from the selection
undo, redo Undoes or redoes the last edit
editor.runCommand('bold');
editor.runCommand('heading', { level: 2 });
editor.runCommand('link', { href: 'https://example.com', target: '_blank' });
editor.runCommand('color', { color: 'light-dark(#0053c0, #6eb3ff)', highlight: null });
editor.runCommand('table', { rows: 4, columns: 2 });
editor.runCommand('image', { align: 'wrap-start' });

Use the isActive() method to check what's applied at the selection. It accepts the text format names above, paragraph, heading-1 to heading-6, code-block, blockquote, bullet-list, ordered-list, link, image, embed, table, and color (any text or highlight color).

It also accepts align-start to align-justify, image-align- followed by an image alignment (such as image-align-wrap-start), table-header-row, and table-header-column.

The editor also has methods and properties for working with content and the selection:

Member Description
insertHtml(html) Replaces the selection with HTML. Markup the editor doesn't support is stripped
insertText(text) Replaces the selection with plain text
deleteSelection() Deletes the selected content
selectAll() Selects all of the content. Does nothing while the editor is disabled
undo(), redo() Undoes or redoes the last edit and returns whether there was one
canUndo, canRedo Whether there's an edit to undo or redo
selectedText The selected text
getSelection() The selection as { from, to, empty } document positions
focus(), blur() Moves focus to or away from the content
view The underlying ProseMirror EditorView, for advanced use. undefined until the editor renders

The editor emits selectionchange when the selection, or the formatting at it, changes. Use it to keep your own controls in sync. In this example, the buttons stay disabled until there's something for them to do.

Select text, then use the buttons below.

Visit the release page for details.

Heading 2 Insert Date Remove Link Undo Redo
<div class="wa-stack">
  <wa-rich-text-editor id="rich-text-editor__control" label="Changelog" toolbar="">
    <p>Select text, then use the buttons below.</p>
    <p>Visit <a href="https://example.com">the release page</a> for details.</p>
  </wa-rich-text-editor>
  <div class="wa-cluster">
    <wa-button id="rich-text-editor__control-heading" size="s">Heading 2</wa-button>
    <wa-button id="rich-text-editor__control-date" size="s">Insert Date</wa-button>
    <wa-button id="rich-text-editor__control-unlink" size="s" disabled>Remove Link</wa-button>
    <wa-button id="rich-text-editor__control-undo" size="s" disabled>Undo</wa-button>
    <wa-button id="rich-text-editor__control-redo" size="s" disabled>Redo</wa-button>
  </div>
</div>

<script type="module">
  const editor = document.getElementById('rich-text-editor__control');
  const button = name => document.getElementById(`rich-text-editor__control-${name}`);

  function run(action) {
    action();
    editor.focus();
  }

  button('heading').addEventListener('click', () => {
    run(() => editor.runCommand(editor.isActive('heading-2') ? 'paragraph' : 'heading-2'));
  });
  button('date').addEventListener('click', () => {
    run(() => editor.insertText(new Date().toLocaleDateString()));
  });
  button('unlink').addEventListener('click', () => run(() => editor.runCommand('unlink')));
  button('undo').addEventListener('click', () => run(() => editor.undo()));
  button('redo').addEventListener('click', () => run(() => editor.redo()));

  editor.addEventListener('selectionchange', () => {
    button('unlink').disabled = !editor.isActive('link');
    button('undo').disabled = !editor.canUndo;
    button('redo').disabled = !editor.canRedo;
  });
</script>

Styling the Editor

Link to This Section

Content renders in the editor's shadow DOM, so page styles can't reach it. Use the content part to style the editable region, such as its font or padding:

wa-rich-text-editor::part(content) {
  font-family: var(--wa-font-family-longform);
}

To style elements inside the content, adopt a stylesheet into the editor's shadow root and scope its selectors to the content part. These rules override the editor's own content styles:

Getting Started

Create a workspace, then invite your team.

Most teams are up and running in under ten minutes.

<wa-rich-text-editor id="rich-text-editor__styling" label="Article">
  <h2>Getting Started</h2>
  <p>Create a workspace, then invite your team.</p>
  <blockquote><p>Most teams are up and running in under ten minutes.</p></blockquote>
</wa-rich-text-editor>

<script type="module">
  const editor = document.getElementById('rich-text-editor__styling');
  await customElements.whenDefined('wa-rich-text-editor');

  const sheet = new CSSStyleSheet();
  sheet.replaceSync(`
    [part~='content'] h2 {
      color: var(--wa-color-brand-on-quiet);
    }

    [part~='content'] blockquote {
      font-style: italic;
    }
  `);

  editor.shadowRoot.adoptedStyleSheets = [...editor.shadowRoot.adoptedStyleSheets, sheet];
</script>

Use the --content-min-height and --content-max-height custom properties to control the height of the content. Taller content scrolls while the toolbar stays in view.

  • Added bulk editing for tasks.
  • Added keyboard shortcuts to the board view.
  • Improved search ranking for recent items.
  • Fixed a bug where due dates shifted across time zones.
  • Fixed a bug where archived projects appeared in search.
  • Removed the legacy export format.
<wa-rich-text-editor
  label="Changelog"
  toolbar="bold italic | bullet-list | undo redo"
  style="--content-min-height: 4em; --content-max-height: 10em"
>
  <ul>
    <li>Added bulk editing for tasks.</li>
    <li>Added keyboard shortcuts to the board view.</li>
    <li>Improved search ranking for recent items.</li>
    <li>Fixed a bug where due dates shifted across time zones.</li>
    <li>Fixed a bug where archived projects appeared in search.</li>
    <li>Removed the legacy export format.</li>
  </ul>
</wa-rich-text-editor>

What's Not Included

Link to This Section

The following features aren't currently supported:

  • Task lists, footnotes, and a language on code blocks. See Markdown for how they are read.
  • Find and replace, a full-screen mode, and an emoji picker.
  • Dragging blocks to reorder them. Only images, figures, and embeds can be dragged.
  • Collaborative editing.
  • A shortcut to submit. Enter starts a paragraph, and Shift + Enter and Ctrl + Enter insert a line break.

Accessibility Considerations

Link to This Section

The content region is a multi-line textbox, labeled by the editor's label and described by its hint and character count. It exposes the required, readonly, disabled, and invalid states. Always give the editor a label with the label attribute or slot.

The toolbar is a single tab stop. Use the arrow keys to move between tools, including those in the actions slot, and Home and End to jump to the first and last. Toggle buttons report whether their format is active.

Tooltips show each tool's name and shortcut, and Escape dismisses them. They're visual only, since each tool has its own accessible name. Give icon-only custom buttons a name with the label attribute on their <wa-icon>.

In lists and tables, Tab indents list items and moves between cells. Elsewhere, it moves focus out of the editor as usual.

Menus and editors opened from the toolbar take focus and return it to the content when they close. Escape closes them without changes. Screen readers announce swatches by their label, so make sure custom swatches have one. The table size picker works with the arrow keys and announces its size.

The editor announces changes that aren't otherwise visible, such as a removed link, an inserted table, available suggestions, and the remaining character count. While suggestions are open, focus stays in the content and the highlighted one is conveyed with aria-activedescendant.

The image editor asks for alt text, and the embed editor asks for a title, which names the <iframe>. Encourage users to fill them in. An imageProvider skips the image editor, so resolve with alt text when you have it. Users can still click the image to add it.

API

Link to This Section

Importing

Link to This Section

If you're using the autoloader or a hosted project, components load on demand — no manual import needed. To cherry-pick a component manually, use one of the following snippets.

CDN npm Self-Hosted React

Import this component directly from the CDN:

import 'https://ka-f.webawesome.com/[email protected]/components/rich-text-editor/rich-text-editor.js';

After installing Web Awesome via npm, import this component:

import '@awesome.me/webawesome/dist/components/rich-text-editor/rich-text-editor.js';

If you're self-hosting Web Awesome, import this component from your server:

import './webawesome/dist/components/rich-text-editor/rich-text-editor.js';

To import this component for React 18 or below, use the following code:

import WaRichTextEditor from '@awesome.me/webawesome/dist/react/rich-text-editor/index.js';

Slots

Link to This Section

Learn more about using slots.

Name Description
(default) Initial HTML content, like the text inside a <textarea>. It's read once when the editor connects and becomes the default value. Ignored when the value attribute is set.
actions Custom buttons placed in the toolbar, after the built-in tools or wherever the actions token appears in toolbar.
hint Text that describes how to use the editor. Alternatively, you can use the hint attribute.
label The editor's label. Alternatively, you can use the label attribute.

Attributes & Properties

Link to This Section

Learn more about attributes and properties.

Name Description Reflects
appearance
appearance
The editor's visual appearance.
Type 'filled' | 'outlined' | 'filled-outlined'
Default 'outlined'
autocapitalize
autocapitalize
Controls whether and how text input is automatically capitalized as it is entered by the user.
Type 'off' | 'none' | 'on' | 'sentences' | 'words' | 'characters'
autocorrect
autocorrect
Indicates whether the browser's autocorrect feature is on or off. When set as an attribute, use "off" or "on". When set as a property, use true or false.
Type boolean
canRedo
Whether there's an undone edit to redo.
Type boolean
canUndo
Whether there's an edit to undo.
Type boolean
defaultValue
value
The default value of the form control, used when resetting the form. Content placed between the tags is used when the value attribute isn't set.
Type string
dirty
Whether the value differs from defaultValue. Both are compared as the editor serializes them, so markup that only differs in form doesn't count. Set defaultValue to the current value to mark the editor clean, e.g. after saving.
Type boolean
disabled
disabled
Disables the editor.
Type boolean
Default false
disabledFeatures
disabled-features
Space-separated features to remove from the editor entirely: their tools, shortcuts, and input rules are left out, and they're stripped from the value and from pasted content. Use lists to remove both list types.
Type string
Default ''
embedProvider
Resolves what users enter in the embed editor (a URL or <iframe> code) to an embed. Resolve with a URL or { src, title?, width?, height? }, null to reject the input, or undefined to use the built-in resolver, which understands iframe code and common video and audio services.
Type  ((input: string) => Promise<RichTextEditorEmbed | null | undefined>) | undefined
enterkeyhint
enterkeyhint
Used to customize the label or icon of the Enter key on virtual keyboards.
Type 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send'
form
By default, form controls are associated with the nearest containing <form> element. This attribute allows you to place the form control outside of a form and associate it with the form that has this id. The form must be in the same document or shadow root for this to work.
Type HTMLFormElement | null
format
format
The format of the editor's value. With markdown, the value property, the value attribute, content placed between the tags, and the value submitted with forms are all Markdown instead of HTML. Markdown can't express everything the editor can, so those parts of the content are kept as inline HTML; see the docs for the list.
Type 'html' | 'markdown'
Default 'html'
headingLevels
heading-levels
The heading levels users can apply, as space-separated numbers from 1 to 6. Other headings are converted to the nearest allowed level. Set it to an empty string to remove headings.
Type string
Default '1 2 3'
highlightColors
highlight-colors
The highlight colors offered in the color menu, in the same format as text-colors. Defaults to translucent tints of the default palette. Set it to an empty string to remove the row.
Type string | (string | RichTextEditorSwatch)[] | undefined
hint
hint
The editor's hint. If you need to display HTML, use the hint slot instead.
Type string
Default ''
iconLibrary
icon-library
The icon library used for the toolbar and popover icons. Defaults to system. Set it to default (or any registered library) to draw the icons from that library instead, e.g. to use Font Awesome Pro icons with a kit code.
Type string
Default 'system'
imageProvider
Provides images to the editor. When set, the image tool calls it instead of asking for a URL, and pasted or dropped image files are passed to it (e.g. to upload them). Resolve with a URL or { src, alt }, or null to cancel. Without it, pasted and dropped image files are embedded as data URLs.
Type  ((file?: File) => Promise<RichTextEditorImage | null | undefined>) | undefined
inputmode
inputmode
Tells the browser what type of data will be entered by the user, allowing it to display the appropriate virtual keyboard on supportive devices.
Type 'none' | 'text' | 'decimal' | 'numeric' | 'tel' | 'search' | 'email' | 'url'
label
label
The editor's label. If you need to display HTML, use the label slot instead.
Type string
Default ''
linkRel
link-rel
The rel given to links created in the editor. Overrides the default rel that _blank adds.
Type string
Default ''
linkTarget
link-target
The target given to links created in the editor. _blank also sets rel="noopener noreferrer".
Type string
Default ''
maxlength
maxlength
The maximum number of characters of text, not counting markup, that will be considered valid. Typing beyond it isn't blocked; the editor becomes invalid instead.
Type number
minlength
minlength
The minimum number of characters of text, not counting markup, that will be considered valid.
Type number
name
name
The name of the editor, submitted as a name/value pair with form data.
Type string | null
Default null
placeholder
placeholder
Placeholder text to show when the editor is empty.
Type string
Default ''
readonly
readonly
Makes the content read-only. It can still be focused, selected, and copied, but the toolbar is disabled.
Type boolean
Default false
required
required
Makes the editor a required field. A blank editor is invalid.
Type boolean
Default false
selectedText
The selected text.
Type string
size
size
The editor's size. The long-form values small, medium, and large are deprecated; use s, m, and l instead.
Type 'xs' | 's' | 'm' | 'l' | 'xl' | 'small' | 'medium' | 'large'
Default 'm'
spellcheck
spellcheck
Enables spell checking on the editor.
Type boolean
Default true
suggestions
Typeahead sources. Typing a source's trigger character opens a menu of its suggestions under the caret.
Type RichTextEditorSuggestionSource[]
Default []
textColors
text-colors
The text colors offered in the color menu, as a semicolon-separated list of CSS colors or an array of colors or { color, label } objects. Defaults to a palette that adapts to light and dark color schemes. Set it to an empty string to remove the row.
Type string | (string | RichTextEditorSwatch)[] | undefined
textValue
The content as plain text, with block boundaries as line breaks.
Type string
toolbar
toolbar
The tools to show in the toolbar, as space-separated tokens. A | draws a divider between groups, and actions positions the actions slot. Set it to an empty string to remove the toolbar.
Type string
Default 'block | bold italic format-menu | link image table | lists | undo redo'
toolbarPlacement
toolbar-placement
Where the toolbar sits.
Type 'top' | 'bottom'
Default 'top'
validationTarget
Where native constraint validation messages are anchored.
Type undefined | HTMLElement
validators
Validators are static because they have observedAttributes, essentially attributes to "watch" for changes. Whenever these attributes change, we want to be notified and update the validator.
Type Validator[]
Default []
value
The editor's content as an HTML string, or a Markdown string when format is markdown. Submitted as a name/value pair with form data.
Type string
view
The underlying ProseMirror EditorView, for advanced use. The editor is built on ProseMirror. undefined until the editor renders.
Type EditorView | undefined
withCount
with-count
Shows a character count below the editor. When maxlength is set, shows remaining characters instead.
Type boolean
Default false
withHint
with-hint
Only required for SSR. Set to true if you're slotting in a hint element so the server-rendered markup includes the hint before the component hydrates on the client.
Type boolean
Default false
withLabel
with-label
Only required for SSR. Set to true if you're slotting in a label element so the server-rendered markup includes the label before the component hydrates on the client.
Type boolean
Default false
withoutAutolink
without-autolink
Turns off linking URLs as they're typed.
Type boolean
Default false
withoutMarkdownShortcuts
without-markdown-shortcuts
Turns off the Markdown-style shortcuts that format content as users type, such as # for a heading, - for a list, and ==text== for a highlight. Keyboard shortcuts still work.
Type boolean
Default false
withoutSmartPunctuation
without-smart-punctuation
Turns off smart quotes and the replacement of ... and -- with an ellipsis and an em dash as users type.
Type boolean
Default false

Methods

Link to This Section

Learn more about methods.

Name Description Arguments
blur() Removes focus from the editor.
deleteSelection() Deletes the selected content.
focus() Sets focus on the editor's content. options: FocusOptions
formStateRestoreCallback() Called when the browser is trying to restore element’s state to state in which case reason is "restore", or when the browser is trying to fulfill autofill on behalf of user in which case reason is "autocomplete". In the case of "restore", state is a string, File, or FormData object previously set as the second argument to setFormValue. state: string | File | FormData | null, reason: 'autocomplete' | 'restore'
getSelection() Gets the selection as ProseMirror document positions.
insertHtml() Inserts HTML at the selection, replacing it. Markup the editor doesn't support is stripped. html: string
insertText() Inserts plain text at the selection, replacing it. text: string
isActive() Whether a format or context is active at the selection, such as bold, heading-2, bullet-list, align-center, link, image, image-align-wrap-start, or table. name: string
redo() Redoes the last undone edit. Returns whether there was one to redo.
resetValidity() Reset validity is a way of removing manual custom errors and native validation.
runCommand() Runs a command by name, such as bold, heading (with { level }), link (with { href }), or table-add-row-below. Returns whether it applied. Unknown commands, commands that can't apply at the selection, and commands for disabled features return false. The embed command resolves src with the built-in URL resolver only, and takes an optional width and height in pixels; embedProvider applies to the embed editor popover. name: string, options: RichTextEditorCommandOptions
selectAll() Selects all of the content. Does nothing while the editor is disabled.
setCustomValidity() Do not use this when creating a "Validator". This is intended for end users of components. We track manually defined custom errors so we don't clear them on accident in our validators. message: string
undo() Undoes the last edit. Returns whether there was one to undo.

Events

Link to This Section

Learn more about events.

Name Description
blur Emitted when the editor loses focus. Moving focus between the content and the toolbar doesn't emit it.
change Emitted when the user commits a change, i.e. when focus leaves the editor after its content changed.
focus Emitted when the editor gains focus. Moving focus between the content and the toolbar doesn't emit it.
input Emitted when the content changes.
selectionchange Emitted when the selection or the formatting at the selection changes. Use it to keep custom toolbar buttons in sync with isActive().
type
wa-invalid Emitted when the form control has been checked for validity and its constraints aren't satisfied.
wa-suggestions-error Emitted when a suggestion source's dataSource rejects. The event detail contains { error: unknown, request: { trigger: string, query: string } }.

CSS Custom Properties

Link to This Section

Learn more about CSS custom properties.

Name Description
--content-max-height
The maximum height of the editable region. Taller content scrolls.
Default none
--content-min-height
The minimum height of the editable region.
Default 8em
--hide-duration
The hide duration of menus and popovers.
Default var(--wa-transition-fast)
--shadow-color
The base color of the shadows that show when toolbar tools are hidden off an edge.
Default var(--wa-form-control-background-color)
--shadow-size
The size of those shadows.
Default 2em
--show-duration
The show duration of menus and popovers.
Default var(--wa-transition-fast)

Custom States

Link to This Section

Learn more about custom states.

Name Description CSS selector
blank The editor has no content. :state(blank)
dirty The value differs from the default value. :state(dirty)

CSS Parts

Link to This Section

Learn more about CSS parts.

Name Description CSS selector
color-menu The text and highlight color popover. ::part(color-menu)
content The editable region. ::part(content)
count The character count, rendered when the with-count attribute is present. ::part(count)
embed-popover The embed editor popover. ::part(embed-popover)
form-control-label The label. ::part(form-control-label)
hint The hint's wrapper. ::part(hint)
image-popover The image editor popover. ::part(image-popover)
link-popover The link editor popover. ::part(link-popover)
rich-text-editor The box that wraps the toolbar and the content. ::part(rich-text-editor)
suggestion-item Each suggestion in the listbox. ::part(suggestion-item)
suggestion-item-active The highlighted suggestion. ::part(suggestion-item-active)
suggestion-menu The suggestions listbox. ::part(suggestion-menu)
table-menu The table options button shown beside the current table cell. ::part(table-menu)
table-picker The table size picker popover. ::part(table-picker)
toolbar The toolbar. Set flex-wrap: wrap to wrap tools instead of scrolling them. ::part(toolbar)
toolbar-button Each built-in toolbar button, including menu triggers. ::part(toolbar-button)
toolbar-divider The dividers between toolbar groups. ::part(toolbar-divider)

Dependencies

Link to This Section

This component automatically imports the following elements. Sub-dependencies, if any exist, will also be included in this list.

  • <wa-button>
  • <wa-checkbox>
  • <wa-divider>
  • <wa-dropdown>
  • <wa-dropdown-item>
  • <wa-icon>
  • <wa-input>
  • <wa-popover>
  • <wa-popup>
  • <wa-spinner>
  • <wa-textarea>
  • <wa-tooltip>
Need a hand? Report a bug Ask for help
Go Make Something Awesome
Version 3.15.0 © Fonticons, Inc.
  • Terms
  • Privacy
  • Refunds
  • Core License
  • Pro License

Quick Links

  • Components
  • CSS Utilities
  • Theming
  • Using with AI
  • Changelog
  • Help & Support

Recent Searches

    D'oh! No results for “”

    Suggest on GitHub Ask on Discord
    Navigate Select
    Close Esc

    We Have Cookies…

    We use cookies to make webawesome.com work better by storing limited information about your usage.

    We value your privacy, so we won't use them for evil or ask you to join the dark side.

    Customize
    Necessary Only Accept All
    Strictly Necessary
    Required to make the site function correctly — cannot be turned off
    Functionality Analytics
    Cancel Confirm Cookie Choices