Documentation / Internals

Text Editing

How core and the platform hosts synchronize text, selection, formatting, and composition in retained editors.

Ownership and the shared description

A field describes an editable Binding<String>; it does not contain the live editor. Core retains the view and its bindings, while the platform host retains the editing resource. Native uses a TextEditor backed by Parley. Web uses an input, textarea, or contenteditable DOM node. The host handles caret movement, selection gestures, and IME composition.

Field produces an ElementKind::TextInput description. Its Element.input is an optional boxed TextInputProperties payload containing the value, placeholder, multiline mode, requested selection, selection visibility, spans, and highlight. Ordinary elements do not allocate this payload. The description is comparable data; the host's mutable editing buffer and browser objects stay outside core.

Selection, formatting, and highlights are separate field properties. Bind a selection when the application needs to observe or request a range. Supply text spans when it owns formatting. Use a highlight for a decoration such as a search result, without changing the current editing selection.

The Field reference lists the public builders. The examples below use refract::prelude::*, including TextSelection, TextSpan, and TextHighlight. Configure field-specific methods before adding structural wrappers such as padding or frame.

From a host edit to a committed description

During Field::body, core reads the text binding and optional selection binding into the input properties. Those reads subscribe the field to model changes. The field installs a handler that writes Event::Input and Event::TextSelection back through set_if_changed, then invokes application callbacks. An on_input callback therefore sees the updated text binding.

A committed user edit produces Event::Input with the complete string. Selection observations are separate targeted events. Graph propagation marks subscribed views dirty; preparation produces an updated description, the host applies its patches, and core commits the prepared tree. See Graph for the reconciliation boundary.

Hosts compare the requested value with their retained state so an ordinary binding echo does not replace the text the user just typed. Native can leave its editor buffer and local undo history intact; a plain browser field avoids an unnecessary value assignment. Styled browser fields may rebuild their formatting nodes while preserving the active range.

The multiline and rich-text flags participate in element identity. Changing either replaces the host control, resetting its transient editing state. Updating spans, highlights, or the requested selection within a stable mode retains the control. Keep text_spans enabled with an empty vector when a styled field currently has no formatting.

Native: a retained Parley editor

Each native text-input entry owns a TextEditor. It retains a PlainEditor<()>, the last model value and spans, selection acknowledgement, composition state, local history, and scroll offset. The host synchronizes input properties and resolved typography into this editor. Winit keyboard, pointer, and IME events reach the host; application handlers run before the relevant editor defaults.

Parley operates on UTF-8 byte positions internally. Refract converts portable UTF-16 selections and span endpoints at the editor boundary, then uses Parley's layout cursors, selection geometry, and point hit testing. The refract-parley fork adds PlainEditor::set_ranged_styles: it stores externally supplied ranges, marks layout dirty, and applies those styles after defaults during layout construction. Parley's composition underline is applied afterward. This extension retains Parley's editing machinery; it does not maintain the application's document formatting model.

Painting refreshes the shaped layout for the available width, clamps editor scrolling, and reveals the caret when needed. Glyph runs, underlines, highlight rectangles, host selection, and caret commands share the same text origin and clipping bounds. Highlight geometry is computed from a separate range without changing the editing selection. selection_visible gates host selection and caret paint. See Native Rendering for how those commands reach the renderer.

Native undo records bounded snapshots of the text and selection. A model echo preserves that history; an external text replacement clears it so Undo cannot restore stale model content. These snapshots do not include application-owned formatting spans or multi-field document state. Applications that own those edits also own the corresponding document history.

Web: browser controls and styled contenteditable

Plain single-line fields use an input; multiline fields use a textarea. Their live values and selectionStart/selectionEnd/selectionDirection properties supply the text and directional range. The DOM entry retains its last element description, composition flag, and deferred model value. Ordinary input events publish the browser's current value, while patches avoid assigning an unchanged value.

Calling text_spans selects a styled contenteditable surface with contenteditable="plaintext-only" and textbox semantics. The application still owns a string and explicit spans, not an HTML document. rich_text::flatten walks text nodes and line-break structure into that string and maps DOM selection endpoints into the same UTF-16 coordinate space. A solitary caret-placeholder br is treated as empty text; the adapter's trailing-line marker is excluded from the value.

rich_text::render splits text at formatting and highlight boundaries, creates spans with explicit bold, italic, underline, and background styles, and inserts their content through text nodes. It replaces the formatting children and restores the previous selection only when the editor owns focus. Formatting patches therefore operate on application data rather than accepting arbitrary browser HTML as the model.

The browser owns its editing and undo behavior; the adapter does not implement native's snapshot history for DOM fields. Replacing contenteditable children is a different mechanism from native buffer editing, so the shared API does not promise identical undo behavior across hosts. Persistent rich-text or multi-field history belongs in the application model.

