Skip to content
IzzyBlazor

Enter all results ↑ ↓ move Esc close

RichTextEditor

Since 0.1.0-alpha.22
Lets the user write formatted text, saved as sanitized HTML.

Formatted text with label, hint and errors: headings, lists, quotes, code, bold, italic and the rest of what RichTextSanitizer allows. Its value is that HTML, sanitized on the server every time it binds, with no styles or classes, so it shows the same anywhere (show it with RichText).

In a form

A RichTextEditor's value is HTML: headings, lists, quotes, code, bold, italic and the like, with no styles or classes. It's sanitized on the server whenever it binds, so the model only ever holds safe HTML. To show it, use RichText.

Static

Preview

Text style

The office is closed on Friday, November 27 for the building's electrical work.

What to do

  • Work from home, or from the Riverside office.
  • Take your laptop home on Thursday.

Questions go to Facilities.

Insert image

What the image shows, for people who can't see it.

Insert table

Shown on the team page.

Code

Usage.razor
@using System.ComponentModel.DataAnnotations

@* A team announcement: the editor's value is sanitized HTML, shown back with RichText. *@
<Form Model="Model" FormName="rich-text-editor-usage" OnValidSubmit="Post">
    <TextField @bind-Value="Model!.Title" />
    <RichTextEditor @bind-Value="Model.Body" Hint="Shown on the team page." />
    <FormActions>
        <Button Submit>Post</Button>
    </FormActions>
</Form>
@if (_posted is not null)
{
    <Card Title="@_posted.Value.Title">
        <RichText Html="@_posted.Value.Body" />
    </Card>
}

@code {
    [SupplyParameterFromForm(FormName = "rich-text-editor-usage")]
    private TeamPost? Model { get; set; }

    private (string? Title, string? Body)? _posted;

    protected override void OnInitialized() => Model ??= new();

    private void Post() => _posted = (Model!.Title, Model.Body);
}

Static: IzzyBlazor's script makes the text editable and keeps the field's value current as the user types, so it posts with the form.

Add this example to a page with the izzy CLI:

bash
izzy add component RichTextEditor --at <file>:<line>

Topics

  • Toolbar and shortcuts: Choose the tools in the toolbar. Shortcuts work for every format, shown or not.
  • Security: What the editor's value can hold, where it's sanitized, and how to show it safely.
  • Markdown shortcuts: Typed Markdown becomes formats as you type, for people who write it out of habit.
  • Links: Add, change and remove links, and open them in a new tab.
  • Images: Add images by address, upload, paste or drop, each with a description.
  • Tables: Insert tables, add and delete rows and columns, and give them a header row.
  • Task lists: Lists of tasks with checkboxes, ticked as they're done.
  • Code blocks: Mark a code block's language; RichText shows it highlighted.
  • Styling the content: The text uses Prose's styles, so it looks the same in the editor and where it's shown.

Everything it formats

The default tools format headings and paragraphs, with bold, italic, underline, strikethrough and inline code. They also make numbered and bulleted lists nested in each other, quotes, code blocks and horizontal lines.

Static

Preview

Text style

Your first week

Welcome to the team. This guide covers what to set up before Friday, who to ask, and what to skip for now. The old wiki is still the source of truth being retired, so use this guide instead.

Accounts

  1. Sign in to your laptop with the password from IT.
  2. Set up two-step sign-in:
    • Install the authenticator app.
    • Scan the code on the security page.
  3. Join the #team-platform channel.

If something doesn't work

Restart once, then ask in #it-help with a screenshot.

Nobody expects you to ship anything in your first week. Ask questions.

Your development setup

Clone the main repository and run the setup script:

git clone https://example.com/platform.git
cd platform
./setup.sh

Questions about this guide go to your onboarding buddy.

Insert image

What the image shows, for people who can't see it.

Insert table

Code

Formats.razor
@* Every format the editor makes, as one onboarding guide. *@
<RichTextEditor Grow @bind-Value="_guide" Label="Onboarding guide" Rows="12" />

@code {
    private string? _guide =
        """
        <h1>Your first week</h1>
        <p>Welcome to the team. This guide covers what to set up before <strong>Friday</strong>, who to ask, and what to <em>skip for now</em>. The old wiki is <s>still the source of truth</s> being retired, so <u>use this guide</u> instead.</p>
        <h2>Accounts</h2>
        <ol>
          <li>Sign in to your laptop with the password from IT.</li>
          <li>Set up two-step sign-in:
            <ul>
              <li>Install the authenticator app.</li>
              <li>Scan the code on the security page.</li>
            </ul>
          </li>
          <li>Join the <code>#team-platform</code> channel.</li>
        </ol>
        <h3>If something doesn't work</h3>
        <p>Restart once, then ask in <code>#it-help</code> with a screenshot.</p>
        <blockquote>Nobody expects you to ship anything in your first week. Ask questions.</blockquote>
        <h2>Your development setup</h2>
        <p>Clone the main repository and run the setup script:</p>
        <pre><code>git clone https://example.com/platform.git
        cd platform
        ./setup.sh</code></pre>
        <hr>
        <p>Questions about this guide go to your onboarding buddy.</p>
        """;
}

