zgui

Events

Attach listeners with on:, handle clicks, keys, pointer, wheel and scroll input, and control how an event travels through the document.

A listener is a function attached to one element for one kind of event. You attach it in a view with on:, and the handler's argument type follows from the event name.

Attach a listener

use zgui::prelude::*;

#[component]
fn Counter() -> impl IntoView {
    let count = RwSignal::new(0);

    view! {
        row(class = "counter") {
            text {{move || count.get().to_string()}}
            control(
                class = "button",
                on:click = move |_| count.update(|n| *n += 1)
            ) {
                "+"
            }
        }
    }
}

The attribute is on: followed by an event name:

on:click:stop = move |ev| f(ev)
on:
The event namespace.
click
A snake_case event name.
:stop
Zero or more modifiers, each after its own colon.
= move |ev| f(ev)
Any expression that is a function of the event.
The parts of an event attribute

The handler's argument, ev, dereferences to the event's payload, so you read fields such as ev.key or ev.position directly. on:click gives a pointer payload and on:key_down a key payload, with no annotation or downcast. ev also has methods that control dispatch, such as ev.stop_propagation(). Handler argument reference lists them all.

A misspelled event name is a compile error with a suggestion:

error: `on:clik` is not an event

help: there is an event called `on:click`

on:click with no = is also an error: `on:click` needs a handler: `on:click=…`.

A handler runs inside the reactive owner that was current when the listener was attached, usually its component. It can call use_context, create signals and spawn tasks just as the component body can. See Context.

Define a handler outside the view

An inline closure gets its argument type from the element. A closure stored in a let first does not, and the element rejects it with implementation of Fn is not general enough. Wrap it in handler, which fixes the event type and costs nothing at run time:

let dismiss = handler(events::KEY_DOWN, move |ev: &mut EventCx<'_, events::KeyDown>| {
    if ev.key == Key::Named(NamedKey::Escape) {
        open.set(false);
    }
});

view! {
    box(on:key_down = dismiss) { "…" }
}

Listeners and callback props

An element takes on:click. A component takes on_click, with an underscore:

control(on:click = f)      // a listener on an element
Dialog(on_open_change = f) // an ordinary prop of a component

A listener is registered on a node and takes part in dispatch: ancestors see the event, and a handler can stop it. A callback prop is a plain value that the component calls itself; it has no node and no dispatch path.

A component can forward listeners to the element it renders with #[prop(attrs)] and a {..attrs} spread. See Components.

Handle clicks

on:click fires when an element is activated:

  • a primary-button press and release on it,
  • Enter or Space while it has focus, or
  • an activation from an assistive technology.

One on:click handler therefore covers mouse, touch, keyboard and assistive technologies. A pointer click requires the primary button, pressed and released over the same element. Secondary, middle, back, forward and other buttons never activate a control, and releasing outside the pressed element cancels the click.

A pointer click carries the release's button and modifiers, so you can read Shift or Control from on:click directly:

control(
    class = "row",
    on:click = move |ev| {
        if ev.modifiers.primary() {
            selection.update(|s| s.toggle(id));   // Ctrl-click, or Cmd-click on macOS
        } else {
            selection.set(Selection::only(id));
        }
    },
    on:double_click = move |_| open(id)
)

Double clicks

double_click is dispatched right after the second click when:

  • both clicks come from the pointer and land on the same element,
  • the second follows the first within 500 ms,
  • and it lands within 4 CSS pixels of the first on each axis.

Both clicks are still delivered. A third press starts a new count, so a triple click produces one double_click. A keyboard activation resets the count.

Right-clicks and context menus

on:context_menu fires on a touch long press, or when an assistive technology asks for the element's menu. It does not fire on a right-click. To handle a right-click, check the button in on:pointer_down:

box(on:pointer_down = move |ev| {
    if ev.button == Some(PointerButton::Secondary) {
        menu_at.set(Some(ev.position));
    }
})

Act on press

A control that acts on press, such as a menu trigger or a switch, calls ev.activate_now() in its on:pointer_down handler. That clicks the element immediately, and the later release does not click it again. The control's on:click handler still defines what activation does, so Enter, Space and assistive technologies reach the same code.

To move focus from an on:click handler, call focus() on a NodeRef. ev.request_focus(…) does nothing there; Queued commands explains why.

Handle keys

on:key_down and on:key_up are aimed at the element that has focus. With nothing focused, they are aimed at the root element, so a listener there acts as a window-wide shortcut. When the focused element is removed from the document, focus is cleared and keys go to the root again.

