Rich Text Editor

web component

Edit formatted HTML content with headings, lists, links, tables and images

Rich Text Editor lets users compose formatted HTML content with headings, lists, links, tables and images. It provides a formatting toolbar, a selection bubble, a / command menu, Markdown shortcuts and interactive table handles.

<sa-rich-text-editor name="Bio" label="Guide bio" description="Shown on the guide's public profile."
                     placeholder="Tell travellers about this guide…"
                     value="<h2>Meet Amara</h2><p>Amara has led <strong>small-group walking tours</strong> through Cape Town for twelve years. She grew up in Bo-Kaap and knows every <em>spice merchant</em> by name.</p><ul><li><p>Table Mountain sunrise hikes</p></li><li><p>Bo-Kaap food walks</p></li></ul>" />

Usage

<sa-rich-text-editor> is a self-closing tag:

<sa-rich-text-editor asp-for="..." />

Bind asp-for to a string property, or set name and value directly. Use rows to set the initial height in lines (8 by default). The editor expands with its content and scrolls once it reaches 32rem.

Web component

<sa-rich-text-editor> renders StellarAdmin.UI's <ui-sa-rich-text-editor> custom element, built with ui-sdk. The Tag Helper loads its own script automatically. See JavaScript & Interactivity for how StellarAdmin.UI loads and initializes custom elements.

The editor's module (rich-text-editor.js, about 140 KB compressed plus shared ui-sdk chunks) loads only on pages that render an editor, downloads once when multiple editors appear on the same page, and loads on arrival for editors swapped in by htmx.

Examples

Model binding

When bound with asp-for, the editor reads its label, description and placeholder from the property's [Display] attribute.

<div class="w-full max-w-2xl">
    <sa-rich-text-editor asp-for="Highlights"/>
</div>

Image uploads

Set upload-url to enable pasting, dropping or inserting images from the toolbar or the / menu. Images upload immediately with a progress overlay, and selected images can be resized with their corner handle. When upload-url is omitted, the image button and slash command are hidden and pasted image files are ignored.

<sa-rich-text-editor name="Itinerary" label="Itinerary" upload-url="/ImageUpload?handler=Upload" max-file-size="2097152"
                     description="Paste, drop or insert photos of each stop. Up to 2 MB each."
                     value="<h3>Day 1: Lisbon</h3><p>Arrive in Lisbon and take the tram up to Alfama for dinner.</p>" />

The demo above simulates uploads in the browser rather than sending files to a server, so selected files never leave your machine.

The editor posts each image to upload-url as a multipart/form-data POST request with the file in the file field. The form's antiforgery token is sent in both the __RequestVerificationToken form field and the RequestVerificationToken header.

Return a 200 OK JSON response containing the URL where the stored image can be loaded:

{ "url": "https://cdn.voyager.example/itineraries/lisbon-4f2a.jpg" }

When an upload fails, return an error status code with a JSON object containing an error message. The editor removes the failed image and displays the message beneath the editing area:

{ "error": "Unsupported image format." }

By default, the browser checks accept (image/jpeg,image/png,image/webp,image/gif,image/avif) and max-file-size (5242880 bytes, or 5 MB) before uploading.

Browser file checks can be bypassed. Always validate the uploaded file type and size on the server before storing it.

Read only

Set readonly="true" to display formatted content without allowing edits. A read-only editor hides the toolbar, remains focusable and submits its HTML value with the form.

<sa-rich-text-editor name="Terms" label="Booking terms" readonly="true" rows="4"
                     value="<p>Bookings can be cancelled free of charge up to <strong>14 days</strong> before departure.</p>" />

Disabled

Set disabled="true" to disable the editor and its toolbar. Like a disabled <textarea>, a disabled editor cannot receive focus and does not submit its value.

<sa-rich-text-editor name="ArchivedTerms" label="Archived booking terms" disabled="true" rows="4"
                     value="<p>Bookings could be cancelled free of charge up to <strong>7 days</strong> before departure.</p>" />

HTML output and sanitization

The editor keeps a child <textarea> synchronized with its HTML content and dispatches an input event on the <textarea> whenever the document changes. Lists serialize as standard <ul> and <ol> elements, and an empty document submits an empty string. Plain text values without HTML tags are converted into <p> elements separated by blank lines when loaded. Until the editor's script loads, or if JavaScript is unavailable, the <textarea> is displayed in place of the editor so the form remains usable.

Always sanitize submitted HTML on the server before storing or rendering it. Although the editor outputs safe markup, incoming requests can carry scripts or event handlers. Allow only the elements and attributes the editor produces: p, h1 to h3, strong, em, u, s, code, pre, blockquote, ul, ol, li, a (href), img (src, width, height), table, tbody, tr, th and td (colspan, rowspan, data-colwidth), hr and br. Restrict href and src values to http, https, mailto or relative URLs using a library such as HtmlSanitizer.