Observe selections without echoing requests

Selection synchronization distinguishes a host observation from a model request. Native remembers the last acknowledged range in model_selection; web updates the retained input description before dispatching Event::TextSelection. Both skip unchanged observations and suppress observation during composition. A later binding echo then matches already-applied host state instead of rewinding the caret.

Native publishes changed ranges after editing and pointer interactions and synchronizes them before application commands. Web combines document selectionchange notifications, delegated select events, and explicit synchronization before input and command handlers. A document notification is filtered to the focused control owned by that mount, so one mount does not publish another mount's selection.

For styled DOM fields, selection endpoints must map into the editor's subtree. The adapter uses a root-local selection API when available and supports composed ranges for shadow-root endpoints. Applying a range checks that the editor is active before touching browser Selection; a committed focus request reapplies the field's requested range after focusing it. This keeps selection requests separate from focus ownership.

Keep IME preedit local to the host

Provisional composition text stays in the editor instead of becoming a sequence of model edits. Hosts suppress ordinary input publication and selection synchronization while composition is active. Incoming model values are deferred until composition finishes; a pending model value takes precedence over the provisional edit.

HostComposition lifecycle
NativeWinit preedit updates Parley's composition. Refract saves the committed text and selection so cancellation can restore replaced content. Commit restores that baseline, inserts the committed text, and records one edit; a pending external value replaces it and clears local history. Losing field focus cancels composition.
Webcompositionstart marks the DOM entry as composing. Input events remain local and relevant model patches store a pending value. compositionend clears the flag, chooses the pending model value or completed browser text, restores the field's presentation, and publishes the resulting string.

Observe and request a selection

.selection(binding) accepts Binding<Option<TextSelection>>. Some(range) requests a directional range; TextSelection::caret(offset) places its anchor and focus at the same offset. None leaves the range under host control. Hosts publish user selection changes back into the binding and synchronize the current range before editing commands.

Selection and focus are independent. Request focus with focused or focused_value when an action should also activate the editor. A selection request alone should not be used to focus a field. This example observes the range and moves the caret to the end when the user activates a button.

selection.rs
use refract::prelude::*;

struct SelectionEditor;

impl View for SelectionEditor {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let value = cx.state("value", || String::from("Hello 👋"));
        let selection = cx.state("selection", || None::<TextSelection>);
        let focused = cx.state("focused", || false);

        let status = match cx.read(&selection) {
            Some(range) => format!("Selection: {} → {}", range.anchor, range.focus),
            None => String::from("Selection is under host control"),
        };

        Ok(v_stack()
            .gap(8.0)
            .child(field(value.clone())
                .label("Message")
                .selection(selection.clone())
                .focused(focused.clone()))
            .child(text(status))
            .child(text("Move caret to end").on_press(move |cx| {
                let end = value.get(cx.runtime()).encode_utf16().count() as u32;
                selection.set(cx.runtime(), Some(TextSelection::caret(end)));
                focused.set(cx.runtime(), true);
            })))
    }
}

fn selection_editor() -> impl View {
    SelectionEditor
}
i

Observing a selection does not turn it into an input edit. Programmatic selection writes are not echoed as user changes, and selection observation does not interrupt active composition or take focus from another browser mount.

Use UTF-16 offsets on both hosts

TextSelection offsets and TextSpan endpoints count UTF-16 code units on both web and native. They are not Rust byte indices, Unicode scalar counts, or grapheme counts. Use text.encode_utf16().count() when calculating a caret at the end of a string. Hosts clamp requested selection offsets to valid character boundaries.

In A😀B, A occupies offsets 0–1, the emoji occupies 1–3, and B occupies 3–4. A span with start: 1, end: 3 formats the emoji. A selection with anchor: 3, focus: 1 selects the same range backwards; preserve anchor and focus when selection direction matters.

Span ranges are half-open: start is inclusive and end is exclusive. Rust search methods return byte positions. Convert a matched prefix and substring to UTF-16 lengths before constructing a range, as in the styled editor below. Only slice strings at known character boundaries.

TypeFields and meaning
TextSelectionanchor, focus: directional UTF-16 offsets. caret(offset) collapses the range; is_collapsed() checks whether the endpoints match.
TextSpanstart, end: half-open UTF-16 range, plus bold, italic, and underline booleans.
TextHighlightrange: TextSelection, color: Color: a background decoration. Range direction does not affect its appearance.

Style editable text ranges

.text_spans(Vec<TextSpan>) enables styled editing and supplies bold, italic, and underline ranges. On web it uses a contenteditable field; native applies the ranges through its retained text editor. Whole-field typography such as .italic() remains available separately.

