# Blazor Rich Text Editor

URL: https://flexcoreui.com/demo/rich-text-editor  
Section: Components  
Controls: EditorControl, FormatControl, EditorLiteControl  
Keywords: rich text editor, HTML editor, WYSIWYG editor, document editor, block editor

A Blazor rich text editor for long documents, with headings, images and page breaks, its own toolbar, and a lighter editor for notes.

## Documentation

### Editor

| Name | Type | Default | Description |
|---|---|---|---|
| EditorId | string | $"fx-editor-{Guid.NewGuid():N}" | DOM id of the editable element. The script finds the editor by this id, so it must be unique on the page; an empty value throws ArgumentException. |
| Blocks | IReadOnlyList<EditorBlock> | Array.Empty<EditorBlock>() | Starting content. Written into the editor after the first render, and again whenever a different list arrives while AutoPush is on; handing back the list OnBlocksChanged delivered does not rewrite it. An empty list gives one empty paragraph. |
| AutoPush | bool | true | When false, a new Blocks list is not written in; call PushAsync instead. |
| Paginate | bool | false | Lays the text out as fixed-size page cards (fx-paged on the editor, a div.fx-page per card) that the script measures and fills, splitting long paragraphs between words; a blank card and a New page button follow the last one. The script re-paginates while the user types and when the caret moves to another page after an edit. Switching the parameter keeps the current text. |
| PagedCssClass | string? | null | Extra class on the editor in paged mode. Set --fx-page-w, --fx-page-h, --fx-page-pad and --fx-page-bg under it to size the cards; without them a card is 5.5in by 8.5in. |
| PageWidth | EditorPageWidth | EditorPageWidth.Normal | Maximum width of the text: Narrow 640px, Normal 820px and Wide 1040px, centered; Full has no limit. Rendered as the class fx-pw-narrow, fx-pw-normal and so on. |
| FontFamily | string | "Merriweather" | Base font, written as font-family: 'FontFamily', Georgia, serif, so give one family name. The control loads no web fonts. |
| FontSizePx | int | 18 | Base font size in pixels. |
| LineHeight | double | 1.7 | Base line height, unitless. |
| CssClass | string? | null | Added to the editable element. |
| ReadOnly | bool | false | Renders contenteditable="false" and aria-readonly="true" and blocks input; the formatting, undo, redo and replace methods then do nothing. |
| SpellCheck | bool | true | Sets spellcheck on the editable element. |
| AriaLabel | string | "Document editor" | Accessible name of the editable element, which has role="textbox". |
| ShowToolbar | bool | false | Draws the control's own ToolbarControl above the text: Undo, Redo, Bold, Italic, Underline, Align left, Align center and Find / replace. Undo and Redo stay disabled unless EnableHistory is on. |
| EnableHistory | bool | false | Turns on the control's undo and redo: a snapshot after each change, with typing of one kind in one place within 750 ms merged into one step; Ctrl+Z, Ctrl+Y and Ctrl+Shift+Z (or ⌘); UndoAsync and RedoAsync. Leave it off when the host keeps its own history. |
| HistoryLimit | int | 100 | Most undo steps, and most redo steps, kept. Below 1 throws ArgumentOutOfRangeException. |
| HistoryChanged | EventCallback<EditorHistoryState> |  | Raised when CanUndo, CanRedo, UndoCount or RedoCount changes, including the reset after PushAsync. |
| OnBlocksChanged | EventCallback<IReadOnlyList<EditorBlock>> |  | Raised after each change in the editor (typing, a formatting command that changed the blocks, undo, redo, replace) with the whole document read back as blocks. On Blazor Server the document arrives as one SignalR message, so under the default 32 KB limit a long document stops syncing with no error on the page (only the browser console shows the dropped connection); raise HubOptions.MaximumReceiveMessageSize for long documents. |
| OnSelectionChanged | EventCallback<EditorSelectionInfo?> |  | Raised 10 ms after a mouse-up inside the editor with the selected text, its block id and its position relative to the editor's nearest positioned ancestor, or null when nothing is selected. Selecting with the keyboard does not raise it. |

