Table of Contents

Class TwTextEditor

Namespace
TwBlazor.Components
Assembly
TwBlazor.dll

Represents a rich text editor that edits formatted text, such as headings, bold text, lists and links, and binds it as HTML.

public class TwTextEditor : TwBlazorTextInputComponentBase, IComponent, IHandleEvent, IHandleAfterRender, ITwComponent, ITwInputComponent, IAsyncDisposable
Inheritance
TwTextEditor
Implements
Inherited Members

Remarks

Bind the content with @bind-Value. The value is HTML made only of the tags the editor produces (p, h1 to h3, strong, em, u, s, ul, ol, li, blockquote, pre, code, br and a with an http, https, mailto, tel or relative href), or an empty string when the editor holds no text. Everything that enters the editor, including a value set from code and pasted content, is cleaned the same way. The cleaning runs in the browser, so treat HTML posted to a server as untrusted and sanitize it again there before storing or showing it.

Toolbar chooses the controls above the text. The toolbar is built from TwSelect<T>, TwToggleGroup<T>, TwToggle, TwButton and TwSeparator, the link bar from TwTextfield<T>, and the HTML source view from a multiline TwTextfield<T>. The editing area is a textbox named after the Label, and the toolbar follows the ARIA toolbar pattern: Alt + F10 moves focus from the text to the toolbar.

Constructors

TwTextEditor()

public TwTextEditor()

Properties

ActiveFormats

Gets the formats applied at the selection, such as Bold and Heading2.

public IReadOnlySet<TextEditorFormat> ActiveFormats { get; }

Property Value

IReadOnlySet<TextEditorFormat>

DebounceInterval

Gets or sets how long, in milliseconds, to wait after the last keystroke before reporting the new content. Defaults to 250. Use 0 to report every keystroke.

[Parameter]
public int DebounceInterval { get; set; }

Property Value

int

Remarks

Formatting from the toolbar, a paste and focus leaving the editor are reported at once.

ExportFileName

Gets or sets the name exported files are saved with, without the extension. It is also stored as the document's title. Defaults to document.

[Parameter]
public string ExportFileName { get; set; }

Property Value

string

ExportFormats

Gets or sets the formats offered by an export menu at the end of the toolbar, in the order listed. Empty (the default) shows no export menu.

[Parameter]
public IReadOnlyList<TextEditorExportFormat> ExportFormats { get; set; }

Property Value

IReadOnlyList<TextEditorExportFormat>

Remarks

The files are written by TwTextEditorExport, using only the .NET libraries, and saved by the browser. The menu is not shown when Toolbar is None; call ExportAsync(TextEditorExportFormat, string?) from your own control instead.

Height

Gets or sets a fixed height for the editing area, as a CSS length. The area scrolls once its text is taller.

[Parameter]
public string? Height { get; set; }

Property Value

string

HelperText

Gets or sets the text shown under the editor. It is read out with the editor.

[Parameter]
public string HelperText { get; set; }

Property Value

string

Html

Gets the content as HTML, as last reported by the editor.

public string Html { get; }

Property Value

string

MaxHeight

Gets or sets the largest height of the editing area, as a CSS length. The area scrolls once its text is taller.

[Parameter]
public string? MaxHeight { get; set; }

Property Value

string

MinHeight

Gets or sets the smallest height of the editing area, as a CSS length. Defaults to 150px.

[Parameter]
public string? MinHeight { get; set; }

Property Value

string

OnBlur

Gets or sets the callback invoked when the editing area loses focus.

[Parameter]
public EventCallback OnBlur { get; set; }

Property Value

EventCallback

OnFocus

Gets or sets the callback invoked when the editing area receives focus.

[Parameter]
public EventCallback OnFocus { get; set; }

Property Value

EventCallback

OnSelectionChange

Gets or sets the callback invoked when the selection moves or the formats at it change.

[Parameter]
public EventCallback<TextEditorSelectionEventArgs> OnSelectionChange { get; set; }

Property Value

EventCallback<TextEditorSelectionEventArgs>

OnTextChange

Gets or sets the callback invoked with the new content whenever it changes.

[Parameter]
public EventCallback<TextEditorChangeEventArgs> OnTextChange { get; set; }

Property Value

EventCallback<TextEditorChangeEventArgs>

Placeholder

Gets or sets the text shown in the editor while it is empty.

[Parameter]
public string Placeholder { get; set; }

Property Value

string

Required

Gets or sets whether the editor must hold some text. The editor is announced as required by assistive technology.

[Parameter]
public bool Required { get; set; }