column(
    tabindex = Focus::Sequential,
    on:key_down = move |ev| match &ev.key {
        Key::Named(NamedKey::Enter) => submit(),
        Key::Named(NamedKey::Backspace) => draft.update(|d| { d.pop(); }),
        // inserted_text() handles Space, which is a named key that inserts " ".
        key => if let Some(text) = key.inserted_text() {
            draft.update(|d| d.push_str(text));
        },
    }
)

The payload is a KeyEvent:

pub struct KeyEvent {
    pub key: Key,                   // layout and modifiers applied
    pub key_without_modifiers: Key, // layout applied, modifiers not
    pub physical: PhysicalKey,      // the key's position on the keyboard
    pub location: KeyLocation,      // Standard | Left | Right | Numpad
    pub repeat: bool,               // generated by holding the key down
}

Key is Named(NamedKey), Character(SharedString), Dead(Option<char>) for an accent waiting for the next key, Other for a standard name not in NamedKey, or Unidentified.

Holding a key down fires on:key_down repeatedly, with repeat set. zgui ignores repeats for its own default behaviour, so holding Tab or Enter does not run it repeatedly.

Shortcuts

Modifiers has four flags, SHIFT, CONTROL, ALT and META, with shift(), control(), alt(), meta() and contains(). For application shortcuts, use Modifiers::PRIMARY or primary(): Command on macOS, Control elsewhere.

on:key_down = move |ev| {
    let s = matches!(&ev.key, Key::Character(c) if c.eq_ignore_ascii_case("s"));
    if ev.modifiers.primary() && s {
        ev.prevent_default();
        save();
    }
}

A shortcut without a modifier, such as Delete or Escape on the root, should leave text fields alone. focus_is_text_entry() tells you whether focus is in an element the user types into:

on:key_down = move |ev| {
    if ev.key == Key::Named(NamedKey::Delete) && !focus_is_text_entry() {
        delete_selection();
    }
}

Keyboard and focus covers NamedKey, KeyCode, focusable elements, traversal order, focus rings, focus traps and NodeRef::window_shortcut.

Pointer events

Mouse, touch and pen share one set of events: pointer_down, pointer_up, pointer_move, pointer_enter, pointer_leave and pointer_cancel. Their payload is a PointerEvent:

pub struct PointerEvent {
    pub id: PointerId,               // which pointer; PointerId::MOUSE is always 0
    pub kind: PointerKind,           // Mouse | Touch | Pen | Unknown
    pub primary: bool,               // the mouse, or the first finger down
    pub position: Point<CssPx, Css>, // CSS pixels from the window's top-left corner
    pub button: Option<PointerButton>,
    pub pressure: Option<f32>,       // 0 to 1, when the device reports it
}

PointerButton is Primary, Secondary, Middle, Back, Forward or Other(u16). A touch contact always reports Some(PointerButton::Primary).

PointerKind::can_hover() is true for Mouse and Pen and false for Touch. Do not put a control's only affordance behind hover.

Hover, enter and leave

zgui sets :hover on the hovered element and all its ancestors. Use it for anything visual, and use pointer_enter and pointer_leave only for reactions that are not a style on that element:

