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    pub pointer_capture_requested: std::rc::Rc<Cell<Option<bool>>>,
92    pub cursor_warp_requested: std::rc::Rc<Cell<Option<(f64, f64)>>>,
93
94    // Element Layout & Scroll Measurement Properties (ResizeObserver / onresize / onscroll)
95    pub width: f64,
96    pub height: f64,
97    pub scroll_top: f64,
98    pub scroll_left: f64,
99    pub scroll_height: f64,
100    pub scroll_width: f64,
101    pub client_height: f64,
102    pub client_width: f64,
103
104    // Drag-and-Drop & FileDrop Properties (W3C DragEvent / DataTransfer)
105    pub files: Vec<std::path::PathBuf>,
106    pub data_transfer: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<String, String>>>,
107
108    // Keyboard Properties (W3C KeyboardEvent)
109    pub key: String,
110    pub code: String,
111    pub repeat: bool,
112    pub location: u32,
113
114    // Modifier Keys
115    pub ctrl_key: bool,
116    pub shift_key: bool,
117    pub alt_key: bool,
118    pub meta_key: bool,
119
120    // Wheel Properties (W3C WheelEvent)
121    pub delta_x: f64,
122    pub delta_y: f64,
123    pub delta_z: f64,
124    pub delta_mode: u32,
125
126    // Event Timestamp in Milliseconds
127    pub timestamp: f64,
128
129    // Transition & Animation Event Properties (W3C CSS Transitions & Animations)
130    pub property_name: String,
131    pub animation_name: String,
132    pub elapsed_time: f32,
133}
134
135impl Default for Event {
136    fn default() -> Self {
137        Self {
138            event_type: EventType::Click,
139            phase: Cell::new(EventPhase::None),
140            target_id: None,
141            current_target_id: Cell::new(None),
142            propagation_stopped: std::rc::Rc::new(Cell::new(false)),
143            default_prevented: std::rc::Rc::new(Cell::new(false)),
144            value: String::new(),
145            data: None,
146            input_type: String::new(),
147            client_x: 0.0,
148            client_y: 0.0,
149            screen_x: 0.0,
150            screen_y: 0.0,
151            page_x: 0.0,
152            page_y: 0.0,
153            offset_x: 0.0,
154            offset_y: 0.0,
155            movement_x: 0.0,
156            movement_y: 0.0,
157            button: 0,
158            buttons: 0,
159            detail: 0,
160            pointer_id: 1,
161            pointer_capture_requested: std::rc::Rc::new(Cell::new(None)),
162            cursor_warp_requested: std::rc::Rc::new(Cell::new(None)),
163            width: 0.0,
164            height: 0.0,
165            scroll_top: 0.0,
166            scroll_left: 0.0,
167            scroll_height: 0.0,
168            scroll_width: 0.0,
169            client_height: 0.0,
170            client_width: 0.0,
171            files: Vec::new(),
172            data_transfer: std::rc::Rc::new(std::cell::RefCell::new(
173                std::collections::HashMap::new(),
174            )),
175            key: String::new(),
176            code: String::new(),
177            repeat: false,
178            location: 0,
179            ctrl_key: false,
180            shift_key: false,
181            alt_key: false,
182            meta_key: false,
183            delta_x: 0.0,
184            delta_y: 0.0,
185            delta_z: 0.0,
186            delta_mode: 0,
187            timestamp: 0.0,
188            property_name: String::new(),
189            animation_name: String::new(),
190            elapsed_time: 0.0,
191        }
192    }
193}
194
195impl Event {
196    pub fn new(event_type: EventType) -> Self {
197        Self {
198            event_type,
199            ..Default::default()
200        }
201    }
202
203    /// Stores a key/value payload in the shared drag-and-drop `DataTransfer` store.
204    pub fn set_data(&self, format: impl Into<String>, data: impl Into<String>) {
205        self.data_transfer
206            .borrow_mut()
207            .insert(format.into(), data.into());
208    }
209
210    /// Retrieves a payload by format key from the shared drag-and-drop `DataTransfer` store.
211    pub fn get_data(&self, format: &str) -> Option<String> {
212        self.data_transfer.borrow().get(format).cloned()
213    }
214
215    /// Requests pointer capture on the current event target for `pointer_id` so subsequent
216    /// `PointerMove`/`MouseMove` and `PointerUp`/`MouseUp` events continue firing even outside bounds.
217    pub fn set_pointer_capture(&self, _pointer_id: i32) {
218        self.pointer_capture_requested.set(Some(true));
219    }
220
221    /// Releases an active pointer capture on the current event target.
222    pub fn release_pointer_capture(&self, _pointer_id: i32) {
223        self.pointer_capture_requested.set(Some(false));
224    }
225
226    /// Requests warping the OS pointer to window-local coordinates `(x, y)` and
227    /// suppresses the resulting synthetic jump from `movement_x` / `movement_y`.
228    pub fn set_cursor_position(&self, x: f64, y: f64) {
229        self.cursor_warp_requested.set(Some((x, y)));
230    }
231
232    /// Alias for [`Event::set_cursor_position`].
233    pub fn warp_cursor(&self, x: f64, y: f64) {
234        self.set_cursor_position(x, y);
235    }
236
237    pub fn with_value(event_type: EventType, val: impl Into<String>) -> Self {
238        Self {
239            event_type,
240            value: val.into(),
241            ..Default::default()
242        }
243    }
244
245    pub fn transition(
246        event_type: EventType,
247        property: impl Into<String>,
248        elapsed_time: f32,
249    ) -> Self {
250        Self {
251            event_type,
252            property_name: property.into(),
253            elapsed_time,
254            ..Default::default()
255        }
256    }
257
258    pub fn animation(
259        event_type: EventType,
260        animation_name: impl Into<String>,
261        elapsed_time: f32,
262    ) -> Self {
263        Self {
264            event_type,
265            animation_name: animation_name.into(),
266            elapsed_time,
267            ..Default::default()
268        }
269    }
270
271    pub fn stop_propagation(&self) {
272        self.propagation_stopped.set(true);
273    }
274
275    pub fn prevent_default(&self) {
276        self.default_prevented.set(true);
277    }
278
279    pub fn is_propagation_stopped(&self) -> bool {
280        self.propagation_stopped.get()
281    }
282
283    pub fn is_default_prevented(&self) -> bool {
284        self.default_prevented.get()
285    }
286
287    pub fn phase(&self) -> EventPhase {
288        self.phase.get()
289    }
290
291    pub fn current_target(&self) -> Option<u32> {
292        self.current_target_id.get()
293    }
294
295    /// Returns true if this event was initiated by the primary (usually left) mouse button.
296    pub fn is_primary(&self) -> bool {
297        self.button == 0
298    }
299
300    /// Returns true if this event was initiated by the auxiliary (usually middle) mouse button.
301    pub fn is_auxiliary(&self) -> bool {
302        self.button == 1
303    }
304
305    /// Returns true if this event was initiated by the secondary (usually right) mouse button.
306    pub fn is_secondary(&self) -> bool {
307        self.button == 2
308    }
309
310    /// Returns true if any keyboard modifier key (Ctrl, Shift, Alt, or Meta) was held.
311    pub fn has_modifier(&self) -> bool {
312        self.ctrl_key || self.shift_key || self.alt_key || self.meta_key
313    }
314}
315
316impl Deref for Event {
317    type Target = str;
318    fn deref(&self) -> &Self::Target {
319        &self.value
320    }
321}
322
323/// Dispatches a synthetic event across a node tree ancestry path.
324pub struct EventDispatcher;
325
326impl EventDispatcher {
327    /// Dispatches an event through Capturing, AtTarget, and Bubbling phases.
328    /// `ancestry_path` must be ordered from Root (index 0) to Target element (last index).
329    pub fn dispatch<F>(ancestry_path: &[u32], event: &Event, mut listener_invoker: F)
330    where
331        F: FnMut(u32, EventPhase, &Event),
332    {
333        if ancestry_path.is_empty() {
334            return;
335        }
336
337        let target_node = *ancestry_path.last().unwrap();
338
339        // 1. Capturing Phase: Root down to target's parent
340        event.phase.set(EventPhase::Capturing);
341        if ancestry_path.len() > 1 {
342            for &node_id in &ancestry_path[..ancestry_path.len() - 1] {
343                if event.is_propagation_stopped() {
344                    return;
345                }
346                event.current_target_id.set(Some(node_id));
347                listener_invoker(node_id, EventPhase::Capturing, event);
348            }
349        }
350
351        // 2. At Target Phase
352        if event.is_propagation_stopped() {
353            return;
354        }
355        event.phase.set(EventPhase::AtTarget);
356        event.current_target_id.set(Some(target_node));
357        listener_invoker(target_node, EventPhase::AtTarget, event);
358
359        // 3. Bubbling Phase: Target's parent up to Root
360        if event.is_propagation_stopped() {
361            return;
362        }
363        event.phase.set(EventPhase::Bubbling);
364        if ancestry_path.len() > 1 {
365            for &node_id in ancestry_path[..ancestry_path.len() - 1].iter().rev() {
366                if event.is_propagation_stopped() {
367                    return;
368                }
369                event.current_target_id.set(Some(node_id));
370                listener_invoker(node_id, EventPhase::Bubbling, event);
371            }
372        }
373    }
374}