The text-style menu offers normal text and headings 1 to 5. Quote and code block are tools of their own.

When the text shows under a page's own heading 1, set TopHeading to 2, and the menu starts there (see Styling the content).

Layout tools

For pages people lay out, such as newsletters and articles, set Tools to RichTextTools.Extended. It adds alignment, subscript and superscript, text color and highlight, sizes, and fonts from Fonts.

Static

Preview

Text style
Font
Size
Text color
Highlight

The Riverside quarterly

Spring issue

Our building now runs on solar power, cutting CO2 emissions by a third.1

The roof garden opens on April 12. Bring your own gloves.

1. Compared with the same quarter last year.

Insert image

What the image shows, for people who can't see it.

Insert table

Code

Extended.razor
@* A newsletter: the extended tools for a centered title, a colored callout, a highlight and
   a footnote mark, with the publication's own fonts. *@
<RichTextEditor Grow @bind-Value="_newsletter" Label="Newsletter" Rows="10" TopHeading="2"
                Tools="RichTextTools.Extended" Fonts="fonts" />

@code {
    private static readonly string[] fonts = ["Georgia, serif", "ui-monospace, monospace"];

    private string? _newsletter =
        """
        <h2 class="ib-align-center">The Riverside quarterly</h2>
        <p class="ib-align-center"><span class="ib-size-sm ib-color-gray">Spring issue</span></p>
        <p><span style="font-family: Georgia, serif">Our building now runs on solar power, cutting CO<sub>2</sub> emissions by a third.</span><sup>1</sup></p>
        <p><span class="ib-color-green">The roof garden opens on April 12.</span> Bring <span class="ib-highlight-yellow">your own gloves</span>.</p>
        <p><span class="ib-size-sm">1. Compared with the same quarter last year.</span></p>
        """;
}

The colors come from a palette that reads in light and dark themes. Sizes come in steps that scale with the text around them, or as fixed sizes from FontSizes.

The value stores them as the library's own classes, plus a font from your list, so it still carries no free styles. RichText shows them when it has the same Fonts.

Custom colors

To allow any color, such as a brand's, set CustomColors. The text color and highlight menus then end with "Custom…", which opens a color panel.

Static

Preview

Text style
Size
Text color
Highlight

Northwind summer meetup

Thursday, June 18, at the harbor office

Talks on the new warehouse system, then dinner on the terrace. Seats are limited to 60, so sign up by June 1.

Insert image

What the image shows, for people who can't see it.

Insert table

As RichText shows it

Northwind summer meetup

Thursday, June 18, at the harbor office

Talks on the new warehouse system, then dinner on the terrace. Seats are limited to 60, so sign up by June 1.

Code

CustomColors.razor
@* An event flyer in the company's brand colors: CustomColors adds "Custom…" to the color menus,
   and RichText keeps those colors with the same option. The colors are on the heading: a color a
   person picks is the same in light and dark, and at a heading's size these two pass in both. *@
<Stack Gap="6" Grow>
    <RichTextEditor @bind-Value="_flyer" Label="Event flyer" Rows="6" Tools="RichTextTools.Extended" CustomColors />
    @* A labeled line, not a card: RichText draws no box of its own. *@
    <Divider Label="As RichText shows it" />
    <RichText Html="@_flyer" CustomColors />
</Stack>

@code {
    private string? _flyer =
        """
        <h2 class="ib-align-center"><span style="color: #0e7490">Northwind</span> <span style="color: #ea580c">summer meetup</span></h2>
        <p class="ib-align-center">Thursday, June 18, at the harbor office</p>
        <p>Talks on the new warehouse system, then dinner on the terrace. <strong>Seats are limited to 60</strong>, so sign up by June 1.</p>
        """;
}

The color is stored as a style with six hex digits. The sanitizer keeps that style only with the option, so set CustomColors on RichText too.

The option is off by default because a color chosen in a light theme can be unreadable in a dark one. The palette's colors avoid that.

A short comment