### Methods

| Name | Type | Description |
|---|---|---|
| PushAsync(IReadOnlyList<EditorBlock>? blocks = null) | Task | Replaces the content with blocks, or with Blocks when none are given, and clears the search results, the undo history and the dirty flag. |
| ReadBlocksAsync() | Task<IReadOnlyList<EditorBlock>> | The document as blocks. Inline markup is cut down to b, i, u, s, strong, em, br and spans carrying color, font-family, font-size or font-weight (a style value containing a double quote is dropped), and Html is set to the same text. A paragraph split across pages comes back as one block. |
| IsDirtyAsync() | Task<bool> | True after any change since the last push; undoing back to the pushed text makes it false again. Also true when the check itself fails. |
| GetSelectionAsync() | Task<EditorSelectionInfo?> | The selected text, trimmed, with its block id and position; null when the selection is empty or outside the editor. |
| SelectAllAsync() | Task | Selects all of the editor's content. |
| ClearSelectionAsync() | Task | Clears the page's selection and focuses the editor. |
| ExecFormatCommandAsync(string command) | Task | Runs a browser editing command (bold, italic, underline, strikeThrough) on the selection. Like the other formatting methods it first restores the editor's last selection when focus is elsewhere, and records one undo step when the blocks read back afterward differ. The browser writes strikeThrough as a strike element, which the read-back does not keep: it is not reported, not undoable and is lost on the next undo, redo or read. |
| ApplyInlineStyleAsync(string property, string value) | Task | Wraps the selected text in spans carrying one CSS property, or sets it on a span that already wraps just that text. Does nothing when the selection is collapsed. Only the four properties ReadBlocksAsync keeps survive a read. |
| ApplyHeadingStyleAsync(string fontFamily, int fontSizePx, bool bold = true) | Task | Font family, size in pixels and, when bold, weight 700 on the selection: three ApplyInlineStyleAsync calls, so three undo steps. The paragraph stays a paragraph. |
| ApplyBlockStyleAsync(string property, string value) | Task | Sets one CSS property on every block the selection or caret touches; an empty value removes it. line-height is the one ReadBlocksAsync keeps. A triple-click selection ends at the start of the next block, so that block is changed too. |
| SetBlockAlignmentAsync(EditorAlignment alignment) | Task | Sets data-align on every block the selection or caret touches; Left removes it. EditorAlignment is Left, Center, Right or Justify. A triple-click selection ends at the start of the next block, so that block is changed too. |
| GetCaretAsync() | Task<EditorCaretInfo?> | The caret as a block id and character offset, or null outside a block. |
| SetCaretAsync(string blockId, int offset) | Task | Focuses the editor and places the caret at that offset in that block. |
| ScrollToBlockAsync(string blockId) | Task | Scrolls the block into view; an unknown id does nothing. |
| ScrollToTopAsync() | Task | Smooth-scrolls the editor's nearest scrolling ancestor to the top. |
| ResetEditorKey() | void | Changes the editable element's @key, so the control's next render rebuilds it and writes Blocks in again. |
| GetHistoryStateAsync() | Task<EditorHistoryState> | Undo and redo availability and counts; false and zero while EnableHistory is off. |
| UndoAsync() / RedoAsync() | Task | One step back or forward, with the caret put back where it was. Both do nothing while ReadOnly or with EnableHistory off. |
| FindAllAsync(string text, EditorSearchOptions? options = null) | Task<IReadOnlyList<EditorSearchMatch>> | Literal matches in each block, also across bold or styled runs; EditorSearchOptions(MatchCase, WholeWord). Matches are highlighted where the browser supports the CSS Custom Highlight API, and the results are refreshed as the user types. |
| SelectSearchResultAsync(int index) | Task<bool> | Selects that match and scrolls it into view; false when there is no such match. |
| ReplaceCurrentAsync(string replacement) | Task<int> | Replaces the selected match with literal text; returns 1, or 0 when no match is selected. |
| ReplaceAllAsync(string replacement) | Task<int> | Replaces every current match as one undo step and returns the count. |
| ClearSearchAsync() | Task | Drops the matches and their highlights. |
| OpenSearchAsync() | Task | Opens the find-and-replace panel above the text and focuses its Find box, as Ctrl+F or ⌘F does. |