The application owns formatting spans and must keep them consistent with the current text. For persistent document formatting, update the ranges as your document model changes. For search or syntax-based styling, derive fresh spans from the current string during view evaluation.

This editor italicizes every exact search match and highlights the first one. It recomputes UTF-16 ranges after changes to the draft or search query. The highlight leaves the user's caret and selection alone. An empty query produces no formatting, while the field stays in styled mode.

search_editor.rs
use refract::prelude::*;

fn matching_spans(value: &str, query: &str) -> Vec<TextSpan> {
    if query.is_empty() {
        return Vec::new();
    }
    value.match_indices(query).map(|(byte_start, matched)| {
        let start = value[..byte_start].encode_utf16().count() as u32;
        let end = start + matched.encode_utf16().count() as u32;
        TextSpan { start, end, italic: true, ..TextSpan::default() }
    }).collect()
}

struct SearchEditor;

impl View for SearchEditor {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let draft = cx.state("draft", || {
            String::from("A small note with a little emphasis.")
        });
        let query = cx.state("query", || String::from("little"));

        let spans = matching_spans(&cx.read(&draft), &cx.read(&query));
        let highlight = spans.first().map(|span| TextHighlight {
            range: TextSelection { anchor: span.start, focus: span.end },
            color: Color::rgb(255, 225, 140),
        });

        Ok(v_stack()
            .gap(12.0)
            .child(field(query).label("Find text").placeholder("Find text"))
            .child(field(draft)
                .label("Document")
                .multiline(true)
                .text_spans(spans)
                .text_highlight(highlight)
                .height(160.0)))
    }
}

fn search_editor() -> impl View {
    SearchEditor
}
i

Keep calling text_spans, including with an empty vector, for a styled field. Switching between plain and styled editing remounts the control and resets focus, selection, undo history, and composition. Changing multiline also remounts it. Updating spans within a stable mode retains the editor.

Keep highlights separate from selection painting

.text_highlight(Some(TextHighlight { range, color })) paints one range with the supplied background color. It does not move the selection, request focus, or hide the host caret. Pass None to remove the decoration. On web, enable styled editing with .text_spans(vec![]) even when no inline formatting is needed.

.selection_visible(false) hides the host caret and selection paint when the application supplies its own presentation. It leaves the logical range, selection observations, focus, and editing behavior intact. The default is true. A search-result highlight usually keeps that default so the user can still see where typing will occur.

PropertyResponsibility
selectionObserve or request the logical editing range.
selection_visibleChoose whether the host paints its caret and selection.
text_highlightPaint an independent application-colored range.
focused / focused_valueRequest and observe which control receives keyboard input.

Build interactions around the editor

Keep ordinary typing and selection gestures with the host. Add on_key for application shortcuts and ignore composing keys unless the command understands IME input. Use clipboard handlers for application-owned copy, cut, and paste; they cover host menu commands as well as keyboard commands.

For spatial interactions, .geometry_tag(tag) includes an editor in cx.tagged_geometry() snapshots during pointer and scroll dispatch. cx.geometry() describes the current handler's element. Its optional text_offset is a UTF-16 hit position; on web this requires a styled field. Bounds and transforms can anchor an application toolbar or menu. See element geometry.

When a custom drag selection reaches a viewport edge, drive the surrounding ScrollView's velocity from application state. Values are logical pixels per second, with positive x/y moving right/down. Hosts clamp at content bounds. Set the velocity to zero when the drag ends or is cancelled, and use scroll observations to update the selection as the content moves.

For application context menus, the host synchronizes selection before secondary-pointer handlers. Preventing the secondary pointer default also suppresses the corresponding browser context menu. Use Input & Focus for event propagation and default behavior.

Source map

The shared contract lives in core; editor state and platform behavior live in the hosts. These files connect the public field builders to the retained editing resources and their regression coverage.

SourceResponsibility
crates/core/src/view/field.rsBinding reads, field configuration, and binding-writing event handlers.
crates/core/src/element.rs, events.rsInput properties, spans, highlights, UTF-16 selections, and event contracts.
crates/native/src/editor.rs, editor/history.rsParley synchronization, range conversion, composition, local undo, and editor painting.
crates/native/src/host/input.rs, app/events.rsFocus, pointer/key routing, selection publication, and application command boundaries.
vendor/parley/src/editing/editor.rsExternally supplied style ranges applied during Parley layout.
crates/web/src/dom.rs, events.rsDOM retention, value patches, focus, composition, and selection observation.
crates/web/src/rich_text.rs, base.cssStyled DOM construction, text/selection mapping, hit testing, and selection paint visibility.
crates/test/tests/text_input.rs, crates/web/tests/browser/selection_fixture.rsShared field behavior and browser checks for selection ownership, composition, formatting, and highlights. Native editor regressions live alongside TextEditor.