From ba11ad01d9f9ac85e73c2fc0693c5c2efc6f045f Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:04:21 +0530 Subject: [PATCH 1/9] html events --- CHANGELOG.md | 11 + bindings/rust/blenderui/src/element.rs | 263 ++++++++++++---- bindings/rust/blenderui/src/events.rs | 145 +++++++++ bindings/rust/blenderui/src/layout.rs | 19 +- bindings/rust/blenderui/src/window.rs | 316 +++++++++++++++----- bindings/rust/blenderui/tests/events_dom.rs | 289 ++++++++++++++++++ website/src/content/docs/rust/events.mdx | 64 +++- 7 files changed, 972 insertions(+), 135 deletions(-) create mode 100644 bindings/rust/blenderui/tests/events_dom.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 91041c78..d1562048 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ All notable changes to **blenderui** (BUI). The format follows ## [Unreleased] ### Added +- **Rust: every HTML event, with capture and bubbling.** A listener for each `on*` event: `on_double_click`, + `on_aux_click`, `on_context_menu`, `on_mouse_enter` / `leave` / `over` / `out`, the pointer events + (`on_pointer_down` / `up` / `move` / `enter` / `leave` / `over` / `out` / `cancel` and the pointer capture pair, with a + `PointerEvent`), `on_focus` / `blur` / `focus_in` / `focus_out`, `on_scroll` and `on_wheel`, and a `_capture` twin of + each (`onClickCapture` in `rsx!`) for the pass from the root down to the target. `cx.stop_propagation()` ends the pass it + is in. `window.set_pointer_capture(cx)` holds the pointer for an element, so a drag keeps hearing the moves and the + release outside it; `on_mouse_event` / `on_key_event` / `on_window_event` hear every event of a kind in the window, in + both passes, as gpui's `on_mouse_event` does (`DispatchPhase::Capture` / `Bubble`). A press fires `pointerdown` before + `mousedown`, and a move `pointermove` before `mousemove`. One listener list per element holds them all (a frame + skips the walk for kinds nothing listens for). Not there yet: touch, drag-and-drop, clipboard, media and CSS animation + events, and the JavaScript side of the new ones. `App::simulate_button` clicks with the middle or secondary button in tests. - **Animation: GSAP and Motion on one engine** (feature `anim`, on by default; `BUI_ANIM` in CMake). One C engine in the kit (`kit/intern/anim`, `BUI_anim.h`) runs every animation, so Rust, JavaScript, Python, Lua and C animate the same way and none carries its own. Eases: every name of GSAP, Motion, CSS and Blender, `cubic-bezier()`, diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rs index 91010a27..dda760ea 100644 --- a/bindings/rust/blenderui/src/element.rs +++ b/bindings/rust/blenderui/src/element.rs @@ -15,8 +15,28 @@ pub type SharedString = Cow<'static, str>; /// state across renders. pub type ElementId = SharedString; -/// An event listener, owned by its element (moved into the frame, never shared). -pub(crate) type Listener = Box; +/// One listener: the event it hears, in which pass, and whether it hears the whole window. Owned by its +/// element (moved into the frame, never shared); the closure takes any event type and does nothing +/// with the others, so one list holds every kind of listener. +pub(crate) struct Entry { + pub kind: EventKind, + /// Heard on the way down (the capture pass) rather than on the way up. + pub capture: bool, + /// Hears every event of its kind in the window, wherever it happens (gpui's `on_mouse_event`). + pub wide: bool, + pub call: EntryFn, +} + +/// What an [`Entry`] calls: the event (of any type: the closure picks its own), the pass, the window and the app. +pub(crate) type EntryFn = Box; + +/// The listeners of an element, in the order they were added. +#[derive(Default)] +pub(crate) struct Listeners { + pub entries: Vec, + /// The kinds among `entries` (bits of `EventKind::bit`): a window skips the walk for the rest. + pub kinds: u64, +} /// Work an element postpones until the window can lend itself: it receives /// the window and app and finishes the element (children, styles) in place. @@ -49,18 +69,42 @@ pub(crate) fn resolve_deferred(el: &mut AnyElement, window: &mut Window, app: &m /// Custom painting (gpui's `canvas()` element). pub(crate) type PaintFn = Box, &mut crate::paint::Painter, &App)>; -#[derive(Default)] -pub(crate) struct Listeners { - pub click: Vec>, - pub mouse_down: Vec<(Option, Listener)>, - pub mouse_up: Vec<(Option, Listener)>, - pub mouse_move: Vec>, - pub hover: Vec>, - pub scroll: Vec>, - pub key_down: Vec>, - pub key_up: Vec>, - pub change: Vec>, - pub input: Vec>, +/// The window-wide listeners' event types: which kind each one is. +pub trait WindowEvent: 'static { + const KIND: EventKind; +} +impl WindowEvent for MouseDownEvent { + const KIND: EventKind = EventKind::MouseDown; +} +impl WindowEvent for MouseUpEvent { + const KIND: EventKind = EventKind::MouseUp; +} +impl WindowEvent for MouseMoveEvent { + const KIND: EventKind = EventKind::MouseMove; +} +impl WindowEvent for ScrollWheelEvent { + const KIND: EventKind = EventKind::Wheel; +} +impl WindowEvent for KeyDownEvent { + const KIND: EventKind = EventKind::KeyDown; +} +impl WindowEvent for KeyUpEvent { + const KIND: EventKind = EventKind::KeyUp; +} + +/// `on_x` and `on_x_capture` for each `name, capture_name => Kind, EventType` line. +macro_rules! listeners { + ($( $(#[$doc:meta])* $name:ident, $capture:ident => $kind:ident, $event:ty; )*) => {$( + $(#[$doc])* + pub fn $name(self, f: impl Fn(&$event, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::$kind, false, f) + } + $(#[$doc])* + /// (The capture pass: from the root down to the target.) + pub fn $capture(self, f: impl Fn(&$event, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::$kind, true, f) + } + )*}; } /// An element: a tag, its attributes, styles, children and listeners. @@ -322,58 +366,165 @@ impl Div { } // -- events ---------------------------------------------------------------------------- - /// Click (press and release on this element); bubbles to ancestors. - pub fn on_click(mut self, f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().click.push(Box::new(f)); - self - } - pub fn on_mouse_down(mut self, button: MouseButton, - f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().mouse_down.push((Some(button), Box::new(f))); + // + // HTML's `on*` events, one method each (`onClick` is `.on_click`, in `rsx!` too), and `_capture` for + // the pass that runs from the root down to the target before the usual one back up (`onClickCapture`). + // A listener gets the event, the window and the app; `window.stop_propagation()` ends the pass. + + fn listen(mut self, kind: EventKind, capture: bool, + f: impl Fn(&E, &mut Window, &mut App) + 'static) -> Self { + self.push_entry(Entry { + kind, + capture, + wide: false, + call: Box::new(move |e, _, w, a| { + if let Some(e) = e.downcast_ref::() { + f(e, w, a); + } + }), + }); self } - pub fn on_any_mouse_down(mut self, - f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().mouse_down.push((None, Box::new(f))); - self - } - pub fn on_mouse_up(mut self, button: MouseButton, - f: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().mouse_up.push((Some(button), Box::new(f))); - self + + fn push_entry(&mut self, entry: Entry) { + let ls = self.listeners_mut(); + ls.kinds |= entry.kind.bit(); + ls.entries.push(entry); } - pub fn on_mouse_move(mut self, - f: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().mouse_move.push(Box::new(f)); - self + + /// Hears every event of its kind in the window, whatever element it happens on, in both passes: a + /// drag that leaves its element keeps hearing the moves and the release (gpui's `on_mouse_event`). + /// `E` is the event the listener takes: `MouseMoveEvent`, `MouseDownEvent`, `MouseUpEvent`, + /// `ScrollWheelEvent`, `KeyDownEvent` or `KeyUpEvent`. + pub fn on_mouse_event(self, f: impl Fn(&E, DispatchPhase, &mut Window, &mut App) + 'static) -> Self { + self.on_window_event(E::KIND, f) } - /// Called with `true` when the pointer enters, `false` when it leaves. - pub fn on_hover(mut self, f: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().hover.push(Box::new(f)); - self + + /// [`on_mouse_event`](Self::on_mouse_event) for the keyboard. + pub fn on_key_event(self, f: impl Fn(&E, DispatchPhase, &mut Window, &mut App) + 'static) -> Self { + self.on_window_event(E::KIND, f) } - pub fn on_scroll_wheel(mut self, - f: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().scroll.push(Box::new(f)); + + /// The window-wide listener of any event kind and type (the pointer events take this form). + pub fn on_window_event(mut self, kind: EventKind, + f: impl Fn(&E, DispatchPhase, &mut Window, &mut App) + 'static) -> Self { + self.push_entry(Entry { + kind, + capture: false, + wide: true, + call: Box::new(move |e, phase, w, a| { + if let Some(e) = e.downcast_ref::() { + f(e, phase, w, a); + } + }), + }); self } - pub fn on_key_down(mut self, f: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().key_down.push(Box::new(f)); - self + + /// Press with `button` (and the capture pass of it). + pub fn on_mouse_down(self, button: MouseButton, + f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseDown, false, move |e: &MouseDownEvent, w, a| { + if e.button == button { + f(e, w, a); + } + }) } - pub fn on_key_up(mut self, f: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().key_up.push(Box::new(f)); - self + pub fn on_mouse_down_capture(self, button: MouseButton, + f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseDown, true, move |e: &MouseDownEvent, w, a| { + if e.button == button { + f(e, w, a); + } + }) } - /// Form controls: the committed value changed (`change` in HTML). - pub fn on_change(mut self, f: impl Fn(&ChangeEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().change.push(Box::new(f)); - self + pub fn on_mouse_up(self, button: MouseButton, + f: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseUp, false, move |e: &MouseUpEvent, w, a| { + if e.button == button { + f(e, w, a); + } + }) } - /// Form controls: every edit (`input` in HTML). - pub fn on_input(mut self, f: impl Fn(&ChangeEvent, &mut Window, &mut App) + 'static) -> Self { - self.listeners_mut().input.push(Box::new(f)); - self + pub fn on_mouse_up_capture(self, button: MouseButton, + f: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseUp, true, move |e: &MouseUpEvent, w, a| { + if e.button == button { + f(e, w, a); + } + }) + } + /// Press with any button (`mousedown`). + pub fn on_any_mouse_down(self, f: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::MouseDown, false, f) + } + + /// Called with `true` when the pointer enters, `false` when it leaves (does not bubble). + pub fn on_hover(self, f: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self { + self.listen(EventKind::Hover, false, f) + } + + listeners! { + /// `click`: press and release on this element; bubbles. + on_click, on_click_capture => Click, ClickEvent; + /// `dblclick` + on_double_click, on_double_click_capture => DoubleClick, ClickEvent; + /// `auxclick`: a click with a button other than the main one. + on_aux_click, on_aux_click_capture => AuxClick, ClickEvent; + /// `contextmenu` + on_context_menu, on_context_menu_capture => ContextMenu, ContextMenuEvent; + /// `mousemove` + on_mouse_move, on_mouse_move_capture => MouseMove, MouseMoveEvent; + /// `mouseenter`: this element only (no bubbling, and its children don't count as leaving). + on_mouse_enter, on_mouse_enter_capture => MouseEnter, MouseMoveEvent; + /// `mouseleave` + on_mouse_leave, on_mouse_leave_capture => MouseLeave, MouseMoveEvent; + /// `mouseover`: bubbles, also from the children. + on_mouse_over, on_mouse_over_capture => MouseOver, MouseMoveEvent; + /// `mouseout` + on_mouse_out, on_mouse_out_capture => MouseOut, MouseMoveEvent; + /// `wheel` + on_scroll_wheel, on_scroll_wheel_capture => Wheel, ScrollWheelEvent; + /// `wheel` (HTML's name for `on_scroll_wheel`) + on_wheel, on_wheel_capture => Wheel, ScrollWheelEvent; + /// `pointerdown` + on_pointer_down, on_pointer_down_capture => PointerDown, PointerEvent; + /// `pointerup` + on_pointer_up, on_pointer_up_capture => PointerUp, PointerEvent; + /// `pointermove` + on_pointer_move, on_pointer_move_capture => PointerMove, PointerEvent; + /// `pointerenter` (no bubbling) + on_pointer_enter, on_pointer_enter_capture => PointerEnter, PointerEvent; + /// `pointerleave` + on_pointer_leave, on_pointer_leave_capture => PointerLeave, PointerEvent; + /// `pointerover` + on_pointer_over, on_pointer_over_capture => PointerOver, PointerEvent; + /// `pointerout` + on_pointer_out, on_pointer_out_capture => PointerOut, PointerEvent; + /// `pointercancel` + on_pointer_cancel, on_pointer_cancel_capture => PointerCancel, PointerEvent; + /// `gotpointercapture`: `Window::set_pointer_capture` took the pointer for this element. + on_got_pointer_capture, on_got_pointer_capture_capture => GotPointerCapture, PointerEvent; + /// `lostpointercapture` + on_lost_pointer_capture, on_lost_pointer_capture_capture => LostPointerCapture, PointerEvent; + /// `keydown`: goes to the focused element. + on_key_down, on_key_down_capture => KeyDown, KeyDownEvent; + /// `keyup` + on_key_up, on_key_up_capture => KeyUp, KeyUpEvent; + /// `focus` (no bubbling) + on_focus, on_focus_capture => Focus, FocusEvent; + /// `blur` (no bubbling) + on_blur, on_blur_capture => Blur, FocusEvent; + /// `focusin`: like `focus`, and it bubbles. + on_focus_in, on_focus_in_capture => FocusIn, FocusEvent; + /// `focusout` + on_focus_out, on_focus_out_capture => FocusOut, FocusEvent; + /// `scroll`: this element's scroll position changed (no bubbling). + on_scroll, on_scroll_capture => Scroll, ScrollEvent; + /// Form controls: the committed value changed (`change` in HTML). + on_change, on_change_capture => Change, ChangeEvent; + /// Form controls: every edit (`input` in HTML). + on_input, on_input_capture => Input, ChangeEvent; } // -- state styles (gpui's .hover(|s| ...), CSS :hover / :active / :focus) ---------------- diff --git a/bindings/rust/blenderui/src/events.rs b/bindings/rust/blenderui/src/events.rs index c167bb29..99be4ad4 100644 --- a/bindings/rust/blenderui/src/events.rs +++ b/bindings/rust/blenderui/src/events.rs @@ -94,3 +94,148 @@ pub struct ChangeEvent { /// Numbers, ranges and selects (the selected index). pub number: f64, } + +/// HTML's two passes over the elements an event goes through: down from the root to the target +/// (`Capture`), then back up (`Bubble`). A listener of the whole window hears both. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DispatchPhase { + Capture, + Bubble, +} + +impl DispatchPhase { + #[must_use] + pub const fn bubble(self) -> bool { + matches!(self, Self::Bubble) + } + + #[must_use] + pub const fn capture(self) -> bool { + matches!(self, Self::Capture) + } +} + +/// Which event a listener hears: HTML's `on*` attributes, one for one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum EventKind { + // mouse + Click, + DoubleClick, + AuxClick, + ContextMenu, + MouseDown, + MouseUp, + MouseMove, + MouseEnter, + MouseLeave, + MouseOver, + MouseOut, + Wheel, + // pointer + PointerDown, + PointerUp, + PointerMove, + PointerEnter, + PointerLeave, + PointerOver, + PointerOut, + PointerCancel, + GotPointerCapture, + LostPointerCapture, + // keyboard + KeyDown, + KeyUp, + // focus + Focus, + Blur, + FocusIn, + FocusOut, + // the rest + Scroll, + Hover, + Change, + Input, +} + +impl EventKind { + /// Whether it goes up to the ancestors after the target (`mouseenter`, `focus`, `scroll` ... don't). + #[must_use] + pub const fn bubbles(self) -> bool { + !matches!( + self, + Self::MouseEnter | Self::MouseLeave | Self::PointerEnter | Self::PointerLeave | Self::Focus | Self::Blur + | Self::Scroll | Self::Hover | Self::GotPointerCapture | Self::LostPointerCapture + ) + } + + pub(crate) const fn bit(self) -> u64 { + 1 << self as u8 + } +} + +/// Who a pointer is (HTML's `pointerType`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PointerType { + Mouse, + Pen, + Touch, +} + +/// HTML's `PointerEvent`: what `pointerdown`, `pointermove`, `pointerup`, `pointerenter`, `pointerleave`, +/// `pointerover`, `pointerout`, `pointercancel` and the capture events carry. The mouse is pointer 1. +#[derive(Clone, Debug)] +pub struct PointerEvent { + pub pointer_id: i32, + pub pointer_type: PointerType, + pub is_primary: bool, + /// The button that changed (`None` for moves and the like). + pub button: Option, + /// The buttons held, as the DOM's `buttons` bits: 1 left, 2 right, 4 middle. + pub buttons: u8, + pub position: Point, + pub modifiers: Modifiers, + /// 0.5 while a button is held, else 0 (a mouse has no pressure of its own). + pub pressure: f32, + pub click_count: usize, +} + +impl PointerEvent { + pub(crate) fn mouse(position: Point, button: Option, held: Option, + modifiers: Modifiers, click_count: usize) -> Self { + let bits = |b: MouseButton| match b { + MouseButton::Left => 1, + MouseButton::Right => 2, + MouseButton::Middle => 4, + }; + Self { + pointer_id: 1, + pointer_type: PointerType::Mouse, + is_primary: true, + button, + buttons: held.map_or(0, bits), + position, + modifiers, + pressure: if held.is_some() { 0.5 } else { 0.0 }, + click_count, + } + } +} + +/// `contextmenu`: the secondary button (or the menu key) asked for a context menu. +#[derive(Clone, Debug)] +pub struct ContextMenuEvent { + pub position: Point, + pub modifiers: Modifiers, +} + +/// `focus`, `blur`, `focusin` and `focusout`. +#[derive(Clone, Copy, Debug, Default)] +pub struct FocusEvent; + +/// `scroll`: a scroll container moved. +#[derive(Clone, Debug)] +pub struct ScrollEvent { + /// Where its content is scrolled to (from the top left). + pub offset: Point, +} diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rs index 426cb27a..268b8be5 100644 --- a/bindings/rust/blenderui/src/layout.rs +++ b/bindings/rust/blenderui/src/layout.rs @@ -305,6 +305,8 @@ pub(crate) struct BoxNode { pub(crate) struct Frame { pub nodes: Vec, els: Vec, + /// The kinds of event something in this frame listens for (bits of `EventKind::bit`). + pub listen: u64, pub title: Option, by_key: std::cell::OnceCell>, } @@ -2341,7 +2343,8 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca }); drop(s); let _s = span(Phase::Place); - let mut frame = Frame { nodes, els, title, by_key: Default::default() }; + let listen = els.iter().filter_map(|e| e.listeners.as_deref()).fold(0, |m, l| m | l.kinds); + let mut frame = Frame { nodes, els, listen, title, by_key: Default::default() }; box_of.clear(); for (i, n) in frame.nodes.iter().enumerate() { if let Some(t) = n.taffy { @@ -2569,6 +2572,20 @@ impl Frame { (e != NONE).then(|| &self.els[e as usize]) } + /// The boxes from the root down to box `i` (itself last). + pub(crate) fn path_to(&self, mut i: usize) -> smallvec::SmallVec<[usize; 16]> { + let mut path = smallvec::SmallVec::new(); + loop { + path.push(i); + match self.nodes[i].parent { + Some(p) => i = p, + None => break, + } + } + path.reverse(); + path + } + pub(crate) fn attr(&self, i: usize, name: &str) -> Option<&str> { el_attr(&self.nodes, &self.els, i, name) } diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rs index bde709f3..eeea4ce5 100644 --- a/bindings/rust/blenderui/src/window.rs +++ b/bindings/rust/blenderui/src/window.rs @@ -13,7 +13,7 @@ use std::ffi::{c_char, c_double, c_int, c_void, CStr, CString}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; -use crate::element::{AnyElement, IntoElement, Listener, Listeners, SharedString}; +use crate::element::{AnyElement, IntoElement, SharedString}; use crate::events::*; use crate::geometry::{point, px, size, Bounds, Pixels, Size}; use crate::layout::{id_key, layout, Content, Frame, Key, LayoutCaches, UiState}; @@ -814,6 +814,24 @@ impl App { }); } + /// Click with the middle or the secondary button at (x, y) (as a window sends it: the secondary + /// button's click arrives as its release alone). The left button is [`simulate_click`](Self::simulate_click). + pub fn simulate_button(&mut self, window: WindowId, x: f32, y: f32, button: MouseButton) { + let code = match button { + MouseButton::Left => return self.simulate_click(window, x, y), + MouseButton::Middle => 2, + MouseButton::Right => 3, + }; + self.simulate_mouse_move(window, x, y); + self.input(window, |ctx, s| unsafe { + let (x, y) = ((x * s) as c_int, (y * s) as c_int); + if button == MouseButton::Middle { + sys::BK_button(ctx, x, y, code, 0, 0); + } + sys::BK_button(ctx, x, y, code, 1, 0); + }); + } + /// Press at `from`, drag to `to` and release there. pub fn simulate_drag(&mut self, window: WindowId, from: (f32, f32), to: (f32, f32)) { self.simulate_mouse_move(window, from.0, from.1); @@ -1007,6 +1025,18 @@ pub struct Window { pointer: (f32, f32), pressed: Vec, press_button: MouseButton, + /// How many presses in a row the last one was (a double click's second is 2). + press_count: usize, + /// The element that holds the pointer (HTML's pointer capture): while one does, the pointer's events go + /// to it, wherever the pointer is. + capture: Option, + /// The element whose listener is running (what [`Window::set_pointer_capture`] holds the pointer for). + current: Option, + /// The elements under the pointer, outermost first: the order of what it enters and leaves. + hover_path: Vec, + /// Capture events raised by a listener: fired when the event it is in has gone through (the frame is + /// lent to that one meanwhile). + later: Vec<(EventKind, Key, PointerEvent)>, } impl Window { @@ -1066,6 +1096,11 @@ impl Window { pointer: (-1.0, -1.0), pressed: Vec::new(), press_button: MouseButton::Left, + press_count: 1, + capture: None, + current: None, + hover_path: Vec::new(), + later: Vec::new(), }; if headless { win.scale = sys::BK_scale().max(1.0); @@ -1398,29 +1433,115 @@ impl Window { f.hit_path(x, y, &self.caches.styles).into_iter().map(|i| f.nodes[i].key).collect() } - /// Call the listeners `pick` selects, from element `key` up to the root. - /// The frame is moved out of the window meanwhile, so listeners can take - /// `&mut Window` while the frame lends them out: no copies, no `Rc`. - fn emit(&mut self, app: &mut App, key: Key, e: &E, - pick: impl Fn(&Listeners) -> Vec<&Listener>) { + /// Deliver `e` of `kind` to element `target` as HTML does: down from the root to it (the capture pass), + /// then back up (the bubbling pass, when `kind` bubbles), with the window-wide listeners heard before and + /// after both. A listener that calls `stop_propagation` ends the pass it is in. The frame is moved out + /// of the window meanwhile, so listeners can take `&mut Window` while the frame lends them out: no + /// copies, no `Rc`. + fn fire(&mut self, app: &mut App, kind: EventKind, target: Key, e: &E) { let Some(frame) = self.frame.take() else { return }; + if frame.listen & kind.bit() == 0 { + self.frame = Some(frame); + return; + } app.propagate = true; - let mut cur = frame.by_key().get(&key).copied(); - 'up: while let Some(i) = cur { - if let Some(ls) = frame.el(i).and_then(|e| e.listeners.as_deref()) { - for l in pick(ls) { - l(e, self, app); + let entries = |i: usize| frame.el(i).and_then(|el| el.listeners.as_deref()).map(|l| &l.entries[..]); + let path = frame.by_key().get(&target).map(|&t| frame.path_to(t)).unwrap_or_default(); + let any = e as &dyn std::any::Any; + // every element of the window, for the listeners that hear all of it + let wide = |this: &mut Self, app: &mut App, phase: DispatchPhase| { + for i in 0..frame.nodes.len() { + for en in entries(i).into_iter().flatten().filter(|en| en.wide && en.kind == kind) { + this.current = Some(frame.nodes[i].key); + (en.call)(any, phase, this, app); + if !app.propagate { + return; + } + } + } + }; + wide(self, app, DispatchPhase::Capture); + 'pass: { + if !app.propagate { + break 'pass; + } + for &i in &path { + for en in entries(i).into_iter().flatten().filter(|en| en.capture && !en.wide && en.kind == kind) { + self.current = Some(frame.nodes[i].key); + (en.call)(any, DispatchPhase::Capture, self, app); + if !app.propagate { + break 'pass; + } + } + } + let up = if kind.bubbles() { path.len() } else { path.len().min(1) }; + for &i in path.iter().rev().take(up) { + for en in entries(i).into_iter().flatten().filter(|en| !en.capture && !en.wide && en.kind == kind) { + self.current = Some(frame.nodes[i].key); + (en.call)(any, DispatchPhase::Bubble, self, app); if !app.propagate { - break 'up; + break 'pass; } } } - cur = frame.nodes[i].parent; + wide(self, app, DispatchPhase::Bubble); } app.propagate = true; + self.current = None; if self.frame.is_none() { self.frame = Some(frame); } + self.fire_later(app); + } + + /// The capture events that listeners raised, once the event they were in is done. + fn fire_later(&mut self, app: &mut App) { + while self.frame.is_some() && !self.later.is_empty() { + let (kind, key, e) = self.later.remove(0); + self.fire(app, kind, key, &e); + } + } + + /// Hold the pointer for the element whose listener is running (HTML's `setPointerCapture`): its + /// pointer and mouse events go to that element, also after the pointer left it or the window, until the + /// button is released or [`release_pointer_capture`](Self::release_pointer_capture). A drag starts here. + pub fn set_pointer_capture(&mut self, app: &mut App) { + let Some(key) = self.current else { return }; + if self.capture != Some(key) { + self.release_pointer_capture(app); + self.capture = Some(key); + let held = (!self.pressed.is_empty()).then_some(self.press_button); + let e = self.pointer_event(None, held, 0); + self.later.push((EventKind::GotPointerCapture, key, e)); + self.fire_later(app); + } + } + + /// Let go of the pointer (HTML's `releasePointerCapture`). + pub fn release_pointer_capture(&mut self, app: &mut App) { + if let Some(key) = self.capture.take() { + let held = (!self.pressed.is_empty()).then_some(self.press_button); + let e = self.pointer_event(None, held, 0); + self.later.push((EventKind::LostPointerCapture, key, e)); + self.fire_later(app); + } + } + + /// Whether `key`'s element holds the pointer. + #[must_use] + pub fn has_pointer_capture(&self, key: Key) -> bool { + self.capture == Some(key) + } + + /// A pointer event at the pointer's place. + fn pointer_event(&self, button: Option, held: Option, clicks: usize) -> PointerEvent { + PointerEvent::mouse(point(px(self.pointer.0), px(self.pointer.1)), button, held, Modifiers::default(), clicks) + } + + /// Where the pointer's events go: the element that holds it, else the one under it (else the root, + /// which the window-wide listeners hear through). + fn pointer_target(&self) -> Key { + self.capture.or_else(|| self.state_deepest()).unwrap_or(crate::layout::ROOT_KEY) } fn update_hover(&mut self, app: &mut App, fire: bool) { @@ -1429,12 +1550,14 @@ impl Window { if now == self.state.hovered { return; } - let entered: Vec = now.difference(&self.state.hovered).copied().collect(); - let left: Vec = self.state.hovered.difference(&now).copied().collect(); + let entered: Vec = path.iter().copied().filter(|k| !self.state.hovered.contains(k)).collect(); + let left: Vec = self.hover_path.iter().rev().copied().filter(|k| !now.contains(k)).collect(); + let (old_deepest, new_deepest) = (self.hover_path.last().copied(), path.last().copied()); let restyle = self.frame.as_ref().is_some_and(|f| { entered.iter().chain(&left).any(|k| f.by_key().get(k).is_some()) }); self.state.hovered = now; + self.hover_path = path.clone(); // cursor of the deepest element that sets one if let Some(f) = &self.frame { let cursor = path.iter().rev() @@ -1447,20 +1570,28 @@ impl Window { } } if fire { - // hover listeners don't bubble: each element hears its own enter / leave - for (keys, on) in [(left, false), (entered, true)] { - for k in keys { - let Some(frame) = self.frame.take() else { return }; - let el = frame.by_key().get(&k).and_then(|&i| frame.el(i)); - if let Some(ls) = el.and_then(|e| e.listeners.as_deref()) { - for l in &ls.hover { - l(&on, self, app); - } - } - if self.frame.is_none() { - self.frame = Some(frame); - } - } + // out, leave, over, enter (HTML's order); enter and leave go to each element on its own, so a + // child doesn't make its parent leave + let held = (!self.pressed.is_empty()).then_some(self.press_button); + let pe = self.pointer_event(None, held, 0); + let me = MouseMoveEvent { position: pe.position, pressed_button: held, modifiers: Modifiers::default() }; + if let Some(k) = old_deepest.filter(|_| new_deepest != old_deepest) { + self.fire(app, EventKind::PointerOut, k, &pe); + self.fire(app, EventKind::MouseOut, k, &me); + } + for &k in &left { + self.fire(app, EventKind::PointerLeave, k, &pe); + self.fire(app, EventKind::MouseLeave, k, &me); + self.fire(app, EventKind::Hover, k, &false); + } + if let Some(k) = new_deepest.filter(|_| new_deepest != old_deepest) { + self.fire(app, EventKind::PointerOver, k, &pe); + self.fire(app, EventKind::MouseOver, k, &me); + } + for &k in &entered { + self.fire(app, EventKind::PointerEnter, k, &pe); + self.fire(app, EventKind::MouseEnter, k, &me); + self.fire(app, EventKind::Hover, k, &true); } } if restyle { @@ -1468,7 +1599,7 @@ impl Window { } } - fn pointer_event(&self, text: &str) -> (Modifiers, MouseButton) { + fn parse_pointer(&self, text: &str) -> (Modifiers, MouseButton) { let mut it = text.split_whitespace().map(|v| v.parse::().unwrap_or(0)); let mods = it.next().unwrap_or(0); let button = match it.next().unwrap_or(1) { @@ -1479,14 +1610,26 @@ impl Window { (Modifiers::from_kit(mods), button) } - /// Focus the element `key` (path: its ancestors, for `:focus-within`). - fn set_focus(&mut self, path: &[Key]) { - self.state.focused = path.last().copied(); + /// Focus the element at the end of `path` (its ancestors, for `:focus-within`): `blur` and `focusout` for + /// the one that had it, `focus` and `focusin` for the one that has it now. + fn set_focus(&mut self, app: &mut App, path: &[Key]) { + let (old, new) = (self.state.focused, path.last().copied()); + self.state.focused = new; self.state.focus_path = path.iter().copied().collect(); self.state.focused_id = self.frame.as_ref().and_then(|f| { let i = *f.by_key().get(path.last()?)?; f.el(i)?.id.as_ref().map(|s| s.to_string()) }); + if old != new { + if let Some(k) = old { + self.fire(app, EventKind::Blur, k, &FocusEvent); + self.fire(app, EventKind::FocusOut, k, &FocusEvent); + } + if let Some(k) = new { + self.fire(app, EventKind::Focus, k, &FocusEvent); + self.fire(app, EventKind::FocusIn, k, &FocusEvent); + } + } } fn dispatch(&mut self, ev: RawEvent, app: &mut App) { @@ -1509,12 +1652,14 @@ impl Window { self.request_motion_frame(); // a drag: a redraw, no render } self.update_hover(app, true); - let (modifiers, _) = self.pointer_event(&ev.text); - let pressed = (!self.pressed.is_empty()).then_some(self.press_button); - let e = MouseMoveEvent { position: point(px(x), px(y)), pressed_button: pressed, modifiers }; - if let Some(deepest) = self.state_deepest() { - self.emit(app, deepest, &e, |l| l.mouse_move.iter().collect()); - } + let (modifiers, _) = self.parse_pointer(&ev.text); + let held = (!self.pressed.is_empty()).then_some(self.press_button); + let target = self.pointer_target(); + let mut pe = self.pointer_event(None, held, 0); + pe.modifiers = modifiers; + self.fire(app, EventKind::PointerMove, target, &pe); + let e = MouseMoveEvent { position: point(px(x), px(y)), pressed_button: held, modifiers }; + self.fire(app, EventKind::MouseMove, target, &e); } sys::BK_EV_LEAVE => { self.pointer = (-1.0, -1.0); @@ -1522,52 +1667,73 @@ impl Window { } sys::BK_EV_PRESS | sys::BK_EV_DOUBLE => { self.pointer = (x, y); - let (modifiers, button) = self.pointer_event(&ev.text); + let (modifiers, button) = self.parse_pointer(&ev.text); let path = self.path_at(x, y); self.press_button = button; + self.press_count = if ev.kind == sys::BK_EV_DOUBLE { 2 } else { 1 }; self.state.active = path.iter().copied().collect(); - self.set_focus(&path); + self.set_focus(app, &path); self.pressed = path.clone(); self.dirty = true; self.caches.anim.pointer_down(&path, x, y); - let e = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, - click_count: if ev.kind == sys::BK_EV_DOUBLE { 2 } else { 1 } }; - if let Some(&deepest) = path.last() { - self.emit(app, deepest, &e, |l| l.mouse_down.iter() - .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f).collect()); - } + let target = self.pointer_target(); + let mut pe = self.pointer_event(Some(button), Some(button), self.press_count); + pe.modifiers = modifiers; + self.fire(app, EventKind::PointerDown, target, &pe); + let e = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, click_count: self.press_count }; + self.fire(app, EventKind::MouseDown, target, &e); } sys::BK_EV_RELEASE => { - let (modifiers, button) = self.pointer_event(&ev.text); - let path = self.path_at(x, y); + self.pointer = (x, y); + let (modifiers, button) = self.parse_pointer(&ev.text); + let path = self.capture.map_or_else(|| self.path_at(x, y), |k| self.path_to_key(k)); + let target = path.last().copied().unwrap_or(crate::layout::ROOT_KEY); + let mut pe = self.pointer_event(Some(button), None, self.press_count); + pe.modifiers = modifiers; + self.fire(app, EventKind::PointerUp, target, &pe); let up = MouseUpEvent { button, position: point(px(x), px(y)), modifiers }; - if let Some(&deepest) = path.last() { - self.emit(app, deepest, &up, |l| l.mouse_up.iter() - .filter(|(b, _)| b.is_none_or(|b| b == button)).map(|(_, f)| f).collect()); - } + self.fire(app, EventKind::MouseUp, target, &up); // click: the deepest element under both press and release - let common = self.pressed.iter().zip(&path).take_while(|(a, b)| a == b) - .map(|(a, _)| *a).last(); + let common = if self.pressed.is_empty() { + path.last().copied() // a button a window reports by its release alone + } else { + self.pressed.iter().zip(&path).take_while(|(a, b)| a == b).map(|(a, _)| *a).last() + }; self.pressed.clear(); self.state.active.clear(); self.dirty = true; self.caches.anim.pointer_up(); - if let (Some(target), MouseButton::Left) = (common, button) { - self.toggle_details(target); - let down = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, click_count: 1 }; + if let Some(target) = common { + let down = MouseDownEvent { button, position: point(px(x), px(y)), modifiers, click_count: self.press_count }; let e = ClickEvent { down, up }; - self.emit(app, target, &e, |l| l.click.iter().collect()); + if button == MouseButton::Left { + self.toggle_details(target); + self.fire(app, EventKind::Click, target, &e); + if self.press_count == 2 { + self.fire(app, EventKind::DoubleClick, target, &e); + } + } else { + self.fire(app, EventKind::AuxClick, target, &e); + if button == MouseButton::Right { + let at = point(px(x), px(y)); + self.fire(app, EventKind::ContextMenu, target, &ContextMenuEvent { position: at, modifiers }); + } + } } + // the pointer is let go when its button is + self.release_pointer_capture(app); } sys::BK_EV_WHEEL => { - let (modifiers, _) = self.pointer_event(&ev.text); + let (modifiers, _) = self.parse_pointer(&ev.text); let (px_, py_) = self.pointer; let e = ScrollWheelEvent { position: point(px(px_), px(py_)), delta: ev.a as f32, modifiers }; let path = self.path_at(px_, py_); - if let Some(&deepest) = path.last() { - self.emit(app, deepest, &e, |l| l.scroll.iter().collect()); + let target = path.last().copied().unwrap_or(crate::layout::ROOT_KEY); + self.fire(app, EventKind::Wheel, target, &e); + if let Some((key, at)) = self.scroll_by(&path, -(ev.a as f32) * 40.0, modifiers.shift) { + let e = ScrollEvent { offset: point(px(at.0), px(at.1)) }; + self.fire(app, EventKind::Scroll, key, &e); } - self.scroll_by(&path, -(ev.a as f32) * 40.0, modifiers.shift); } sys::BK_EV_KEY | sys::BK_EV_KEYRELEASE => { let mut parts = ev.text.splitn(2, '\t'); @@ -1578,15 +1744,21 @@ impl Window { let target = self.state.focused.or_else(|| self.state_deepest()) .unwrap_or(crate::layout::ROOT_KEY); if ev.kind == sys::BK_EV_KEY { - self.emit(app, target, &KeyDownEvent { keystroke: ks }, |l| l.key_down.iter().collect()); + self.fire(app, EventKind::KeyDown, target, &KeyDownEvent { keystroke: ks }); } else { - self.emit(app, target, &KeyUpEvent { keystroke: ks }, |l| l.key_up.iter().collect()); + self.fire(app, EventKind::KeyUp, target, &KeyUpEvent { keystroke: ks }); } } _ => {} } } + /// Element keys from the root to the element `key` (empty when it isn't in this frame). + fn path_to_key(&self, key: Key) -> Vec { + let Some(f) = &self.frame else { return Vec::new() }; + f.by_key().get(&key).map_or_else(Vec::new, |&i| f.path_to(i).into_iter().map(|j| f.nodes[j].key).collect()) + } + fn state_deepest(&self) -> Option { self.path_at(self.pointer.0, self.pointer.1).last().copied() } @@ -1612,8 +1784,9 @@ impl Window { } /// Scroll the innermost scroll container along `path` that can move. - fn scroll_by(&mut self, path: &[Key], dy: f32, horizontal: bool) { - let Some(f) = &self.frame else { return }; + /// Returns the container that moved and where it is now. + fn scroll_by(&mut self, path: &[Key], dy: f32, horizontal: bool) -> Option<(Key, (f32, f32))> { + let f = self.frame.as_ref()?; for key in path.iter().rev() { let Some(&i) = f.by_key().get(key) else { continue }; let n = &f.nodes[i]; @@ -1628,9 +1801,10 @@ impl Window { if (nx, ny) != (sx, sy) { self.state.scroll.insert(*key, (nx, ny)); self.dirty = true; - return; + return Some((*key, (nx, ny))); } } + None } fn widget_event(&mut self, ev: RawEvent, app: &mut App) { @@ -1655,8 +1829,8 @@ impl Window { } _ => {} } - self.emit(app, key, &e, |l| l.input.iter().collect()); - self.emit(app, key, &e, |l| l.change.iter().collect()); + self.fire(app, EventKind::Input, key, &e); + self.fire(app, EventKind::Change, key, &e); self.dirty = true; } sys::BK_EV_CLICK => { @@ -1665,7 +1839,7 @@ impl Window { modifiers: Modifiers::default(), click_count: 1 }; let up = MouseUpEvent { button: MouseButton::Left, position: point(px(x), px(y)), modifiers: Modifiers::default() }; - self.emit(app, key, &ClickEvent { down, up }, |l| l.click.iter().collect()); + self.fire(app, EventKind::Click, key, &ClickEvent { down, up }); self.dirty = true; } _ => {} diff --git a/bindings/rust/blenderui/tests/events_dom.rs b/bindings/rust/blenderui/tests/events_dom.rs new file mode 100644 index 00000000..14f2ace3 --- /dev/null +++ b/bindings/rust/blenderui/tests/events_dom.rs @@ -0,0 +1,289 @@ +//! HTML's events: the capture pass before the bubbling one, `stopPropagation`, `mouseenter` against +//! `mouseover`, listeners of the whole window, pointer capture, the pointer events, focus and scroll. + +use std::sync::Mutex; + +use blenderui::prelude::*; + +static LOG: Mutex> = Mutex::new(Vec::new()); + +fn log(s: &str) { + LOG.lock().unwrap().push(s.to_owned()); +} + +fn take() -> Vec { + std::mem::take(&mut *LOG.lock().unwrap()) +} + +/// A tree of three boxes inside each other, a box beside them, and a scroller. +struct Page; + +impl Render for Page { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().id("body").size_full() + .child( + div().id("outer").absolute().left(px(0.0)).top(px(0.0)).w(px(200.0)).h(px(200.0)) + .on_click_capture(|_, _, _| log("outer capture")) + .on_click(|_, _, _| log("outer bubble")) + .on_mouse_enter(|_, _, _| log("outer enter")) + .on_mouse_leave(|_, _, _| log("outer leave")) + .on_mouse_over(|_, _, _| log("outer over")) + .on_mouse_out(|_, _, _| log("outer out")) + .child( + div().id("inner").absolute().left(px(50.0)).top(px(50.0)).w(px(100.0)).h(px(100.0)) + .on_click_capture(|_, _, _| log("inner capture")) + .on_click(|_, _, _| log("inner bubble")) + .on_double_click(|_, _, _| log("inner dblclick")) + .on_aux_click(|_, _, _| log("inner auxclick")) + .on_context_menu(|e, _, _| log(&format!("inner contextmenu {}", e.position.x.0 as i32))) + .on_pointer_down(|_, _, _| log("inner pointerdown")) + .on_any_mouse_down(|_, _, _| log("inner mousedown")) + .on_mouse_enter(|_, _, _| log("inner enter")) + .on_mouse_leave(|_, _, _| log("inner leave")) + .on_mouse_over(|_, _, _| log("inner over")) + .on_mouse_out(|_, _, _| log("inner out")), + ), + ) + .child( + div().id("side").absolute().left(px(300.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_mouse_enter(|_, _, _| log("side enter")), + ) + } +} + +fn open(cx: &mut App) -> WindowId { + blenderui::motion::lag_smoothing(0.0, 0.0); + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(500.0), px(300.0)), + })), + ..Default::default() + }; + let w = cx.open_window(opts, |_, cx| cx.new(|_| Page)).unwrap().id; + cx.draw(w); + w +} + +#[test] +fn passes_and_enter_leave() { + Application::headless().run(|cx| { + let w = open(cx); + // capture runs from the root down, then bubble back up + cx.simulate_click(w, 100.0, 100.0); + let l = take(); + let at = |s: &str| l.iter().position(|x| x == s).unwrap_or(usize::MAX); + assert!(at("outer capture") < at("inner capture") && at("inner capture") < at("inner bubble") + && at("inner bubble") < at("outer bubble"), "click: {l:?}"); + // entering the inner box: over bubbles (and the pointer came from outside everything), enter is + // for each element on its own, outermost first + assert!(l.contains(&"outer enter".to_owned()) && l.contains(&"inner enter".to_owned()), "enter: {l:?}"); + assert!(at("outer enter") < at("inner enter"), "outermost first: {l:?}"); + + // from the inner box to the outer one: the inner box is left, the outer one is not + take(); + cx.simulate_mouse_move(w, 20.0, 20.0); + let l = take(); + assert!(l.contains(&"inner leave".to_owned()) && !l.contains(&"outer leave".to_owned()), "leave: {l:?}"); + assert!(l.contains(&"inner out".to_owned()), "out bubbles from the left box: {l:?}"); + assert!(!l.contains(&"outer enter".to_owned()), "no second enter for the parent: {l:?}"); + + // out of everything + take(); + cx.simulate_mouse_move(w, 450.0, 250.0); + let l = take(); + assert!(l.contains(&"outer leave".to_owned()), "left it: {l:?}"); + }); +} + +#[test] +fn pointer_events_come_before_mouse_events() { + Application::headless().run(|cx| { + let w = open(cx); + take(); + cx.simulate_press(w, 100.0, 100.0); + let l = take(); + let at = |s: &str| l.iter().position(|x| x == s).unwrap_or(usize::MAX); + assert!(at("inner pointerdown") < at("inner mousedown"), "{l:?}"); + cx.simulate_release(w, 100.0, 100.0); + }); +} + +static WIDE: Mutex> = Mutex::new(Vec::new()); + +/// A drag: it takes the pointer on press, and hears the moves and the release wherever they are. +struct Drag; + +impl Render for Drag { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().id("page").size_full() + .child( + div().id("handle").absolute().left(px(10.0)).top(px(10.0)).w(px(50.0)).h(px(50.0)) + .on_pointer_down(|_, window, app| { + window.set_pointer_capture(app); + WIDE.lock().unwrap().push("down".into()); + }) + .on_pointer_move(|e, _, _| WIDE.lock().unwrap().push(format!("move {}", e.position.x.0 as i32))) + .on_pointer_up(|_, _, _| WIDE.lock().unwrap().push("up".into())) + .on_got_pointer_capture(|_, _, _| WIDE.lock().unwrap().push("got".into())) + .on_lost_pointer_capture(|_, _, _| WIDE.lock().unwrap().push("lost".into())), + ) + .child( + // hears everything in the window, in both passes + div().id("watcher") + .on_mouse_event(|e: &MouseMoveEvent, phase, _, _| { + WIDE.lock().unwrap().push(format!("wide {:?} {}", phase, e.position.x.0 as i32)); + }), + ) + } +} + +#[test] +fn pointer_capture_and_window_wide_listeners() { + Application::headless().run(|cx| { + blenderui::motion::lag_smoothing(0.0, 0.0); + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(500.0), px(300.0)), + })), + ..Default::default() + }; + let w = cx.open_window(opts, |_, cx| cx.new(|_| Drag)).unwrap().id; + cx.draw(w); + cx.simulate_mouse_move(w, 30.0, 30.0); + WIDE.lock().unwrap().clear(); + cx.simulate_press(w, 30.0, 30.0); + // far outside the handle: the handle still hears the pointer + cx.simulate_mouse_move(w, 400.0, 200.0); + cx.simulate_release(w, 400.0, 200.0); + let l = std::mem::take(&mut *WIDE.lock().unwrap()); + assert!(l.contains(&"got".to_owned()), "took the pointer: {l:?}"); + assert!(l.contains(&"move 400".to_owned()), "heard a move far outside: {l:?}"); + assert!(l.contains(&"up".to_owned()), "and the release: {l:?}"); + assert!(l.contains(&"lost".to_owned()), "and let go with the button: {l:?}"); + // the window-wide listener: capture pass before bubble pass, for a move anywhere + let cap = l.iter().position(|x| x == "wide Capture 400"); + let bub = l.iter().position(|x| x == "wide Bubble 400"); + assert!(cap.is_some() && bub.is_some() && cap < bub, "both passes: {l:?}"); + + // without capture, the handle hears nothing far away + WIDE.lock().unwrap().clear(); + cx.simulate_mouse_move(w, 450.0, 250.0); + let l = std::mem::take(&mut *WIDE.lock().unwrap()); + assert!(!l.iter().any(|x| x.starts_with("move")), "no capture, no move: {l:?}"); + }); +} + +struct Stop; + +impl Render for Stop { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().id("a").size_full() + .on_click(|_, _, _| log("a bubble")) + .child( + div().id("b").absolute().left(px(0.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_click_capture(|_, _, app| { + log("b capture"); + app.stop_propagation(); + }) + .on_click(|_, _, _| log("b bubble")) + .child(div().id("c").size_full().on_click(|_, _, _| log("c bubble"))), + ) + } +} + +#[test] +fn stop_propagation_in_the_capture_pass() { + Application::headless().run(|cx| { + blenderui::motion::lag_smoothing(0.0, 0.0); + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Stop)).unwrap().id; + cx.draw(w); + take(); + cx.simulate_click(w, 50.0, 50.0); + assert_eq!(take(), ["b capture"], "stopped on the way down: nothing below or after it hears the click"); + }); +} + +struct Focus; + +impl Render for Focus { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div().id("page").size_full() + .child(div().id("one").absolute().left(px(0.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_focus(|_, _, _| log("one focus")).on_blur(|_, _, _| log("one blur")) + .on_focus_in(|_, _, _| log("one focusin")).on_focus_out(|_, _, _| log("one focusout"))) + .child(div().id("two").absolute().left(px(200.0)).top(px(0.0)).w(px(100.0)).h(px(100.0)) + .on_focus(|_, _, _| log("two focus")).on_blur(|_, _, _| log("two blur"))) + .child( + div().id("scroller").absolute().left(px(0.0)).top(px(150.0)).w(px(100.0)).h(px(100.0)) + .overflow_y_scroll() + .on_scroll(|e, _, _| log(&format!("scroll {}", e.offset.y.0 as i32))) + .child(div().h(px(500.0)).w(px(50.0))), + ) + } +} + +#[test] +fn focus_and_scroll() { + Application::headless().run(|cx| { + blenderui::motion::lag_smoothing(0.0, 0.0); + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Focus)).unwrap().id; + cx.draw(w); + take(); + cx.simulate_click(w, 50.0, 50.0); + assert_eq!(take(), ["one focus", "one focusin"], "focused"); + cx.simulate_click(w, 250.0, 50.0); + assert_eq!(take(), ["one blur", "one focusout", "two focus"], "focus moves: out of one, into two"); + cx.simulate_scroll(w, 50.0, 200.0, -1); + let l = take(); + assert!(l.iter().any(|x| x.starts_with("scroll ") && x != "scroll 0"), "the scroller scrolled: {l:?}"); + }); +} + +#[test] +fn double_click_and_the_other_buttons() { + Application::headless().run(|cx| { + let w = open(cx); + take(); + cx.simulate_click(w, 100.0, 100.0); + cx.simulate_click(w, 100.0, 100.0); + let l = take(); + assert_eq!(l.iter().filter(|x| *x == "inner bubble").count(), 2, "two clicks: {l:?}"); + assert_eq!(l.iter().filter(|x| *x == "inner dblclick").count(), 1, "one double click: {l:?}"); + + take(); + cx.simulate_button(w, 100.0, 100.0, MouseButton::Right); + let l = take(); + assert!(l.contains(&"inner auxclick".to_owned()) && l.contains(&"inner contextmenu 100".to_owned()), "{l:?}"); + assert!(!l.contains(&"inner bubble".to_owned()), "a right click isn't a click: {l:?}"); + }); +} + +struct Rsx; + +impl Render for Rsx { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + rsx! { +
+
+
+ } + } +} + +#[test] +fn rsx_spellings() { + Application::headless().run(|cx| { + blenderui::motion::lag_smoothing(0.0, 0.0); + let w = cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Rsx)).unwrap().id; + cx.draw(w); + take(); + cx.simulate_click(w, 20.0, 20.0); + let l = take(); + assert!(l.contains(&"rsx pointerdown".to_owned()) && l.contains(&"rsx enter".to_owned()), "{l:?}"); + let at = |s: &str| l.iter().position(|x| x == s).unwrap_or(usize::MAX); + assert!(at("rsx capture") < at("rsx bubble"), "{l:?}"); + }); +} diff --git a/website/src/content/docs/rust/events.mdx b/website/src/content/docs/rust/events.mdx index 04abd684..37269f27 100644 --- a/website/src/content/docs/rust/events.mdx +++ b/website/src/content/docs/rust/events.mdx @@ -1,10 +1,10 @@ --- title: Events -description: Respond to clicks, keys, the wheel and form changes, update your view with cx.listener, and paint your own content on a canvas. +description: Respond to every HTML event (mouse, pointer, keys, focus, wheel, scroll, form changes), with capture and bubbling, pointer capture and window-wide listeners, update your view with cx.listener, and paint your own content on a canvas. section: Rust order: 70 languages: ["rust"] -sources: ["docs/rust.md", "bindings/rust/blenderui/src/events.rs", "bindings/rust/blenderui/src/element.rs", "bindings/rust/blenderui/src/window.rs", "bindings/rust/blenderui/src/paint.rs", "bindings/rust/blenderui-macros/src/rsx.rs", "bindings/rust/blenderui/tests/headless.rs", "bindings/rust/blenderui/examples/showcase.rs"] +sources: ["docs/rust.md", "bindings/rust/blenderui/src/events.rs", "bindings/rust/blenderui/src/element.rs", "bindings/rust/blenderui/src/window.rs", "bindings/rust/blenderui/src/paint.rs", "bindings/rust/blenderui-macros/src/rsx.rs", "bindings/rust/blenderui/tests/headless.rs", "bindings/rust/blenderui/tests/events_dom.rs", "bindings/rust/blenderui/examples/showcase.rs"] --- A UI that doesn't answer back is just a picture. **Events are how your code hears the user**: a click, a key, a dragged slider. Attach a listener to any element, change your state, and BUI redraws what changed. @@ -41,22 +41,40 @@ If you use [hooks](../hooks/) instead, you don't need either: writing a signal r ## Every listener +Every HTML `on*` event has a listener, named the same in snake case (`onPointerDown` is `.on_pointer_down`). A listener gets the event, the `Window` and the `App`. + | Listener | Event | Bubbles | | --- | --- | --- | | `on_click` | `ClickEvent { down, up }`: a press and release on the element | Yes | +| `on_double_click` | `ClickEvent` (`click_count()` is 2) | Yes | +| `on_aux_click` | `ClickEvent`: a click with the middle or secondary button | Yes | +| `on_context_menu` | `ContextMenuEvent { position, modifiers }` | Yes | | `on_mouse_down(button, f)`, `on_any_mouse_down(f)` | `MouseDownEvent { button, position, modifiers, click_count }` | Yes | | `on_mouse_up(button, f)` | `MouseUpEvent { button, position, modifiers }` | Yes | | `on_mouse_move` | `MouseMoveEvent { position, pressed_button, modifiers }` | Yes | +| `on_mouse_enter`, `on_mouse_leave` | `MouseMoveEvent`: this element only; moving into a child doesn't leave it | No | +| `on_mouse_over`, `on_mouse_out` | `MouseMoveEvent`: also from the children | Yes | | `on_hover` | `bool`: `true` when the pointer enters, `false` when it leaves | No | -| `on_scroll_wheel` | `ScrollWheelEvent { position, delta, modifiers }` | Yes | +| `on_pointer_down`, `on_pointer_up`, `on_pointer_move` | `PointerEvent` | Yes | +| `on_pointer_enter`, `on_pointer_leave` | `PointerEvent` | No | +| `on_pointer_over`, `on_pointer_out`, `on_pointer_cancel` | `PointerEvent` | Yes | +| `on_got_pointer_capture`, `on_lost_pointer_capture` | `PointerEvent` | No | +| `on_scroll_wheel` (or `on_wheel`) | `ScrollWheelEvent { position, delta, modifiers }` | Yes | +| `on_scroll` | `ScrollEvent { offset }`: a scroll container moved | No | | `on_key_down`, `on_key_up` | `KeyDownEvent` / `KeyUpEvent { keystroke }` | Yes, from the focused element | +| `on_focus`, `on_blur` | `FocusEvent` | No | +| `on_focus_in`, `on_focus_out` | `FocusEvent` | Yes | | `on_change`, `on_input` | `ChangeEvent { value, checked, number }` | Yes | +Each has a `_capture` twin (`on_click_capture` …) that hears the event on the way down, before the target (see [the two passes](#the-two-passes)). Touch, drag-and-drop, clipboard, media and CSS animation events (`touchstart`, `dragstart`, `paste`, `ended`, `transitionend` …) are not there yet. + The details: - **Positions** are in logical pixels (they don't change with display scaling). - **`MouseButton`** is `Left`, `Right` or `Middle`. - **`Modifiers`** has `shift`, `control` and `alt`. +- **`PointerEvent`** has `pointer_id` (the mouse is 1), `pointer_type`, `is_primary`, `button`, `buttons` (bits: 1 left, 2 right, 4 middle), `position`, `modifiers`, `pressure` and `click_count`. A press fires `pointerdown` and then `mousedown`; a move fires `pointermove` and then `mousemove`. +- **`on_context_menu` and `on_aux_click`** run when the secondary or middle button is released (a window reports the secondary button's click that way). - **`ClickEvent::click_count()`** tells a double-click from a single one. - **`ScrollWheelEvent::delta`** is in lines; positive scrolls the content up (the wheel turned away from you). - **`Keystroke`** has `key` (the key's name: `"a"`, `"Return"`, `"Left"` …), `key_char` (the typed text, if any) and `modifiers`. @@ -74,11 +92,19 @@ rsx! { } ``` -## Focus and bubbling +## The two passes + +An event goes through the elements twice, as in a browser. First down from the root to the target (the **capture** pass, the `_capture` listeners), then back up (the **bubbling** pass, the ordinary listeners). `cx.stop_propagation()` ends the pass it is called in, so a capture listener can keep an event from reaching its target. -- **Clicking an element focuses it.** Key events go to the focused element, then bubble up through its ancestors. -- **Most events bubble**: a click on a `` inside a `