Documentation / Fundamentals

Input & Focus

Handle input, bind focus to state, and style focused controls and containers on web and native.

Choose a callback

Import refract::prelude::*. Shared event methods preserve concrete builder types, including Field and ScrollView. On composed or generic views, ViewExt targets a directly described element or adds an outer box. Configure the concrete control before wrapping it when the callback belongs on that control.

Callbacks receive &mut ActionContext first. Use cx.runtime() to update bindings and cx.environment::<K>() to read inherited values. Registering the same callback family multiple times appends handlers in registration order; it does not replace earlier handlers.

MethodPayloadBehavior
on_pressNoneSemantic activation by click or Enter/Space. Use on non-editable elements; existing roles remain intact.
on_key&KeyEventKey down and up, before native editor and activation defaults. Bubbles.
on_pointer&PointerEventDown, move, up, cancel, enter, and leave. Down/move/up/cancel bubble.
on_hoverboolMouse/pen enters or leaves this element and its descendants. Touch does not produce hover callbacks.
on_focus_changeboolConfirmed direct focus on this element. Descendant focus does not focus the ancestor.
on_focus_within_changeboolConfirmed focus enters or leaves this element or its descendants. Moving between children keeps the ancestor focused.
on_wheel&WheelEventWheel or trackpad input before host scrolling. Bubbles; its default can be prevented.
on_clipboard&ClipboardEventCopy, cut, or paste before host defaults, including edit-menu commands. Bubbles.
Field::on_input&strUser-edited text, after the binding updates. Programmatic writes do not emit input.
Field::on_submitNoneEnter for single-line fields; Cmd/Ctrl+Enter for multiline fields. IME composition does not submit.
ScrollView::on_scroll&ScrollEventActual scrolling and viewport/content geometry changes. See Scroll View.

Keyboard input

KeyEvent contains key, code, state (KeyState::Down or Up), modifiers, repeat, and is_composing. Key includes common named keys such as Escape and ArrowDown, printable Character(String), and other Named(String) keys. code identifies a physical key such as KeyA; prefer logical key for ordinary shortcuts. Modifiers exposes shift, control, alt, and meta.

Keyboard events start at the focused element. Add .focusable(true) to include a custom element in Tab navigation without giving it button semantics. Fields and activatable elements are included by default; .focusable(false) removes tab participation while allowing pointer focus. .disabled(true) suppresses user input and tab participation on that element; focus-loss notifications still let observers clear their state. Registering a keyboard or focus handler alone does not make an element focusable.

Ignore composition keys for shortcuts unless the control explicitly understands IME input. Repeated keydowns are exposed; use event.repeat to distinguish a held key. This example intentionally allows arrow-key repetition.

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

struct Stepper;

impl View for Stepper {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let count = cx.state("count", || 0);

        Ok(view()
            .child(text(format!("Value: {}", cx.read(&count))))
            .focusable(true)
            .label("Adjust value with the arrow keys")
            .on_key(move |cx, event| {
                if event.state != KeyState::Down || event.is_composing {
                    return;
                }
                let delta = match event.key {
                    Key::ArrowUp => 1,
                    Key::ArrowDown => -1,
                    _ => return,
                };
                cx.prevent_default();
                count.update(cx.runtime(), |value| *value += delta);
            }))
    }
}

Pointer input and capture

PointerEvent carries an id, kind (Mouse, Touch, Pen, or Unknown), phase, position, changed button, held buttons, modifiers, and pressure. Positions use logical pixels relative to the web mounting root or native window. The pointer ID identifies one pointer stream; do not persist it as application identity. Query held buttons with event.buttons.contains(PointerButton::Primary).

Call cx.capture_pointer() during pointer down or move to receive subsequent events at the current handler's element even outside its bounds. cx.release_pointer() releases that ownership. Capture ends on up/cancel; in native apps, mouse capture remains until all buttons are released. Always handle Cancel to clear drag state. Removal or disabling releases capture and suppresses further callbacks to that element.

The browser exposes mouse, touch, and pen. The native host exposes Winit mouse and touch input; device-specific pen data is not available through its current mouse path. Touch input has no hover callbacks. Browser touch scrolling can cancel a pointer stream; pointer capture alone does not override the browser's touch-gesture policy.

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

struct ResizeHandle;

impl View for ResizeHandle {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let width = cx.state("width", || 160.0);
        let anchor = cx.state("anchor", || None::<(f64, f32)>);