### Block

| Name | Type | Default | Description |
|---|---|---|---|
| Id | string |  | Block identity, written as data-block-id; carets, search matches and ScrollToBlockAsync refer to it. A paragraph the browser creates on Enter gets a generated id the next time the document is read. |
| Kind | EditorBlockKind |  | Paragraph (p), ChapterHeading (h2), SectionHeading (h3), Image (a figure that cannot be edited) or PageBreak (a labeled divider; a new card in paged mode). There is no list kind. |
| Text | string |  | The block's content. Written in as escaped plain text unless Html is set; read back with the allowed inline markup. For an image, the alt text. |
| Alignment | string? | null | left, center, right or justify, written as data-align. |
| LineHeight | string? | null | Written as style="line-height: …" on the block. |
| Html | string? | null | When set, written in as the block's markup exactly as given, without sanitizing. ReadBlocksAsync sets it to the same value as Text. |
| ImageSrc | string? | null | Image address for an Image block, such as a data URL. |

### Format

| Name | Type | Default | Description |
|---|---|---|---|
| FontFamily / PageWidth / LineHeight | string? | null | Value the Font, Width and Line dropdowns show. |
| FontSizePx | int | 0 | Value the Size dropdown shows, compared as invariant-culture text with the option values. |
| FontFamilyOptions / FontSizeOptions / PageWidthOptions / LineHeightOptions | IEnumerable<EditorDropDownControl.EditorDropDownOption>? | null | EditorDropDownOption(Value, Label) lists for the four dropdowns. A null list leaves its dropdown out. |
| OnFontFamilyChanged / OnFontSizeChanged / OnPageWidthChanged / OnLineHeightChanged | EventCallback<string> |  | Raised with the picked option's value. Store it and pass it back through the matching parameter, which is what the dropdown shows after the next render. |
| OnBoldClicked / OnItalicClicked / OnUnderlineClicked / OnStrikeClicked | EventCallback |  | Raised by the B, I, U and S buttons. Every button in the control cancels its mouse-down, so a click leaves focus and the selection in the editor. |
| OnHeading1Clicked / OnHeading2Clicked | EventCallback |  | Raised by H1 and H2. The two buttons are drawn only when at least one of these has a handler. |
| OnAlignLeftClicked / OnAlignCenterClicked / OnAlignRightClicked / OnAlignJustifyClicked | EventCallback |  | Raised by the four alignment buttons. |
| CssClass | string? | null | Added to the fx-format-control root. |

### Lite

| Name | Type | Default | Description |
|---|---|---|---|
| Value | string | string.Empty | Content as HTML. A value that differs from what the control last wrote or read is sanitized and written in; text without a block element is wrapped in a p. |
| ValueChanged | EventCallback<string> |  | Raised after each input and each toolbar action with the sanitized HTML. |
| Changed | EventCallback<EditorLiteValue> |  | Raised at the same moments with every read-back format; see EditorLiteValue. |
| Placeholder | string | "Type here..." | Drawn by CSS (:empty) while the editing area has no child nodes; not part of Value. |
| ShowToolbar | bool | true | Draws the toolbar: a text style list (Normal, Heading, Subheading, Quote), Bold, Italic, Underline, Bulleted list, Numbered list, Link and Clear formatting. Link asks for the address with the browser's prompt and keeps only http, https, mailto, # and / addresses. |
| ToolbarLabel | string | "Editor formatting" | aria-label of the toolbar. |
| Height | string? | null | CSS height of the whole control; the editing area scrolls inside it. |
| MinHeight | string | "160px" | Minimum height of the control and of the editing area, through --fx-editor-lite-min-height. |
| Disabled | bool | false | Leaves out contenteditable, disables the toolbar and adds the class is-disabled. |
| SpellCheck | bool | true | Rendered as the spellcheck attribute when true. When false the attribute is left out, so the browser's default applies. |
| EditorId | string? | null | DOM id of the editing area; a generated fx-editor-lite-… id when empty. |
| CssClass | string? | null | Added to the fx-editor-lite root. |