For short notes and comments, set Tools to RichTextTools.Basic: bold, italic, links and the two lists. Rows sets the height the text starts at, and Placeholder the prompt in it while it's empty.

Static

Preview

Code

Comment.razor
@* A comment box: four tools, a few lines, a prompt. *@
<RichTextEditor @bind-Value="_comment" Label="Comment" Tools="RichTextTools.Basic" Rows="3"
                Placeholder="Add a comment" MaxWidth="32.Rem" Grow />

@code {
    private string? _comment;
}

Limiting the length

To limit the text, set MaxLength; it counts the characters readers see, not the HTML around them, and is checked on the server. To show the count under the field, set ShowCount. Don't use [StringLength] on the property: it would count the HTML.

Static

Preview

A 1.7 litre kettle that boils in under two minutes and keeps water warm for an hour.

  • Lid that doesn't drip
  • Off when lifted from the base
134 / 300

Code

Length.razor
@using System.ComponentModel.DataAnnotations

@* A product description with a limit on its text: the count counts what readers see, not the HTML. *@
<Form Model="Model" FormName="rich-text-editor-length">
    <RichTextEditor @bind-Value="Model!.Description" Tools="RichTextTools.Basic" Rows="4" MaxLength="300" ShowCount />
    <FormActions>
        <Button Submit>Save</Button>
    </FormActions>
</Form>

@code {
    [SupplyParameterFromForm(FormName = "rich-text-editor-length")]
    private Product? Model { get; set; }

    protected override void OnInitialized() => Model ??= new();
}

Static: IzzyBlazor's script keeps the count current as the user types and marks it once it passes the limit.

Read-only and disabled

A read-only editor has no toolbar; the text can be selected and still posts. A disabled one doesn't post.

Static

Preview

Exports fail for reports with more than 10,000 rows. Fixed in 2.4.1.

Exports fail for reports with more than 10,000 rows. Fixed in 2.4.1.

Code

States.razor
@* A ticket's description: read-only once the ticket is closed. *@
<Stack Gap="4" Grow>
    <RichTextEditor @bind-Value="_closed" Label="Description" ReadOnly Rows="3" />
    <RichTextEditor @bind-Value="_archived" Label="Description" Disabled Rows="3" />
</Stack>

@code {
    private string? _closed = "<p>Exports fail for reports with more than <strong>10,000 rows</strong>. Fixed in 2.4.1.</p>";
    private string? _archived = "<p>Exports fail for reports with more than <strong>10,000 rows</strong>. Fixed in 2.4.1.</p>";
}

Details

The page renders the formatted text before any script runs, and a text box beside it, hidden with script, holds the HTML: the script keeps it current as you type, so the field posts in a plain form, and on an interactive page Value changes when you leave the field. The look is Prose's, so what you edit looks like what RichText shows; ContentClass puts your own class on the text for rules of your own.

Mode support

What works in each mode, RichTextEditor
FeatureStaticInteractive
Label, hint and errors from the modelYesYes
Posts in a plain form; sanitized on the serverYesYes
Toolbar, shortcuts and pasteYesYes

Static: static server-side rendering, with no circuit and no WebAssembly. Interactive: Server, WebAssembly or Auto.

Without JavaScript

Every page starts as plain HTML: before IzzyBlazor's script loads on a static page, while an interactive page prerenders, and with JavaScript off. With JavaScript off, it's a text box holding the HTML, which still posts and is sanitized.

Accessibility

  • The text is a textbox with aria-multiline, named by the label and described by the hint and errors, as other fields are.
  • The toolbar is named "Formatting", with one tab stop and arrow keys between its tools. Alt+F10 moves from the text to the toolbar, and Escape back. Toggles say whether the selection has their format (aria-pressed), and each lists its shortcut (aria-keyshortcuts, and the tooltip).
  • Tab leaves the text: it never types a tab, so the keyboard can't get stuck in it. In a table it moves between cells, and from the last one out of the editor.
  • Tables have a header row by default, its cells column headers (scope="col").
  • A task's checkbox is named by the task's text, and says whether it's done. Ctrl+Enter ticks it from the text, without the mouse.
  • The link and image tools open modal dialogs, named by their titles ("Add link", "Edit image"); Escape or Cancel closes them and puts focus back in the text, with its selection.
  • The image dialog asks for a description (alternative text) or for the image to be marked decorative; it opens on its own after an image is pasted or dropped. Its two sources are tabs (arrow keys move between them).
  • With ShowCount, the count ("120 / 2000") is part of the text's description; it isn't announced as it changes.
  • With JavaScript off, it's a textarea of the HTML with the field's label.

Keyboard navigation

In the text

