Skip to main content

strata_dom/
events.rs

1//! W3C-compliant synthetic event pipeline with 3-phase capturing and bubbling dispatch.
2
3use std::cell::Cell;
4use std::ops::Deref;
5
6/// Standard synthetic event types.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8pub enum EventType {
9    Click,
10    DblClick,
11    /// W3C `contextmenu`: fired for a secondary-button press on the nearest listening element.
12    ContextMenu,
13    AuxClick,
14    MouseDown,
15    MouseUp,
16    MouseMove,
17    MouseEnter,
18    MouseLeave,
19    MouseOver,
20    MouseOut,
21    PointerDown,
22    PointerUp,
23    PointerMove,
24    KeyDown,
25    KeyUp,
26    Input,
27    Change,
28    Submit,
29    Focus,
30    Blur,
31    Wheel,
32    Scroll,
33    DragStart,
34    Drag,
35    DragEnter,
36    DragOver,
37    DragLeave,
38    Drop,
39    DragEnd,
40    TransitionRun,
41    TransitionStart,
42    TransitionEnd,
43    TransitionCancel,
44    AnimationStart,
45    AnimationIteration,
46    AnimationEnd,
47    AnimationCancel,
48    Resize,
49    Custom(&'static str),
50}
51
52/// The three dispatch phases of the W3C DOM Event Model.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum EventPhase {
55    None,
56    Capturing,
57    AtTarget,
58    Bubbling,
59}
60
61/// Synthetic DOM Event passed to event handlers, fully modeled after W3C DOM Level 3 / UI Events.
62#[derive(Clone, Debug)]
63pub struct Event {
64    pub event_type: EventType,
65    pub phase: Cell<EventPhase>,
66    pub target_id: Option<u32>,
67    pub current_target_id: Cell<Option<u32>>,
68    pub propagation_stopped: std::rc::Rc<Cell<bool>>,
69    pub default_prevented: std::rc::Rc<Cell<bool>>,
70
71    // Text & Form Value Properties
72    pub value: String,
73    pub data: Option<String>,
74    pub input_type: String,
75
76    // Mouse & Pointer Coordinate Properties (W3C MouseEvent / PointerEvent)
77    pub client_x: f64,
78    pub client_y: f64,
79    pub screen_x: f64,
80    pub screen_y: f64,
81    pub page_x: f64,
82    pub page_y: f64,
83    pub offset_x: f64,
84    pub offset_y: f64,
85    pub movement_x: f64,
86    pub movement_y: f64,
87    pub button: i16,
88    pub buttons: u16,
89    pub detail: i32,
90    pub pointer_id: i32,
91    /// W3C Pointer Events Level 3 `pointerType` (`"mouse"`, `"touch"`, or `"pen"`).
92    pub pointer_type: &'static str,
93    /// Normalized contact pressure in `[0.0, 1.0]` (`0.5` for standard mouse down, analog for pen).
94    pub pressure: f32,
95    /// Barrel tangential pressure / airbrush wheel in `[-1.0, 1.0]`.
96    pub tangential_pressure: f32,
97    /// Stylus X-axis tilt in degrees (`-90.0..=90.0`).
98    pub tilt_x: f32,
99    /// Stylus Y-axis tilt in degrees (`-90.0..=90.0`).
100    pub tilt_y: f32,
101    /// Clockwise stylus barrel rotation in degrees (`0.0..=359.0`).
102    pub twist: f32,
103    /// `true` if this pointer represents the primary contact of its pointer type.
104    pub is_primary: bool,
105    pub pointer_capture_requested: std::rc::Rc<Cell<Option<bool>>>,
106    pub cursor_warp_requested: std::rc::Rc<Cell<Option<(f64, f64)>>>,
107
108    // Element Layout & Scroll Measurement Properties (ResizeObserver / onresize / onscroll)
109    pub width: f64,
110    pub height: f64,
111    pub scroll_top: f64,
112    pub scroll_left: f64,
113    pub scroll_height: f64,
114    pub scroll_width: f64,
115    pub client_height: f64,
116    pub client_width: f64,
117
118    // Drag-and-Drop & FileDrop Properties (W3C DragEvent / DataTransfer)
119    pub files: Vec<std::path::PathBuf>,
120    pub data_transfer: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<String, String>>>,
121
122    // Keyboard Properties (W3C KeyboardEvent)
123    pub key: String,
124    pub code: String,
125    pub repeat: bool,
126    pub location: u32,
127
128    // Modifier Keys
129    pub ctrl_key: bool,
130    pub shift_key: bool,
131    pub alt_key: bool,
132    pub meta_key: bool,
133
134    // Wheel Properties (W3C WheelEvent)
135    pub delta_x: f64,
136    pub delta_y: f64,
137    pub delta_z: f64,
138    pub delta_mode: u32,
139
140    // Event Timestamp in Milliseconds
141    pub timestamp: f64,
142
143    // Transition & Animation Event Properties (W3C CSS Transitions & Animations)
144    pub property_name: String,
145    pub animation_name: String,
146    pub elapsed_time: f32,
147}
148
149impl Default for Event {
150    fn default() -> Self {
151        Self {
152            event_type: EventType::Click,
153            phase: Cell::new(EventPhase::None),
154            target_id: None,
155            current_target_id: Cell::new(None),
156            propagation_stopped: std::rc::Rc::new(Cell::new(false)),
157            default_prevented: std::rc::Rc::new(Cell::new(false)),
158            value: String::new(),
159            data: None,
160            input_type: String::new(),
161            client_x: 0.0,
162            client_y: 0.0,
163            screen_x: 0.0,
164            screen_y: 0.0,
165            page_x: 0.0,
166            page_y: 0.0,
167            offset_x: 0.0,
168            offset_y: 0.0,
169            movement_x: 0.0,
170            movement_y: 0.0,
171            button: 0,
172            buttons: 0,
173            detail: 0,
174            pointer_id: 1,
175            pointer_type: "mouse",
176            pressure: 0.0,
177            tangential_pressure: 0.0,
178            tilt_x: 0.0,
179            tilt_y: 0.0,
180            twist: 0.0,
181            is_primary: true,
182            pointer_capture_requested: std::rc::Rc::new(Cell::new(None)),
183            cursor_warp_requested: std::rc::Rc::new(Cell::new(None)),
184            width: 0.0,
185            height: 0.0,
186            scroll_top: 0.0,
187            scroll_left: 0.0,
188            scroll_height: 0.0,
189            scroll_width: 0.0,
190            client_height: 0.0,
191            client_width: 0.0,
192            files: Vec::new(),
193            data_transfer: std::rc::Rc::new(std::cell::RefCell::new(
194                std::collections::HashMap::new(),
195            )),
196            key: String::new(),
197            code: String::new(),
198            repeat: false,
199            location: 0,
200            ctrl_key: false,
201            shift_key: false,
202            alt_key: false,
203            meta_key: false,
204            delta_x: 0.0,
205            delta_y: 0.0,
206            delta_z: 0.0,
207            delta_mode: 0,
208            timestamp: 0.0,
209            property_name: String::new(),
210            animation_name: String::new(),
211            elapsed_time: 0.0,
212        }
213    }
214}
215
216impl Event {
217    pub fn new(event_type: EventType) -> Self {
218        Self {
219            event_type,
220            ..Default::default()
221        }
222    }
223
224    /// Stores a key/value payload in the shared drag-and-drop `DataTransfer` store.
225    pub fn set_data(&self, format: impl Into<String>, data: impl Into<String>) {
226        self.data_transfer
227            .borrow_mut()
228            .insert(format.into(), data.into());
229    }
230
231    /// Retrieves a payload by format key from the shared drag-and-drop `DataTransfer` store.
232    pub fn get_data(&self, format: &str) -> Option<String> {
233        self.data_transfer.borrow().get(format).cloned()
234    }
235
236    /// Requests pointer capture on the current event target for `pointer_id` so subsequent
237    /// `PointerMove`/`MouseMove` and `PointerUp`/`MouseUp` events continue firing even outside bounds.
238    pub fn set_pointer_capture(&self, _pointer_id: i32) {
239        self.pointer_capture_requested.set(Some(true));
240    }
241
242    /// Releases an active pointer capture on the current event target.
243    pub fn release_pointer_capture(&self, _pointer_id: i32) {
244        self.pointer_capture_requested.set(Some(false));
245    }
246
247    /// Requests warping the OS pointer to window-local coordinates `(x, y)` and
248    /// suppresses the resulting synthetic jump from `movement_x` / `movement_y`.
249    pub fn set_cursor_position(&self, x: f64, y: f64) {
250        self.cursor_warp_requested.set(Some((x, y)));
251    }
252
253    /// Alias for [`Event::set_cursor_position`].
254    pub fn warp_cursor(&self, x: f64, y: f64) {
255        self.set_cursor_position(x, y);
256    }
257
258    pub fn with_value(event_type: EventType, val: impl Into<String>) -> Self {
259        Self {
260            event_type,
261            value: val.into(),
262            ..Default::default()
263        }
264    }
265
266    pub fn transition(
267        event_type: EventType,
268        property: impl Into<String>,
269        elapsed_time: f32,
270    ) -> Self {
271        Self {
272            event_type,
273            property_name: property.into(),
274            elapsed_time,
275            ..Default::default()
276        }
277    }
278
279    pub fn animation(
280        event_type: EventType,
281        animation_name: impl Into<String>,
282        elapsed_time: f32,
283    ) -> Self {
284        Self {
285            event_type,
286            animation_name: animation_name.into(),
287            elapsed_time,
288            ..Default::default()
289        }
290    }
291
292    pub fn stop_propagation(&self) {
293        self.propagation_stopped.set(true);
294    }
295
296    pub fn prevent_default(&self) {
297        self.default_prevented.set(true);
298    }
299
300    pub fn is_propagation_stopped(&self) -> bool {
301        self.propagation_stopped.get()
302    }
303
304    pub fn is_default_prevented(&self) -> bool {
305        self.default_prevented.get()
306    }
307
308    pub fn phase(&self) -> EventPhase {
309        self.phase.get()
310    }
311
312    pub fn current_target(&self) -> Option<u32> {
313        self.current_target_id.get()
314    }
315
316    /// Returns true if this event was initiated by the primary (usually left) mouse button.
317    pub fn is_primary(&self) -> bool {
318        self.button == 0
319    }
320
321    /// Returns true if this event was initiated by the auxiliary (usually middle) mouse button.
322    pub fn is_auxiliary(&self) -> bool {
323        self.button == 1
324    }
325
326    /// Returns true if this event was initiated by the secondary (usually right) mouse button.
327    pub fn is_secondary(&self) -> bool {
328        self.button == 2
329    }
330
331    /// Returns true if any keyboard modifier key (Ctrl, Shift, Alt, or Meta) was held.
332    pub fn has_modifier(&self) -> bool {
333        self.ctrl_key || self.shift_key || self.alt_key || self.meta_key
334    }
335}
336
337impl Deref for Event {
338    type Target = str;
339    fn deref(&self) -> &Self::Target {
340        &self.value
341    }
342}
343
344/// Dispatches a synthetic event across a node tree ancestry path.
345pub struct EventDispatcher;
346
347impl EventDispatcher {
348    /// Dispatches an event through Capturing, AtTarget, and Bubbling phases.
349    /// `ancestry_path` must be ordered from Root (index 0) to Target element (last index).
350    pub fn dispatch<F>(ancestry_path: &[u32], event: &Event, mut listener_invoker: F)
351    where
352        F: FnMut(u32, EventPhase, &Event),
353    {
354        if ancestry_path.is_empty() {
355            return;
356        }
357
358        let target_node = *ancestry_path.last().unwrap();
359
360        // 1. Capturing Phase: Root down to target's parent
361        event.phase.set(EventPhase::Capturing);
362        if ancestry_path.len() > 1 {
363            for &node_id in &ancestry_path[..ancestry_path.len() - 1] {
364                if event.is_propagation_stopped() {
365                    return;
366                }
367                event.current_target_id.set(Some(node_id));
368                listener_invoker(node_id, EventPhase::Capturing, event);
369            }
370        }
371
372        // 2. At Target Phase
373        if event.is_propagation_stopped() {
374            return;
375        }
376        event.phase.set(EventPhase::AtTarget);
377        event.current_target_id.set(Some(target_node));
378        listener_invoker(target_node, EventPhase::AtTarget, event);
379
380        // 3. Bubbling Phase: Target's parent up to Root
381        if event.is_propagation_stopped() {
382            return;
383        }
384        event.phase.set(EventPhase::Bubbling);
385        if ancestry_path.len() > 1 {
386            for &node_id in ancestry_path[..ancestry_path.len() - 1].iter().rev() {
387                if event.is_propagation_stopped() {
388                    return;
389                }
390                event.current_target_id.set(Some(node_id));
391                listener_invoker(node_id, EventPhase::Bubbling, event);
392            }
393        }
394    }
395}