### Lite methods

| Name | Type | Description |
|---|---|---|
| SetHtmlAsync(string html) | Task | Sanitizes html and writes it in, without raising ValueChanged. |
| GetHtmlAsync() | Task<string> | The content as sanitized HTML. |
| ReadAsync() | Task<EditorLiteValue> | Every read-back format at once. |
| ReadJsonAsync(bool indented = false) | Task<string> | ReadAsync serialized as JSON. |
| ReadFormatAsync(EditorLiteOutputFormat format) | Task<string> | One format: Json, Html, PlainText, Markdown, JiraText, JiraDocumentJson, Rtf or OpenDocumentHtml. |
| FocusAsync() | Task | Focuses the editing area. |
| ResetAsync(string html = "") | Task | Writes html in and rebuilds the editing element on the next render, without raising ValueChanged. |

### Lite value

| Name | Type | Default | Description |
|---|---|---|---|
| Schema | string | "fx-editor-lite/1" | Always fx-editor-lite/1. |
| Html | string | string.Empty | Sanitized HTML. Kept: p, br, b, strong, i, em, u, s, strike, ul, ol, li, h1 to h3, blockquote, code, pre, a and span; a div becomes a p. Links keep only http, https, mailto, # and / addresses; spans keep color, background color, weight, style and text decoration. |
| Text | string | string.Empty | Plain text, trimmed. It is read from a copy that is not in the page, where the browser returns the bare text, so paragraphs and line breaks run together. |
| Markdown | string | string.Empty | Headings as #, quotes as >, lists as - or 1., pre as a fenced block, **bold**, *italic*, ~~struck~~, `code` and [text](address); underline stays <u>. Blocks are separated by a blank line; a line break inside a block is dropped, and so is text that sits outside any block element (in Chrome, the first line typed into an empty editor). |
| JiraText | string | string.Empty | The Markdown, or the plain text when the Markdown is empty. |
| JiraDocumentJson | string | string.Empty | The content as a JSON tree: a doc (version 1) of paragraph, heading, blockquote, bulletList, orderedList and codeBlock nodes, whose text nodes carry strong, em, underline, strike, code and link marks. |
| Rtf | string | string.Empty | An RTF document in Arial 11 pt with bold, italic, underline and strike; list items become numbered or bulleted paragraphs. Text outside any block element is left out, as in Markdown. |
| OpenDocumentHtml | string | string.Empty | Html inside a complete HTML document with UTF-8 and Arial 11 pt body styles. |

### Keys

| Name | Description |
|---|---|
| Ctrl+F / ⌘F (EditorControl) | Opens the find-and-replace panel and focuses the Find box. |
| Ctrl+Z / ⌘Z | Undo, with EnableHistory on. With it off the key is left to the browser. |
| Ctrl+Y, Ctrl+Shift+Z / ⌘Y, ⌘⇧Z | Redo, with EnableHistory on. |
| Enter (Find or Replacement box) | Runs Find all and selects the first match. |
| Escape (Find or Replacement box) | Closes the panel, clears the highlights and puts focus back in the editor. |

## Examples

### Document