.button:hover { background-color: #2b3243; }

Only elements whose state changed are touched. :active works the same way along the path of the pressed element.

There is no pointer_over or pointer_out. pointer_enter and pointer_leave:

  • do not bubble. Each element whose boundary the pointer crossed gets its own event, so a wrapper receives one enter, not one per child.
  • arrive leaves first, innermost outwards, then enters, outermost inwards.
  • are dispatched right after the event that caused them.
  • still run the capture phase, so an ancestor's on:pointer_enter:capture sees a descendant's enter.

Drag with pointer capture

A slider thumb must keep receiving moves after the pointer leaves it. Capture the pointer on press and release it on release:

control(
    class = "thumb",
    on:pointer_down = move |ev| { ev.capture_pointer(); dragging.set(true); },
    on:pointer_move = move |ev| if dragging.get() { set_from(ev.position) },
    on:pointer_up = move |ev| { ev.release_pointer(); dragging.set(false); },
)

While the pointer is captured, its events target the capturing element wherever the pointer is. The path still includes that element's ancestors. Other elements do not gain hover during the drag.

Capture is zgui's own routing, not an operating-system grab. It ends when you call release_pointer(), when the capturing element leaves the document, or when the window loses the press (for example, because it loses input focus mid-drag).

ev.capture_pointer() always captures the mouse pointer. A handler cannot capture a single touch contact yet.

A host that shares the pointer with other content, such as a game view under the interface, can ask a window which element holds a capture with Window::pointer_capture(pointer_id) or Window::has_pointer_capture() in zgui::runtime.

Pointer coordinates

position is in CSS pixels from the window's top-left corner. There is no element-relative position.

To measure a pointer against an element, use a NodeRef. NodeRef::window_bounds() is in device pixels from the same origin, so multiply the pointer position by scale() before comparing:

let track_box = track.window_bounds()?;
let x = ev.position.x.0 * track.scale();
let fraction = (x - track_box.origin.x.0) / track_box.size.width.0;

Coalesced pointer moves

Moves of one pointer that arrive between two frames are dispatched once, at the last position. The earlier positions are available from ev.coalesced() as PointerSample values (position, pressure, timestamp), oldest first:

on:pointer_move = move |ev| {
    for sample in ev.coalesced() {
        stroke.push(sample.position, sample.pressure, sample.timestamp);
    }
    stroke.push(ev.position, ev.pressure, ev.timestamp);
}

Use coalesced() for freehand drawing. Hover, dragging and ordinary controls need only the final position. Presses, releases, keys, crossings and moves of another pointer are never merged or reordered.

Wheel and scroll

on:wheel is the input. on:scroll is the result.

pub struct WheelEvent {
    pub delta: ScrollDelta,          // Lines { x, y } or Pixels(Size)
    pub phase: ScrollPhase,          // Discrete | Started | Moved | Momentum | Ended
    pub position: Point<CssPx, Css>,
    pub id: PointerId,
    pub kind: PointerKind,
}

A positive delta moves the scroll offset right and down, so the content moves up and left. The delta is in the device's unit. Line deltas depend on the line height of the container that scrolls, so convert them with ScrollDelta::to_pixels(line_height) once you know it.

A notched wheel reports ScrollPhase::Discrete. A trackpad reports Started, Moved, Momentum and Ended.

pub struct ScrollEvent {
    pub offset: Point<CssPx, Css>,
    pub content_size: Size<CssPx, Css>,
    pub scrollport: Size<CssPx, Css>,
}

on:scroll does not bubble. It fires once per container that moved this frame, after layout and before paint, so a handler that repositions something is drawn in the same frame. Several moves in one frame produce one event. scrollable() and is_at_end_vertically() cover the common checks.

Scrolling covers the offset model, chaining, scrollbars and programmatic scrolling.

Example: a switch

Click, hover and keyboard activation without the component library:

use zgui::prelude::*;

#[component]
fn Wifi() -> impl IntoView {
    let on = RwSignal::new(false);
    let hint = RwSignal::new(String::new());

    view! {
        column(class = "wifi") {
            control(
                class = "switch",
                state:checked = move || on.get(),
                a11y:role = Role::Switch,
                a11y:label = "Wi-Fi",
                on:click = move |_| on.update(|value| *value = !*value),
                on:pointer_enter = move |_| hint.set("Space or Enter toggles".to_owned()),
                on:pointer_leave = move |_| hint.set(String::new())
            ) {
                text {{move || if on.get() { "On" } else { "Off" }}}
            }
            text(class = "wifi__hint") {{move || hint.get()}}
        }
    }
}

const SHEET: &str = css!(
    ".wifi { gap: 8px; }

    .switch {
        padding: 8px 20px;
        border-radius: 999px;
        border: 1px solid #2f3646;
        background-color: #232936;
        text-align: center;
    }

    .switch:hover { background-color: #2b3243; }
    .switch:checked { background-color: #3b6cf6; border-color: #3b6cf6; }
    .switch:focus-visible { outline: 2px solid #7aa2ff; outline-offset: 2px; }

    .wifi__hint { font-size: 12px; color: #6b7689; }"
);
  • control is focusable by default, as are field and editor. Other elements need tabindex = Focus::Sequential.
  • Enter, Space and assistive-technology activation all dispatch click, so one on:click covers them.
  • Hover and focus styling need no listeners. zgui sets :hover and :focus-visible, and the sheet reads them.
  • The enter and leave listeners are needed only because the hint is outside the control, where no selector on the control can reach it.

Propagation

When an event happens, zgui finds the element it is aimed at, the target, and lists the target and all its ancestors, root first. That list is the path.

  • rootdepth 0
    • columndepth 1
      • rowdepth 2
        • controldepth 3 · event target
An event path from the document root to its target

The path follows the document, not the layout boxes. An element with display: contents is on the path. Text nodes are not: a press on a button's label is a press on the button.

The event then travels the path in three phases:

  1. Capture: from the root down to the target's parent. Only :capture listeners run.
  2. Target: at the target. All its listeners run, with or without :capture.
  3. Bubble: from the target's parent back up to the root. Only listeners without :capture run.

On one element in one phase, listeners run in the order they were attached.

An event that does not bubble skips only the bubble phase. The capture phase runs for every event, including pointer_enter, pointer_leave and scroll. That is how a dismissable panel sees every press beneath it first:

// Close the panel when a press lands outside it.
let panel = NodeRef::new();

view! {
    box(
        class = "backdrop",
        on:pointer_down:capture = move |ev| {
            if !panel.contains(ev.target) {
                open.set(false);
            }
        }
    ) {
        box(node_ref = panel, class = "panel") { "…" }
    }
}

Stop an event

stop_propagation() stops the event after the current element's other listeners have run. stop_immediate_propagation() stops it at once. A later handler cannot undo an earlier stop.

The difference matters when one element has several listeners. With nothing focused, keys are aimed at the root element, so a dismissable layer's Escape listener and an application's own Escape listener can share the root. The component library's dismissable layer therefore uses stop_immediate_propagation(), so one Escape closes the top menu and nothing behind it.

Default behaviour

Some events have built-in behaviour:

EventDefault behaviour
pointer_downfocus the nearest focusable element on the path; pressing something unfocusable clears focus
pointer_upwith the primary button, if the release is over the pressed element, dispatch a click on it
wheelscroll the nearest scroll container, passing leftover distance to outer containers
key_down with Tabmove focus to the next element, or the previous one with Shift
key_down with Enter or Spacedispatch a click on the focused element
key_down on an editable elementapply the edit

ev.prevent_default() cancels it. It does not stop propagation. It only works on cancelable events: pointer_down, pointer_up, pointer_move, click, double_click, context_menu, wheel, key_down, key_up, text, ime_start and drop.

Listener modifiers

Write modifiers after the event name, each with its own colon. They combine in any order.

ModifierEffect
:capturerun in the capture phase instead of the bubble phase
:preventcall prevent_default() before the handler
:stopcall stop_propagation() before the handler
:oncerecorded, but nothing acts on it
:passiverecorded, but nothing acts on it
// See a press anywhere below, before the pressed element does.
box(on:pointer_down:capture = move |ev| pressed.set(Some(ev.target)))

// Take over the wheel: the nearest scroll container does not move.
box(on:wheel:prevent = move |ev| {
    zoom.update(|z| *z += ev.delta.to_pixels(zgui::geom::CssPx(16.0)).height.0)
})

// Toggle without the surrounding row seeing the click.
control(on:click:stop = move |_| open.update(|open| *open = !*open))

:once and :passive are Partial· parsed and recorded, and no code reads them. A :once listener is not removed after it runs. To remove a listener, rebuild the element without it, or drop the ListenerGuard returned by NodeRef::listen.

An unknown modifier is a compile error that lists all five. :passive together with :prevent is also a compile error.

Event timing

Events are dispatched at the start of a frame, before style, layout and paint. Hit testing uses the geometry of the last completed frame. As a result:

  • An element created in a handler cannot be hit until the next frame. It has no box yet, but it can still receive events through its ancestors or through focus.
  • Geometry read in a handler, including NodeRef::window_bounds(), is from the last frame. Handlers never trigger layout.
  • Events in one batch see each other's effects. Between events, zgui runs the reactive flush and the queued commands, so a press that opens a dialog and an Escape in the same batch both work.
  • A queued event for a removed element is dropped. If a handler removes an element before the click its press asked for is dispatched, the click is not delivered.

When a frame moves content under a stationary pointer, zgui tests hover again, so :hover follows the content.

Listeners are attached once, when the element is built. Rebuilding an element replaces its listeners rather than adding to them. A dispatch walks only the target's path, not the whole tree. Measurements has the current timings.

Hit testing

Hit testing finds the element under a point. It decides the target, and therefore the path.

zgui keeps a hit index built from the last frame. It searches from the topmost painted item down and takes the first one that:

  1. has pointer-events: auto,
  2. contains the point inside its border box, outside any rounded corner, and
  3. is not clipped away by an ancestor.

Painting order decides what is on top; there is no separate z-index rule for hit testing. A painted piece that belongs to no element (for example, the gap between two lines of a paragraph) resolves to the nearest element above it.

pointer-events has two meaningful values: auto (the default) and anything else, which makes the element unhittable:

.overlay-scrim { pointer-events: none; }

It is inherited. It does not affect painting, layout or accessibility; whatever is behind the element receives the pointer instead. zgui's built-in sheet uses it for :disabled elements and for the empty parts of overlay layers.

Handler argument reference

A handler takes &mut EventCx<'_, E>, where E is the event type (events::Click, events::KeyDown, …). It dereferences to that event's payload:

on:key_down = move |ev| {
    if ev.key == Key::Named(NamedKey::Escape) {   // a payload field, through the deref
        ev.stop_propagation();                     // a method on the context
        close();
    }
}

EventCx also has these fields:

Prop

Type

And these methods:

MethodWhat it does
payload()the whole payload as a Payload enum
coalesced()earlier pointer moves folded into this move, oldest first (see Coalesced pointer moves)
bounds()the current node's box from the last frame; None in a real window, filled only by the test harness. Use NodeRef::window_bounds() instead
stop_propagation()stop after this element's remaining listeners have run
stop_immediate_propagation()stop now; this element's remaining listeners do not run
prevent_default()skip the framework's own behaviour for this event
capture_pointer()send later pointer events to current until released
release_pointer()end that capture
request_focus(node)move focus to node after this dispatch
synthesize(event)dispatch event on current, along the normal path
activate_now()click current now, from a pointer_down handler, so the release does not click it again
retype::<T>()view the same payload as a different event type

Queued commands

capture_pointer, release_pointer, request_focus, synthesize and activate_now are queued and carried out after the current dispatch finishes. The queue is drained in at most eight rounds; a command still pending after that is dropped with a warning.

Commands issued while handling a synthesised event are discarded. click, double_click, pointer_enter, pointer_leave, context_menu and anything sent with ev.synthesize are synthesised, so ev.request_focus(…) inside on:click does nothing. Call focus() on a NodeRef instead.

All events

ev is the handler's argument. It dereferences to the payload type in the second column.

on: nameev derefs toBubblesFires when
pointer_downPointerEventyesa button or contact goes down over the element
pointer_upPointerEventyesa button or contact comes up over the element
pointer_movePointerEventyesthe pointer moves over the element
pointer_enterPointerEventnothe pointer moves onto the element or one of its descendants
pointer_leavePointerEventnothe pointer moves off the element and all of its descendants
pointer_cancelPointerEventyesthe interaction is taken over and will produce no release
clickPointerEventyesthe element is activated: a primary press and release on it, Enter or Space while it has focus, or an assistive technology's activation
double_clickPointerEventyesa second pointer click on the same element, soon and near the first
context_menuPointerEventyesa touch long press, or an assistive technology asks for the element's menu (not a right-click)
wheelWheelEventyesa wheel notch or scroll gesture over the element
key_downKeyEventyesa key goes down while the element has focus
key_upKeyEventyesa key comes up while the element has focus
textTextEventyesnothing produces it today
ime_startImeEventyesan input method starts composing
ime_preeditImeEventyesthe input method's provisional text changes
ime_commitImeEventyesthe input method commits its text
ime_endImeEventyesthe input method stops, discarding any provisional text
focus_inFocusEventyesfocus arrives at the element or one of its descendants
focus_outFocusEventyesfocus leaves the element and all of its descendants
dropDropEventyesfiles are dropped on the window; aimed at the focused element, not the drop point
inputValueEventyesan edit changes an editable element's value
changeValueEventyesfocus leaves an element whose value changed since it was last settled
scrollScrollEventnothe element's scroll offset changed this frame
animation_startAnimationEventyesa declared animation begins, after its delay
animation_iterationAnimationEventyesone iteration ends and the next begins
animation_endAnimationEventyesthe animation finishes
animation_cancelAnimationEventyesthe animation stops before it finishes
transition_runTransitionEventyesa transition is created and waits out its delay
transition_startTransitionEventyesthe value starts moving
transition_endTransitionEventyesthe value arrives
transition_cancelTransitionEventyesthe transition stops before the value arrives

The payload types live in zgui::vocab. You rarely need to name one.

on:text has no producer: text reaches an editable element through key and input-method events.

The same set is available at run time as EventKind, with EventKind::ALL, name(), web_name(), payload_kind(), bubbles(), is_cancelable(), FromStr and Display.

Next

On this page