RichTextEditor keys, In the text
Press this keyTo do this
Ctrl+B or Ctrl+I or Ctrl+UBold, italic, underline
Ctrl+Shift+XStrikethrough
Ctrl+= or Ctrl+Shift+=Subscript, superscript
Ctrl+Shift+L or Ctrl+Shift+E or Ctrl+Shift+RAlign start, center, end
Ctrl+EInline code
Ctrl+KAdd or change a link
Ctrl+Shift+8 or Ctrl+Shift+7 or Ctrl+Shift+9Bulleted list, numbered list, task list
Ctrl+EnterTick or untick the task at the caret
Ctrl+] or Ctrl+[Indent or outdent a list item
Ctrl+Alt+0Paragraph
Ctrl+Alt+1 to Ctrl+Alt+6Heading 1 to 6, from TopHeading; again for a paragraph
Ctrl+ZUndo
Ctrl+Y or Ctrl+Shift+ZRedo
Ctrl+Shift+VPaste as plain text
## or - or 1. or > or three backticks at the start of a line or then SpaceHeading, list, quote, code block
[ ] or [x] at the start of a line or list item or then SpaceA task, not done or done
**text** or *text* or `text`Bold, italic, inline code
--- then EnterHorizontal line
Tab or Shift+TabIn a table, the next or previous cell; Tab in its last cell leaves the editor
Alt+F10Move to the toolbar

In the toolbar

RichTextEditor keys, In the toolbar
Press this keyTo do this
Left or RightMove to the control before or after, wrapping (reversed on right-to-left pages)
Home or EndGo to the first or last control
Down or UpOn a menu's button, open the menu at its first or last item
EscapeBack to the text

Parameters

RichTextEditor parameters
PropTypeDefault
ToolsThe tools in the toolbar.RichTextToolsRichTextTools.Default
RowsThe height of the text, in lines, before it grows.int6
PlaceholderExample text shown when empty.string?
ReadOnlyMakes the field read-only: the text can be selected, not changed, and it still posts.boolfalse
ContentClassA class on the text, for your own rules on what's in it, such as .article h2.string?
FontSizeThe text's font size, on Prose's scale: 14, 16 or 18px, with the gaps between paragraphs to match.ProseSizeProseSize.Md
MarkdownShortcutsTurns typed Markdown into formats as you type: ## a heading, - and 1. lists, > a quote, three backticks a code block, **bold**, *italic* and code.booltrue
TopHeadingThe highest heading level, 1 to 6.int1
FontsThe fonts the Font tool offers, each a CSS font-family value such as Georgia, serif; the first name in each is its label.IReadOnlyList<string>?
FontSizesFixed text sizes for the Size tool, such as 12px or 14pt, in place of its steps (Smaller to Largest), which scale with the text around them.IReadOnlyList<string>?
CodeLanguagesThe languages a code block can be marked as, each a name such as csharp, written in the value as the code's class (language-csharp), which RichText highlights and Prism or highlight.js read too.IReadOnlyList<string>?computed
ImageUploadUrlWhere the image tool sends a chosen, pasted or dropped image: an endpoint of your app that takes a multipart POST with the image in a file field (and the form's antiforgery token, when it has one: a .NET 11 app without UseAntiforgery checks the origin instead), stores it, and answers with its URL, as text or as JSON { "url": "…" }.string?
AllowDataImagesImages chosen, pasted or dropped with no ImageUploadUrl are embedded in the value as data: URLs (PNG, JPEG, GIF, WebP or AVIF, never SVG).boolfalse
CustomColorsThe text color and highlight menus end with "Custom…", which opens a color panel for any color, written as a style with six hex digits.boolfalse
MaxImageSizeThe largest image, in bytes, that can be uploaded or embedded.long2000000
WrapToolbarThe toolbar wraps onto more rows (the default), filling each; false keeps it one row, and what doesn't fit moves into a "…" menu at its end.booltrue
MaxLengthThe most characters of text, not counting the HTML around it.int?
ShowCountShows "n / max" under the field.boolfalse
ToolbarContentTools of your own at the end of the toolbar, such as a ToolbarButton whose OnClick calls InsertHtmlAsync.RenderFragment?
@bind-ValueThe value, bound with @bind-Value.string?
DisplayNameThe field's name in validation messages from the input itself, such as a value that can't be parsed.string?

See also

  • RichText: displays HTML from an editor or a CMS safely in the page.
  • RichTextSanitizer
  • TextArea: lets the user enter several lines of text, and can grow and count them.
  • Form: posts its fields on static pages and validates them live on interactive pages.

Connection lost

Rejoining the server…