```razor
@using System.Net
@using System.Text.RegularExpressions
@using Fx.ControlKit
@using Fx.ControlKit.Editor

<div class="doc">
    <div class="doc-bar">
        <ButtonControl Disabled="@(!_history.CanUndo)" OnClick="Undo">Undo (@_history.UndoCount)</ButtonControl>
        <ButtonControl Disabled="@(!_history.CanRedo)" OnClick="Redo">Redo (@_history.RedoCount)</ButtonControl>
        <ButtonControl OnClick="FindReplace">Find and replace</ButtonControl>
        <ButtonControl OnClick="StartOver">Start over</ButtonControl>
    </div>
    <FormatControl FontFamily="@_font" FontSizePx="_size" PageWidth="@_width.ToString()" LineHeight="@_line"
                   FontFamilyOptions="Fonts" FontSizeOptions="Sizes" PageWidthOptions="Widths" LineHeightOptions="Lines"
                   OnFontFamilyChanged="PickFont" OnFontSizeChanged="PickSize"
                   OnPageWidthChanged="PickWidth" OnLineHeightChanged="PickLine"
                   OnBoldClicked='() => Format("bold")' OnItalicClicked='() => Format("italic")'
                   OnUnderlineClicked='() => Format("underline")' OnStrikeClicked='() => Format("strikeThrough")'
                   OnHeading1Clicked="() => Heading(26)" OnHeading2Clicked="() => Heading(20)"
                   OnAlignLeftClicked="() => Align(EditorAlignment.Left)" OnAlignCenterClicked="() => Align(EditorAlignment.Center)"
                   OnAlignRightClicked="() => Align(EditorAlignment.Right)" OnAlignJustifyClicked="() => Align(EditorAlignment.Justify)" />
    <div class="doc-page">
        <EditorControl @ref="_editor" Blocks="Letter" PageWidth="_width" FontFamily="Georgia" FontSizePx="16" LineHeight="1.6"
                       EnableHistory="true" HistoryChanged="h => _history = h" OnBlocksChanged="LetterChanged"
                       AriaLabel="Status letter to Green Fork Cafe" />
    </div>
    <p class="doc-status">Words: @_words · Blocks: @_blocks · OnBlocksChanged calls: @_changes</p>
</div>
```