        Ok(view()
            .child(text("Drag to resize"))
            .width(cx.read(&width))
            .height(80.0)
            .background(Color::BLUE)
            .on_pointer(move |cx, event| {
                match event.phase {
                    PointerPhase::Down if event.button == Some(PointerButton::Primary) => {
                        let initial = width.get(cx.runtime());
                        anchor.set_if_changed(cx.runtime(), Some((event.position.x, initial)));
                        cx.capture_pointer();
                        cx.prevent_default();
                    }
                    PointerPhase::Move => {
                        if let Some((x, initial)) = anchor.get(cx.runtime()) {
                            let next = (initial + (event.position.x - x) as f32).clamp(80.0, 480.0);
                            width.set_if_changed(cx.runtime(), next);
                        }
                    }
                    PointerPhase::Up | PointerPhase::Cancel => {
                        anchor.set_if_changed(cx.runtime(), None);
                    }
                    _ => {}
                }
            }))
    }
}
i

This demonstrates pointer handling. A complete resize control should also provide keyboard adjustment, using on_key as in the previous example.

Convert pointer coordinates

ActionContext::local_position(event.position) converts a surface point to the current handler's local border box. local_bounds() returns that box. Geometry is supplied by the host for each handler in the bubbling route, so parent and child handlers receive coordinates for their own elements.

Conversion accounts for displayed transforms and scrolling. local_position returns None when geometry is unavailable or the transform is not invertible; local_bounds returns None when geometry is unavailable. These observations do not create graph dependencies.

For a canvas with view_box, local border-box coordinates still need conversion into drawing coordinates. Remove border and padding, then invert the centered aspect-fit transform. See Canvas.

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

fn pointer_surface(position: Binding<Point>) -> impl View {
    canvas(|_g, _frame| {})
        .width(200.0)
        .height(100.0)
        .on_pointer(move |cx, event| {
            if event.phase == PointerPhase::Move {
                if let Some(point) = cx.local_position(event.position) {
                    position.set(cx.runtime(), point);
                }
            }
        })
}

Observe element geometry

cx.geometry() returns the current handler's optional ElementGeometry: local bounds, a transform into mounting-surface coordinates, available scroll metrics, and an optional UTF-16 text hit offset. Geometry is a host observation, not reactive state. Use the bounds and transform to anchor application UI to a control; use scroll.max_offset() to check whether its content overflows.

Attach .geometry_tag("editor") to an element to include it in cx.tagged_geometry() snapshots during pointer and scroll dispatch. Each entry contains the supplied tag and that element's geometry. Tags identify application-defined regions; they do not replace view keys or change layout. Configure a field's tag before structural wrappers when the geometry should describe the editor itself.

Text hit offsets are optional and use UTF-16 code units. On web, they require a styled field enabled with text_spans. Handle missing geometry and hit positions explicitly. See Text Editing for selection interactions.

Propagation and default behavior

Keyboard, pointer down/move/up/cancel, wheel, and clipboard events travel from the target through mounted ancestors in one mutation batch. cx.target() identifies the original target; cx.current_target() identifies the element whose callback is running. Bubbling follows the Refract tree, including through composed views. Capture-phase event handlers are not exposed.

cx.stop_propagation() stops ancestor handlers. Other callbacks already registered on the same element still run. cx.prevent_default() is independent: it suppresses a native key action or pointer default without stopping propagation. Later handlers can inspect cx.default_prevented(). Preventing keydown suppresses the corresponding native editing/activation action. Preventing pointer down suppresses focus/selection defaults and the resulting Refract press activation.

Press, input, text selection, submit, scroll, focus, hover, and pointer enter/leave do not bubble. Parent hover still tracks entry into its entire subtree: moving between children does not repeatedly leave/re-enter the parent. Disabled elements suppress user input, but still receive focus-loss notifications so observers can clear state. Disabling a container does not recursively disable its descendants.

Default prevention is synchronous for keyboard, pointer, wheel, and clipboard callbacks; pointer callbacks can also request capture. These controls do not undo a committed input edit. Browser notifications generated reentrantly during a DOM commit are queued and cannot retroactively prevent a native action.

Handle wheel input

on_wheel receives WheelEvent before the host scrolls. Positive deltas move right/down on both hosts. Check unit (Pixel, Line, or Page) before interpreting the delta; trackpads normally use logical pixels. Events also carry a surface position and modifiers. phase is optional: browsers do not provide gesture phases.

cx.prevent_default() suppresses host scrolling for that event. cx.stop_propagation() only stops ancestor handlers, leaving default scrolling available. Use on_scroll to observe actual movement and content bounds; a wheel delta does not guarantee that anything moved.

This field keeps horizontal gestures away from an ancestor's custom navigation handler only while its content overflows. It retains host scrolling, including at the field's scroll boundaries. A fitting field lets the gesture reach ancestors. Attach the handler before padding so cx.geometry() describes the field.

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