To render saved HTML with the same typography, lists, code blocks and table styles used inside the editor, wrap the sanitized markup in an element with the sa-rich-text class:

<div class="sa-rich-text">@Html.Raw(sanitizedHtml)</div>

JavaScript API

Give <sa-rich-text-editor> an id and look up the rendered <ui-sa-rich-text-editor> element with document.getElementById() to read or replace its HTML, control focus, open the link popover or image picker, or listen for changes. Wait for await customElements.whenDefined("ui-sa-rich-text-editor") before reading properties or calling api right after page load.

The example below reads the current HTML, listens for valuechange, updates the content programmatically and moves focus into the editor:

await customElements.whenDefined("ui-sa-rich-text-editor");

const editor = document.getElementById("guide-bio");

// Read the current serialized HTML
console.log(editor.value);

// Listen for document changes (cancelable)
editor.addEventListener("valuechange", (event) => {
  console.log(event.detail.value, event.detail.reason);

  // Call event.preventDefault() to reject the change and restore the previous document
});

// Replace the editor's content programmatically
editor.api.setValue("<p>Welcome to <strong>Lisbon</strong>.</p>");

// Move focus into the editing area
editor.api.focus();

Properties and methods

The table below lists the properties and api methods available on the <ui-sa-rich-text-editor> element:

MemberDescription
valueLive HTML string of the editor's document (empty string when blank). Assigning a string updates the editor and child <textarea> through api.setValue(), converting plain text without tags into paragraphs.
api.getValue()Returns the current serialized HTML string.
api.setValue(value, options?)Replaces the document with the given HTML or plain text string and dispatches a cancelable valuechange event. Returns true if updated or already equal, or false if disabled, read-only or canceled.
api.focus()Moves focus into the editing area (or focuses the content box when read-only). Returns false when disabled.
api.openLinkPopover()Opens the link popover anchored to the toolbar's Link control. Returns false when disabled or read-only.
api.pickImage()Opens the image file picker when upload-url is configured. Returns false when uploads are disabled or the editor is disabled or read-only.

Events

The table below lists the custom event dispatched by <ui-sa-rich-text-editor>:

EventBubblesCancelableDetail
valuechangeNoYes{ value, reason, event, source, cancel }. Fired whenever the serialized HTML changes via typing or pasting ("input"), toolbar controls ("toolbar"), the / menu ("slash-menu"), table handle actions ("table-action"), applying or removing a link ("link"), api.setValue() or assigning value ("imperative"), or resetting the surrounding form ("reset"). Calling event.preventDefault() or event.detail.cancel() rejects the change and restores the previous document and <textarea> value.

Accessibility

The editing area has role="textbox" and aria-multiline="true", labeled by the field label and described by the field description and validation error. Activating the field label moves focus into the editing area. Upload errors are announced in a polite live region beneath the editing area.

The toolbar uses the WAI-ARIA toolbar pattern with a single Tab stop. Formatting toggles report their state with aria-pressed, controls expose their keyboard shortcuts through aria-keyshortcuts and platform-formatted tooltips (displaying ⌘, ⇧ and ⌥ on Apple platforms), and the Link control opens a popover that focuses the URL input.

Use the following keys while focus is inside the toolbar:

KeyAction
← / →Move focus between toolbar controls.
Home / EndMove focus to the first or last toolbar control.
↓ (on the Text style trigger)Open the block-type menu.
Enter / SpaceActivate the focused button, toggle or menu trigger.
EscClose an open menu or link popover and return focus to its trigger.

Part classes

Pass a RichTextEditorClassNames instance from the StellarAdmin.UI namespace using class-names. Each property accepts an optional string of space-separated CSS classes, which are added to the part's existing classes.

The table below maps each RichTextEditorClassNames property to its target element:

PropertyTarget
RootThe generated field wrapper, when the control renders an implicit field.
LabelThe generated field label, when rendered.
DescriptionThe generated help text, when rendered.
ErrorThe generated validation message element, when rendered.
ContentThe generated container around the label and supporting text in a horizontal implicit field.
ControlThe <ui-sa-rich-text-editor> root element.
EditorThe editing surface element.
ToolbarThe formatting toolbar element.

Root, Label, Description, Error and Content are inherited from FieldClassNames, documented under Field part classes.

API Reference

<sa-rich-text-editor>

Renders a <ui-sa-rich-text-editor> custom element containing the formatting toolbar, editing surface, child <textarea> for form submission, link popover, slash menu, table handles, selection bubble and module script.

Prop

Type

<sa-rich-text-editor> throws an InvalidOperationException if rows or max-file-size is less than or equal to zero.

On this page