```csharp
// Document (needs @using Fx.ControlKit.Editor, System.Net and System.Text.RegularExpressions)
private EditorControl? _editor;
private EditorHistoryState _history = new(false, false, 0, 0);
private EditorPageWidth _width = EditorPageWidth.Normal;
private string _font = "Georgia";
private int _size = 16;
private string _line = "1.6";
private int _words = Words(Letter), _blocks = Letter.Length, _changes;

private static EditorBlock P(string id, string html) => new(id, EditorBlockKind.Paragraph, html, Html: html);

private static readonly EditorBlock[] Letter =
{
    new("title", EditorBlockKind.ChapterHeading, "Website relaunch: Sprint 8 update"),
    P("greeting", "Dear Albus,"),
    P("intro", "Sprint 8 of the <b>Website relaunch</b> for Green Fork Cafe is underway. Here is where the four milestones stand and what we need from you."),
    new("milestones", EditorBlockKind.SectionHeading, "Milestone by milestone"),
    P("design", "<b>Discovery and Design.</b> Both milestones are complete: you signed off on the style guide and the refreshed logo."),
    P("build", "<b>Build.</b> The order form and the menu copy are in review, the order emails and the photo gallery are in progress, and the payment setup has not started."),
    P("launch", "<b>Launch.</b> Once Build is done, we will go through the launch checklist with you and switch the new site on while the cafe is closed."),
    new("next", EditorBlockKind.SectionHeading, "What we need from you"),
    P("provider", "Please choose a payment provider so that we can start the payment setup, and send us any menu changes so that the menu copy is right before you approve it."),
    P("signoff", "Kind regards,<br>The Scope Creep Studio team"),
};

private static readonly EditorDropDownControl.EditorDropDownOption[] Fonts = { new("Georgia", "Georgia"), new("Arial", "Arial"), new("Verdana", "Verdana") };
private static readonly EditorDropDownControl.EditorDropDownOption[] Sizes = { new("14", "14"), new("16", "16"), new("18", "18"), new("20", "20"), new("24", "24") };
private static readonly EditorDropDownControl.EditorDropDownOption[] Widths = { new("Narrow", "Narrow"), new("Normal", "Normal"), new("Full", "Full") };
private static readonly EditorDropDownControl.EditorDropDownOption[] Lines = { new("1.4", "1.4"), new("1.6", "1.6"), new("2", "2") };

private Task Format(string command) => _editor!.ExecFormatCommandAsync(command);
private Task Heading(int px) => _editor!.ApplyHeadingStyleAsync("Georgia", px);
private Task Align(EditorAlignment alignment) => _editor!.SetBlockAlignmentAsync(alignment);
private Task Undo() => _editor!.UndoAsync();
private Task Redo() => _editor!.RedoAsync();
private Task FindReplace() => _editor!.OpenSearchAsync();

private async Task PickFont(string font)
{
    _font = font;
    await _editor!.ApplyInlineStyleAsync("font-family", font);
}

private async Task PickSize(string size)
{
    _size = int.Parse(size);
    await _editor!.ApplyInlineStyleAsync("font-size", size + "px");
}

private void PickWidth(string width) => _width = Enum.Parse<EditorPageWidth>(width);

private async Task PickLine(string line)
{
    _line = line;
    await _editor!.ApplyBlockStyleAsync("line-height", line);
}

private async Task StartOver()
{
    await _editor!.PushAsync();
    (_words, _blocks, _changes) = (Words(Letter), Letter.Length, 0);
    (_font, _size, _line, _width) = ("Georgia", 16, "1.6", EditorPageWidth.Normal);
}

private void LetterChanged(IReadOnlyList<EditorBlock> blocks)
{
    _words = Words(blocks);
    _blocks = blocks.Count;
    _changes++;
}

private static int Words(IEnumerable<EditorBlock> blocks) =>
    blocks.Sum(b => Regex.Count(WebUtility.HtmlDecode(Regex.Replace(Regex.Replace(b.Text, @"<br\s*/?>", " "), "<[^>]+>", "")), @"\S+"));
```

### Comment

```razor
@using System.Net
@using System.Text.RegularExpressions
@using Fx.ControlKit
@using Fx.ControlKit.Editor

<div class="rt">
    <div class="note-label">Task WEB-117 · Order form · a note for Hermione Ranger</div>
    <EditorLiteControl @bind-Value="_note" MinHeight="120px"
                       Placeholder="What changed, how to test it, what is still open…" />
    <div class="note-bar">
        <ButtonControl CssClass="btn-primary btn-sm" Disabled="@NoteEmpty" OnClick="SaveNote">Save note</ButtonControl>
        <span class="note-count" role="status">@_saved.Count note@(_saved.Count == 1 ? "" : "s") on the task</span>
    </div>
    <ul class="note-list">
        @foreach (var saved in _saved)
        {
            <li>@((MarkupString)saved)</li>
        }
    </ul>
    <div class="note-label">Value</div>
    <pre class="note-out">@(_note.Length > 0 ? _note : "(empty)")</pre>
</div>
```

```csharp
// Task note: Value is sanitized HTML, so a saved note can be shown as markup
private string _note = "";
private readonly List<string> _saved = new();
// An emptied editor can still hold <br>, so test the visible text.
private bool NoteEmpty => string.IsNullOrWhiteSpace(WebUtility.HtmlDecode(Regex.Replace(_note, "<[^>]+>", "")));
private void SaveNote()
{
    _saved.Insert(0, _note);
    _note = "";   // a changed Value is written back into the editor
}
```

