DeepWorks Studios Blazor Component Library

Demo user Administrator ยท Blazor Server Library 20261206222504-6e8ff32.dirty

DwsCodeEditor

A plain-text code editor with live highlighting, line numbers, editor-style indentation keys, find and replace and markers. Its find bar is built from DwsInputs and DwsButtons (44 px on a touch screen), its copy button is a DwsClipboard.

API Reference

Placeholder

Placeholder shows while the editor is empty.

Tab indents. To leave the editor, press Escape, then Tab.
Show Code
CodeEditor.razor

<DwsCodeEditor Name="CodeEditorDemo_Placeholder" Label="Shell script" Language="DwsCodeLanguage.Bash" @bind-Value="@_placeholderCode"
               Placeholder="# Paste a shell script here" MinHeight="80" />

@code {
    private string _placeholderCode = string.Empty;
}

Maximum length

MaxLength caps the characters the editor accepts.

Tab indents. To leave the editor, press Escape, then Tab.
Show Code
CodeEditor.razor

<DwsCodeEditor Name="CodeEditorDemo_MaxLength" Label="MaxLength 200" Language="DwsCodeLanguage.Bash" @bind-Value="@_maxLengthCode" MaxLength="200" MinHeight="80" />

@code {
    private string _maxLengthCode = "echo \"MaxLength caps the characters\"";
}

Read-only, with the copy button

ReadOnly keeps the code focusable, selectable and copyable but refuses edits. The status bar has a Copy button that puts the whole code on the clipboard and says "Copied" for two seconds (ShowCopyButton switches it off, OnCopied reports the text, CopyToClipboardAsync does it from code).

Show Code
CodeEditor.razor

<DwsCodeEditor Name="CodeEditorDemo_ReadOnly" Label="Read-only" Language="DwsCodeLanguage.Css" Value="@ReadOnlyCss" ReadOnly="true" />

@code {
    private const string ReadOnlyCss = """"
        .dws-code-editor {
            /* Dark in every theme: Prism's token colours need it. */
            --dws-code-editor-bg: color-mix(in srgb, var(--black) 84%, var(--white));
            border-radius: var(--border-radius, 0.375rem);
        }
        """";
}

Disabled

Disabled greys the editor out and takes it out of the tab order.

Show Code
CodeEditor.razor

<DwsCodeEditor Name="CodeEditorDemo_Disabled" Label="Disabled" Language="DwsCodeLanguage.Html" Value="@DisabledHtml" Disabled="true" />

@code {
    private const string DisabledHtml = """"
        <section class="card">
            <h2>Disabled</h2>
            <p>The editor is greyed out and skipped by Tab.</p>
        </section>
        """";
}

Interface-Description