Property Value

bool

Remarks

Add a validation attribute such as [Required] to the bound property for the form to enforce it; an empty editor binds as an empty string.

ShowContextMenu

Gets or sets whether a right-click on the text opens a menu of formatting actions instead of the browser's own context menu. Keyboard users open it with Shift + F10 or the Menu key.

[Parameter]
public bool ShowContextMenu { get; set; }

Property Value

bool

Remarks

Off by default, since the browser's menu holds spelling suggestions and clipboard actions.

Toolbar

Gets or sets which controls the toolbar shows. Defaults to Standard.

[Parameter]
public TextEditorToolbar Toolbar { get; set; }

Property Value

TextEditorToolbar

ToolbarContent

Gets or sets controls added to the end of the toolbar, or that make up the whole toolbar when Toolbar is Custom. The context is the editor, so a control can call FormatAsync(TextEditorFormat) and read IsActive(TextEditorFormat).

[Parameter]
public RenderFragment<TwTextEditor>? ToolbarContent { get; set; }

Property Value

RenderFragment<TwTextEditor>

Remarks

Not shown when Toolbar is None. An icon-only control needs an AriaLabel.

Value

Gets or sets the content as HTML.

[Parameter]
public string? Value { get; set; }

Property Value

string

ValueChanged

Gets or sets the callback invoked with the new HTML when the content changes.

[Parameter]
public EventCallback<string?> ValueChanged { get; set; }

Property Value

EventCallback<string>

Remarks

While the user types, the change is reported once typing pauses for DebounceInterval, and always when focus leaves the editor.

ValueExpression

Gets or sets the expression that identifies the bound value. Set automatically by @bind-Value, it lets an enclosing EditForm or TwForm validate the property the editor edits.

[Parameter]
public Expression<Func<string?>>? ValueExpression { get; set; }

Property Value

Expression<Func<string>>

Methods

ApplyLinkAsync(string?)

Adds or changes the link, called by twTextEditor.bindLinkInput when Enter is pressed in the address field and by the bar's Apply button. An address that is not allowed keeps the bar open and shows why.

[JSInvokable("ApplyLink")]
public Task ApplyLinkAsync(string? url)

Parameters

url string

The typed address.

Returns

Task

A task that completes once the link has been added.

BuildRenderTree(RenderTreeBuilder)

Renders the component to the supplied RenderTreeBuilder.

protected override void BuildRenderTree(RenderTreeBuilder __builder)

Parameters

__builder RenderTreeBuilder

ClearFormattingAsync()

Removes bold, italic, underline, strikethrough and links from the selection.

public Task ClearFormattingAsync()

Returns

Task

A task that completes once the formatting has been removed.

CloseLinkPanelAsync()

Closes the link bar without changing anything and returns focus to the text. Called by twTextEditor.bindLinkInput for Escape.

[JSInvokable("CloseLinkPanel")]
public Task CloseLinkPanelAsync()

Returns

Task

A task that completes once focus is back in the text.

CreateFieldIdentifier()

Creates the identifier of the model property the field's value is bound to. Input components override this to build it from their value expression (supplied by @bind-Value).

protected override FieldIdentifier? CreateFieldIdentifier()

Returns

FieldIdentifier?

The field identifier, or null when the value is not bound to a property.

DisposeAsync()

Releases the field's connection to its form.

public override ValueTask DisposeAsync()

Returns

ValueTask

A task that completes once the field is released.

ExportAsync(TextEditorExportFormat, string?)

Exports the content as a file and has the browser save it. Any change still waiting for DebounceInterval is included, and the export is announced to screen readers.

public Task<ExportFile> ExportAsync(TextEditorExportFormat format, string? fileName = null)

Parameters

format TextEditorExportFormat

The file format.

fileName string

The file name without its extension, or null to use ExportFileName.

Returns

Task<ExportFile>

The exported file, for example to send it somewhere else as well.

FocusAsync()

Moves focus to the editing area, putting the caret back where it was.

public Task FocusAsync()

Returns

Task

A task that completes once focus has moved.

FormatAsync(TextEditorFormat)

Applies a format to the selection, or removes it when it is already applied. A text style such as Heading1 replaces the style of the paragraphs the selection touches.

public Task FormatAsync(TextEditorFormat format)

Parameters

format TextEditorFormat

The format to apply. Link opens the link bar, or use InsertLinkAsync(string).

Returns

Task

A task that completes once the format has been applied.

GetHtmlAsync()

Gets the content as sanitized HTML, including any change still waiting for DebounceInterval.