fn horizontally_scrollable_field(value: Binding<String>) -> Field {
    field(value)
        .label("Value")
        .width(240.0)
        .on_wheel(|cx, event| {
            let overflows = cx.geometry()
                .and_then(|geometry| geometry.scroll)
                .is_some_and(|metrics| metrics.max_offset().x > 0.0);

            if overflows && event.delta.x.abs() > event.delta.y.abs() {
                cx.stop_propagation();
            }
        })
}

Handle clipboard commands

Use on_clipboard for ClipboardCommand::Copy, Cut, and Paste, including browser clipboard events and native keyboard or edit-menu commands. The current field selection is synchronized before command handlers run. See selection bindings for observing that range.

Copy and cut handlers supply ClipboardContent { text, html } with event.set_content(...), then call cx.prevent_default(). A cut handler also removes the selected content from the application's model. Paste handlers read event.content(), apply the content to the model, and prevent the default when they have handled it. Leaving the default enabled preserves ordinary host editing.

Clipboard handling is synchronous so the browser can populate its native event. Plain text is required for supplied content; HTML is optional. This example copies an application-maintained selection string. It leaves cut, paste, and empty selections to the host; an application that owns a multi-field selection should implement those commands against its own model as well.

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

fn copy_selected_text(
    content: impl View,
    selected_text: Binding<String>,
) -> impl View {
    content.on_clipboard(move |cx, event| {
        if event.command != ClipboardCommand::Copy {
            return;
        }
        let text = selected_text.get(cx.runtime());
        if text.is_empty() {
            return;
        }

        event.set_content(ClipboardContent { text, html: None });
        cx.prevent_default();
    })
}

Observe user edits

A field already synchronizes its binding. Add on_input for work specific to user editing, such as search suggestions or an edited indicator. The callback sees the updated binding, and programmatic writes do not call it. Hosts retain native caret, selection, and IME ownership; provisional composition text is not published as input.

Use the field's selection binding for caret and range observations, and text_spans or text_highlight for formatting and decoration. See Text Editing for the separate ownership of text, selection, and presentation.

input.rs
field(value)
    .on_input(|_, text| println!("User edited: {text}"))
    .on_submit(|_| println!("Submitted"))
    .on_focus_change(|_, focused| println!("Focused: {focused}"));

Event scope and modifier order

Shared event handlers do not introduce a wrapper on concrete primitives or containers. padding and frame are structural: view.padding(12.0).on_pointer(...) targets the padded box, while view.on_pointer(...).padding(12.0) targets the inner element. Attach field handlers and focus bindings before structural modifiers to target the editable control. Attach subtree observation or a focus-within indicator after padding when the feedback belongs to the padded container.

Use on_press for ordinary actions so pointer and keyboard activation share one callback. Low-level pointer handlers do not automatically provide keyboard semantics. Higher-level double-press, long-press, drag-and-drop, and raw composition callbacks are not exposed yet. Wheel input uses on_wheel.

Bind focus to state

Use .focused(Binding<bool>) to request and observe direct focus on one element. The binding is ordinary graph state: true requests focus after the view commits, and host changes from clicking or tabbing update it. Writing false only blurs the element if that binding owns the current focus. No dedicated focus-state type is required.

Focus bindings preserve concrete builders, including Field and ScrollView, and work on custom boxes, text, and images. A binding makes an element a programmatic focus target; it does not add a tab stop or button semantics. Configure the actual field before adding structural wrappers.

Requests are resolved against the committed tree and acknowledged with the actual host target. A disabled or missing target does not become a deferred request: the binding reconciles to actual focus. An initial true requests focus when the attachment first commits. Set focus from an action or committed effect rather than writing state during view evaluation.

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

struct MessageInput;

impl View for MessageInput {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let draft = cx.state("draft", String::new);
        let focused = cx.state("focused", || false);

        Ok(v_stack()
            .gap(12.0)
            .child(field(draft).label("Message").focused(focused.clone()))
            .child(text("Focus message").on_press(move |cx| {
                focused.set(cx.runtime(), true);
            })))
    }
}

Share focus across views

Use .focused_value(Binding<Option<T>>, value) to give each target a name. T must implement Clone + PartialEq + 'static. Writing Some(value) requests that target; host transitions publish its value, and focus outside that selection publishes None. Writing None only clears focus owned by that selection.

Put the selection in an ordinary shared model and provide it with environment_object. Any action with access to the model can request focus, and views can read the selection through cx.read. The example accepts a model whose bindings come from existing state; retain the model at an application or provider boundary as described in Reactivity.

Each binding/value pair must identify one mounted element. Duplicate attachments fail preparation, and simultaneous requests from independent bindings report a conflict. A shared optional selection gives competing targets one source of truth. State-backed bindings keep their identity across renders; create a mapped binding once and reuse its clones instead of recreating the projection for each attachment.

