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
public IReadOnlySet<TextEditorFormat> ActiveFormats { get; }
Property Value
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
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
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
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
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
Html
Gets the content as HTML, as last reported by the editor.
public string Html { get; }
Property Value
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
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
OnBlur
Gets or sets the callback invoked when the editing area loses focus.
[Parameter]
public EventCallback OnBlur { get; set; }
Property Value
OnFocus
Gets or sets the callback invoked when the editing area receives focus.
[Parameter]
public EventCallback OnFocus { get; set; }
Property Value
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
OnTextChange
Gets or sets the callback invoked with the new content whenever it changes.
[Parameter]
public EventCallback<TextEditorChangeEventArgs> OnTextChange { get; set; }
Property Value
Placeholder
Gets or sets the text shown in the editor while it is empty.
[Parameter]
public string Placeholder { get; set; }
Property Value
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
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
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
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
Remarks
Value
Gets or sets the content as HTML.
[Parameter]
public string? Value { get; set; }
Property Value
ValueChanged
Gets or sets the callback invoked with the new HTML when the content changes.
[Parameter]
public EventCallback<string?> ValueChanged { get; set; }
Property Value
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
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
urlstringThe 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
__builderRenderTreeBuilder
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
formatTextEditorExportFormatThe file format.
fileNamestringThe 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
formatTextEditorFormatThe 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
GetLengthAsync()
Gets the number of characters in the content, not counting line breaks.
public Task<int> GetLengthAsync()
Returns
GetTextAsync()
Gets the content as plain text, with a line break between paragraphs.
public Task<string> GetTextAsync()
Returns
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
urlstringThe address. One without a scheme, such as
example.com, getshttps://, and an email address getsmailto:.
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
formatTextEditorFormatThe format to check.
Returns
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
htmlstringThe content as sanitized HTML.
textstringThe content as plain text.
lengthintThe 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
stateTextEditorSelectionStateThe 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
firstRenderboolSet to
trueif this is the first time OnAfterRender(bool) has been invoked on this component instance; otherwisefalse.
Returns
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
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.