public Task<string> GetHtmlAsync()

Returns

Task<string>

The HTML, or an empty string when the editor holds no text.

GetLengthAsync()

Gets the number of characters in the content, not counting line breaks.

public Task<int> GetLengthAsync()

Returns

Task<int>

The number of characters.

GetTextAsync()

Gets the content as plain text, with a line break between paragraphs.

public Task<string> GetTextAsync()

Returns

Task<string>

The text.

InsertLinkAsync(string)

Links the selected text to an address, changes the link the caret is in, or inserts the address as a link when nothing is selected.

public Task<bool> InsertLinkAsync(string url)

Parameters

url string

The address. One without a scheme, such as example.com, gets https://, and an email address gets mailto:.

Returns

Task<bool>

true when the link was added; false when the address is not a web, email, phone or relative address.

IsActive(TextEditorFormat)

Gets whether a format is applied at the selection.

public bool IsActive(TextEditorFormat format)

Parameters

format TextEditorFormat

The format to check.

Returns

bool

true when the format is applied at the selection.

NotifyBlurAsync()

Raises OnBlur, called by twTextEditor.attach.

[JSInvokable("NotifyBlur")]
public Task NotifyBlurAsync()

Returns

Task

A task that completes once the callback has run.

NotifyFocusAsync()

Raises OnFocus, called by twTextEditor.attach.

[JSInvokable("NotifyFocus")]
public Task NotifyFocusAsync()

Returns

Task

A task that completes once the callback has run.

NotifyInputAsync(string?, string?, int)

Takes the content after the user changed it, called by twTextEditor.attach.

[JSInvokable("NotifyInput")]
public Task NotifyInputAsync(string? html, string? text, int length)

Parameters

html string

The content as sanitized HTML.

text string

The content as plain text.

length int

The number of characters.

Returns

Task

A task that completes once the change has been reported.

NotifyStateAsync(TextEditorSelectionState?)

Takes the formats at the selection after it moved, called by twTextEditor.attach.

[JSInvokable("NotifyState")]
public Task NotifyStateAsync(TextEditorSelectionState? state)

Parameters

state TextEditorSelectionState

The selection and its formats.

Returns

Task

A task that completes once the toolbar shows the new formats.

OnAfterRenderAsync(bool)

Method invoked after each time the component has been rendered interactively and the UI has finished updating (for example, after elements have been added to the browser DOM). Any ElementReference fields will be populated by the time this runs.

This method is not invoked during prerendering or server-side rendering, because those processes are not attached to any live browser DOM and are already complete before the DOM is updated.

Note that the component does not automatically re-render after the completion of any returned Task, because that would cause an infinite render loop.

protected override Task OnAfterRenderAsync(bool firstRender)

Parameters

firstRender bool

Set to true if this is the first time OnAfterRender(bool) has been invoked on this component instance; otherwise false.

Returns

Task

A Task representing any asynchronous operation.

Remarks

The OnAfterRender(bool) and OnAfterRenderAsync(bool) lifecycle methods are useful for performing interop, or interacting with values received from @ref. Use the firstRender parameter to ensure that initialization work is only performed once.

OnParametersSet()

Invoked when the component's parameters have been set. Ensures that the component has a unique identifier by generating one if none is provided.

protected override void OnParametersSet()

Remarks

If the component's identifier is not set, a unique ID is generated based on the component's type name (with a 'Tw' prefix removed if present) and a GUID. This helps ensure that each component instance can be uniquely identified, which is useful for scenarios such as associating labels with form elements or targeting elements in client-side scripts.

OpenLinkPanelAsync()

Opens the bar for adding or changing a link, with the address of the link the caret is in. Called by twTextEditor.attach for Ctrl + K.

[JSInvokable("OpenLinkPanel")]
public Task OpenLinkPanelAsync()

Returns

Task

A task that completes once the bar is open.

RedoAsync()

Redoes the last change that was undone.

public Task RedoAsync()

Returns

Task

A task that completes once the change has been redone.

RemoveLinkAsync()

Removes the link the caret is in, or the links in the selection, keeping their text.

public Task RemoveLinkAsync()

Returns

Task

A task that completes once the link has been removed.

SetHtmlAsync(string?)

Replaces the content, cleaning the HTML first, and reports the change through ValueChanged.

public Task SetHtmlAsync(string? html)

Parameters

html string

The new content as HTML, or null to empty the editor.

Returns

Task

A task that completes once the content has been replaced.

UndoAsync()

Undoes the last change.

public Task UndoAsync()

Returns

Task

A task that completes once the change has been undone.