Name Typ Parameters Description
FocusAsync ValueTask Moves the keyboard focus into the editor. Does nothing while it is not shown.
CopyToClipboardAsync Task<bool> Puts the whole code on the clipboard, as the copy button does. False when the browser refuses: outside a secure context (https or localhost) and, in some browsers, when the call does not come from a click.
InsertTextAsync Task<bool> string text Replaces the selection (or inserts at the caret) with the text as if it was typed: undoable and reported like any edit (with Immediate=false once the editor loses focus). Focuses the editor first. Returns false when nothing was inserted: read-only, disabled, not shown or not interactive.
OpenFindAsync Task<bool> bool replace Opens the find bar, as Ctrl+F does; the bar takes the focus and a selection within one line is what is looked for. False when there is nothing to open: EnableFind is off, or the editor is disabled, not shown or not interactive.
CloseFindAsync Task<bool> Closes the find bar, as Escape does: the focus returns to the code with the current match selected. False when the bar was not open.
GoToLineAsync Task<bool> int line, int column Puts the caret on a line and column (both from 1; values outside the code go to its nearest end), scrolls the line into view and focuses the editor - the way to take the user to a marker. Works without EnableFind. False when the editor is disabled, not shown or not interactive.
Name Typ Default Description
Value string string.Empty The code. Supports two-way binding via @bind-Value. Setting it from code redraws the editor without raising ValueChanged. With ValueChanged bound the parent owns the value: a handler that does not update it refuses the edit and the previous text comes back. Line breaks come back as \n.
ValueExpression Expression<Func<string>>? null The bound field, set by @bind-Value. It names the textarea (name="Model.Snippet"), so a statically rendered DwsForm posts the code and [SupplyParameterFromForm] binds it back.
Immediate bool true Reports the text on every keystroke. When false it is reported once the editor loses focus; highlighting and the status bar still follow every key, but on Blazor Server the text travels once per edit session.
Language DwsCodeLanguage DwsCodeLanguage.None Language the code is highlighted as, by Prism in the browser. None leaves it uncoloured. The library's Prism build has no Markdown grammar and highlights Java with its generic C-like grammar.
LanguageName string? null A Prism grammar id that takes the place of Language (e.g. yaml, powershell, docker, diff, scss, cpp). An id the page's Prism does not know leaves the code uncoloured and logs a warning once.
LanguageLabel string? null Language name shown in the status bar. Falls back to the name of Language, to LanguageName, or to the localised "Plain text".
Label string string.Empty Visible label above the editor, tied to the textarea. Without it the editor is named by the localised aria-label "Code editor"; an aria-label in AdditionalAttributes wins.
Placeholder string? null Text shown while the editor is empty.
TabIndents bool true Tab and Shift+Tab indent and outdent the caret's line or every line of a selection. Escape, then Tab, still leaves the editor, and a hidden hint (aria-describedby) says so. When false Tab moves the focus.
AutoIndent bool true Enter keeps the line's indentation, adds a level after an opening bracket (and after a colon in Python), and puts a closing bracket right after the caret on its own line. Shift+Enter inserts a plain line break.
TabSize int 4 Width of an indentation level and of a tab character, in characters (1 to 16).
InsertSpaces bool true Indents with spaces up to the next tab stop; when false with a tab character.
ReadOnly bool false Shows the code but refuses edits; unlike Disabled the editor stays focusable, selectable and copyable.
RefusalCheckDelay int 250 Milliseconds typing must pause before the editor checks whether the parent refused the last edit and puts the previous text back.
Coerce Func<string, string?>? null Opt-in. Asked before an edit is committed, with the text the user produced; returns the text the editor keeps - the same text accepts the edit, another corrects it, null (or the previous text) refuses it. The kept text is shown in the same render and the caret stays where the user was typing. ValueChanged and OnValueChanged report the kept text and are not raised for a refused edit. With a coercion set the timed refusal check (RefusalCheckDelay) does not run; an exception in the callback is reported and refuses the edit.
CoerceAsync Func<string, Task<string?>>? null Coerce for an answer that has to be awaited. What was typed stays visible while the answer is on its way; an answer overtaken by a later edit, or by a value the parent set meanwhile, is dropped. With both set, Coerce runs first and its result is what CoerceAsync is asked about.
MaxLength int? null Most characters the editor accepts (maxlength).
ShowLineNumbers bool true Numbers the lines in a gutter that stays put while the code scrolls sideways.
WordWrap bool false Wraps long lines at the editor's width instead of scrolling sideways. A wrapped line keeps one line number.
ShowStatusBar bool true Shows the caret's line and column, the selection length and the language under the code (localised).
ShowCopyButton bool true Shows a Copy button in the status bar - a DwsClipboard, so the write starts inside the tap, as Safari requires - that puts the whole code on the clipboard and says "Copied" for two seconds; also in a read-only editor. Disabled while the editor is empty or disabled. Needs ShowStatusBar.
EnableFind bool true Find and replace in the browser: Ctrl+F (Cmd+F) or the status bar's Find button open a bar above the code - next / previous with Enter / Shift+Enter or F3 / Shift+F3, a count ('3 of 17'), match case, whole word and regular expression (Alt+C / Alt+W / Alt+R; an invalid pattern is reported, one that takes too long is stopped), every match marked in the code. Ctrl+H (Cmd+Alt+F) adds replace and replace all (one undo step; $1 and $& in a regular-expression search). Ctrl+G goes to a line. Escape closes the bar with the match selected in the code. A read-only editor finds without replacing; a disabled one has no bar. The bar is made of DwsInputs and DwsButtons (44 px on a touch screen; haptic feedback on the options and the replace buttons).
MatchBrackets bool true Marks the bracket next to the caret - ( ) [ ] { } - and its partner. Brackets are counted as text, so one inside a string or a comment counts too.
Markers IReadOnlyList<DwsCodeEditorMarker>? null Findings to show in the code, from a validator of the page's own: DwsCodeEditorMarker(Line, Column, Length, Severity, Message) with lines and columns from 1 and Length 0 for 'to the end of the line' (or the short form Line, Severity, Message for a whole line). Each underlines its stretch in its severity's colour (Error, Warning, Info) and marks its line in the gutter, with the message as the line number's tooltip. A visually hidden list names them for assistive technology and describes the editor (aria-describedby); an error sets aria-invalid; the status bar counts them. Positions are not moved while the user types - validate again and pass new markers.
Height int? null Fixed height of the code area in pixels; the code scrolls inside it.
MinHeight int? null Smallest height of the code area in pixels. Without it the editor is at least five lines tall.
MaxHeight int? null Largest height of the code area in pixels: the editor grows with its code up to it, then scrolls.
Resizable bool false Lets the user drag the code area's bottom edge to change its height.
FontSize int? null Font size of the code in pixels. Default 0.875rem.
Color DwsColor DwsColor.Primary Colour of the focus ring and the selection, resolved through the theme's CSS variables. The editor itself is dark in every theme, because Prism's token colours need a dark surface.
Tooltip string string.Empty Native tooltip (title) of the editor.
Name Typ Description
ValueChanged EventCallback<string> Raised with the new text after an edit (on every keystroke, or on blur with Immediate=false). Used by @bind-Value.
OnValueChanged EventCallback<string> Raised after every edit with the text the user produced - the same value ValueChanged receives. It reports the request, not the outcome: with ValueChanged bound it is raised even when the parent refuses the edit. Stays available when @bind-Value is used.
OnFocus EventCallback<FocusEventArgs> Raised when the editor gains focus.
OnBlur EventCallback<FocusEventArgs> Raised when the editor loses focus.
OnCopied EventCallback<string> Raised after the copy button (or CopyToClipboardAsync) put the code on the clipboard, with the copied text.
Name Typ Default Description
Element ElementReference The associated web component. May be null if accessed before the component is rendered.
ComponentGuid Guid Unique identifier for the component.
TypeString string The name of the component type, obtained from reflection.
Authorized_RegisterEnabled bool false Indicates whether this component is enabled through a permission registry.
Authorized_RegisterSelected bool false Indicates whether this component is selected in permission selection mode.
GetInitializedState bool false Returns whether the component is initialized.
GetRenderModeState DwsRenderMode Returns the current render mode.
GetComponentState DwsComponentStateType Returns the current component state.
GetIsInteractiveState bool false Returns whether the component is interactive.
GetIsPrerenderingState bool false Returns whether the component is prerendering.
GetComponentLoadingState bool false Returns whether the component is loading.
IsFormBusy bool false Whether the DwsForm (or DwsFormBusyRegion) around the component is locked because its submit handler is running. The state itself is the cascaded FormBusyState (IDwsFormBusyState).
Name Typ Parameters Description
DebugInfo void Logs debug information about the component.
UpdateState void Updates the component's state and triggers StateHasChanged.
UpdateStateAsync Task Asynchronously updates the component's state and triggers StateHasChanged.
Dispose void Disposes the component and releases resources.
FocusAsync ValueTask bool containedInScrollableList Sets focus to the component's element.
Name Typ Default Description
Name string Required unique identifier for the component within its container.
Visible bool true Determines if the component is visible in the UI.
Disabled bool false Disables the form control, ensuring it doesn't participate in form submission.
ComponentNameSpace string The namespace for permission-based access control.
PermissionKey string? null A stable key that takes the place of Name in the generated permission namespace (Page.PermissionKey): the stored permission survives a rename, and components that share a key share one permission entry. Null: keyed by Name. Read once, when the component registers; an explicit ComponentNameSpace wins.
Class string Optional CSS class names.
Style string Optional in-line styles.
Tag object An optional user-defined object to store any additional data with the component.
BackReference DwsReference A reference to the enclosing component.
ID string The HTML ID attribute for the component.
AdditionalAttributes Dictionary<string, object> Additional HTML attributes for the component's root element.
IgnorePermissionChecks bool false Bypasses all permission checks for this component.
IgnorePermissionSelection bool false Ignore permission selection mode for this component.
IgnoreFormBusy bool false Takes the component out of the submit lock of the DwsForm (or DwsFormBusyRegion) around it: IsFormBusy stays false for it.
Name Typ Description
OnInitializedCallbackStarted EventCallback Callback when OnInitialized starts.
OnInitializedCallback EventCallback Callback during OnInitialized.
OnInitializedCallbackCompleted EventCallback Callback when OnInitialized completes.
OnInitializedAsyncCallbackStarted EventCallback Callback when OnInitializedAsync starts.
OnInitializedAsyncCallback EventCallback Callback during OnInitializedAsync.
OnInitializedAsyncCallbackCompleted EventCallback Callback when OnInitializedAsync completes.
OnIsComponentLoadingChanged EventCallback<bool> Callback when IsComponentLoading changes.
OnCurrentRenderModeChanged EventCallback<DwsRenderMode> Callback when CurrentRenderMode changes.
OnComponentStateChanged EventCallback<DwsComponentStateType> Callback when ComponentState changes.
An error has occurred. This app may no longer respond until reloaded.