Focus belongs to one application/window. Share its selection within that environment, rather than using one writable selection across independent windows.

shared-focus.rs
use refract::prelude::*;
use std::rc::Rc;

#[derive(Clone, PartialEq)]
enum FocusTarget {
    Search,
    Composer,
}

struct Workspace {
    focus: Binding<Option<FocusTarget>>,
    query: Binding<String>,
    draft: Binding<String>,
}

struct WorkspaceFields;

impl View for WorkspaceFields {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let model = cx.object::<Workspace>()?;
        let focus = model.focus.clone();
        Ok(v_stack()
            .gap(12.0)
            .child(field(model.query.clone())
                .label("Search")
                .focused_value(model.focus.clone(), FocusTarget::Search))
            .child(field(model.draft.clone())
                .label("Message")
                .focused_value(model.focus.clone(), FocusTarget::Composer))
            .child(text("Write a message").on_press(move |cx| {
                focus.set(cx.runtime(), Some(FocusTarget::Composer));
            })))
    }
}

fn workspace(model: Rc<Workspace>) -> impl View {
    WorkspaceFields.environment_object(model)
}

React to focus within a container

.on_focus_change observes direct focus. .on_focus_within_change observes focus on the element or anywhere in its subtree. These are confirmed notifications, not requests, and do not make the container a tab stop. Moving focus between siblings does not emit a false/true pair on their common ancestors.

Binding updates and direct/subtree callbacks run in one graph batch. Write ordinary state in a callback and read it during view evaluation to change a background, border, or other property. Nested containers can each observe their own subtree. These style updates preserve mounted controls and their editing state when identity stays the same.

focus-within.rs
use refract::prelude::*;

struct NameFields;

impl View for NameFields {
    fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
        let first = cx.state("first", String::new);
        let last = cx.state("last", String::new);
        let within = cx.state("within", || false);
        let background = if cx.read(&within) {
            Color::rgb(235, 243, 255)
        } else {
            Color::WHITE
        };
        Ok(v_stack()
            .gap(12.0)
            .child(field(first).label("First name"))
            .child(field(last).label("Last name"))
            .padding(16.0)
            .background(background)
            .radius(8.0)
            .on_focus_within_change(move |cx, active| {
                within.set_if_changed(cx.runtime(), active);
            }))
    }
}

Tab order and focus recovery

Fields and activatable elements participate in Tab navigation by default. .focusable(true) includes a custom element; .focusable(false) excludes it while retaining pointer and programmatic focus. Neither registering a callback nor attaching a focus binding adds a tab stop. Disabled elements are skipped.

Native Tab and Shift-Tab follow mounted tree order and wrap within the window. Traversal continues from the current element's position even if it was focused programmatically and is not itself a tab stop. The web uses browser tab order and can leave the mount. Native traversal respects prevented key defaults, IME composition, and Control/Meta/Alt combinations; the browser retains its native keyboard behavior.

The adapters reveal keyboard and requested focus through scrolling. When a focused target is removed, disabled, or excluded from tab order, recovery searches forward in the previous order, then backward, and clears focus if no eligible target remains. The resulting host transition updates bindings and observers. Unrelated updates do not request focus.

Style focus indicators

.focus_ring(FocusRing) configures the indicator for direct focus. .focus_within(FocusRing) opts a container into an indicator while it or a descendant is focused. These paint modifiers do not request focus or write graph state. Use .on_focus_within_change when the effect needs to change other properties instead.

FocusRing::new(color, width, offset) uses logical pixels. Width and offset must be finite and nonnegative. The default is a blue 2px ring with a 2px gap, following the element's corner radii. Pointer focus uses a quieter translucent indicator up to 1px wide with no gap; typing preserves that treatment, and Tab restores the full navigation ring.

Use FocusRing::none() to suppress an indicator when another element provides the feedback. This example puts feedback around the entire field group. Rings do not affect layout or escape ancestor clipping: leave padding inside a scroll viewport for the ring's width plus offset, such as .padding(6.0).scrollable() for the default ring.

focus-indicators.rs
let group = v_stack()
    .child(field(draft)
        .label("Message")
        .focus_ring(FocusRing::none()))
    .padding(16.0)
    .radius(12.0)
    .focus_within(FocusRing::new(Color::BLUE, 2.0, 2.0));

Window activation is separate

Surface.is_active is a read-only graph attribute for native window or browser document activation. Losing activation retains logical element focus and its binding, while the host hides built-in focus indicators. Returning to the window does not create a new element focus transition.

Read this attribute alongside your focus state when custom styling should also depend on activation. It is independent of the surface's lifecycle: an inactive window can still accept host requests. See Browser & Native for the other surface observations.

window-focus.rs
let surface = cx.object::<Surface>()?;
let active = cx.read(&surface.is_active);