Skip to main content

strata/runtime/
events.rs

1//! Platform event dispatching, pointer gestures, keyboard events, and window drag candidates.
2
3use super::*;
4
5impl AppRuntime {
6    /// Returns the currently active platform mouse cursor icon.
7    pub fn current_cursor(&self) -> strata_platform::window::CursorIcon {
8        self.current_cursor
9    }
10
11    /// Dispatches pointer down at (px, py) coordinates with default modifiers.
12    /// Returns the detailed action result (CaretMoved, FocusChanged, DomListenerInvoked, or Ignored).
13    pub fn dispatch_pointer_down_action(&mut self, px: f32, py: f32) -> PointerDownAction {
14        self.dispatch_pointer_down_action_with_modifiers(
15            px,
16            py,
17            strata_platform::Modifiers::default(),
18        )
19    }
20
21    /// Dispatches pointer down at (px, py) coordinates with no active modifier keys.
22    /// Returns true if focus or selection state changed.
23    pub fn dispatch_pointer_down(&mut self, px: f32, py: f32) -> bool {
24        self.dispatch_pointer_down_action(px, py).is_handled()
25    }
26
27    /// Dispatches pointer down at (px, py) coordinates to manage native input element focus, multi-click,
28    /// Shift+click range extension, and text selection.
29    /// Returns true if focus or selection state changed.
30    pub fn dispatch_pointer_down_with_modifiers(
31        &mut self,
32        px: f32,
33        py: f32,
34        modifiers: strata_platform::Modifiers,
35    ) -> bool {
36        self.dispatch_pointer_down_action_with_modifiers(px, py, modifiers)
37            .is_handled()
38    }
39
40    /// Dispatches pointer down with modifier keys, returning whether the interaction only moved the caret
41    /// in the already-active input, changed focus, or invoked a DOM listener.
42    pub fn dispatch_pointer_down_action_with_modifiers(
43        &mut self,
44        px: f32,
45        py: f32,
46        modifiers: strata_platform::Modifiers,
47    ) -> PointerDownAction {
48        self.dispatch_pointer_down_action_with_button_and_modifiers(px, py, 0, modifiers)
49    }
50
51    /// Dispatches pointer down with explicit mouse button (`0` = Left, `1` = Middle, `2` = Right)
52    /// and modifier keys, managing text input focus/caret on primary clicks and invoking DOM
53    /// `PointerDown` / `MouseDown` listeners with accurate `button` / `buttons` metadata.
54    pub fn dispatch_pointer_down_action_with_button_and_modifiers(
55        &mut self,
56        px: f32,
57        py: f32,
58        button: i16,
59        modifiers: strata_platform::Modifiers,
60    ) -> PointerDownAction {
61        // Surfaces marked `data-keep-focus` (context menus, toolbars) never steal focus from the
62        // active text input, so commands such as Cut/Paste act on the field the user was editing.
63        if Self::hit_test_property(
64            &self.root_blueprint,
65            &self.layout_root,
66            px,
67            py,
68            "data-keep-focus",
69        )
70        .is_some()
71        {
72            self.drag_selection_active = false;
73            return PointerDownAction::Ignored;
74        }
75
76        let mut input_handled = false;
77        if button == 0 {
78            if let Some(target) =
79                Self::hit_test_input(&self.root_blueprint, &self.layout_root, px, py)
80            {
81                let target_key = target
82                    .input_id
83                    .clone()
84                    .unwrap_or_else(|| format!("input:{}", target.input_index));
85                let text_val = if let Some(ref active) = self.active_focus {
86                    let current_key = active
87                        .input_id
88                        .clone()
89                        .unwrap_or_else(|| format!("input:{}", active.input_index));
90                    if current_key == target_key {
91                        active.state.text.get()
92                    } else {
93                        target.current_value.clone()
94                    }
95                } else {
96                    target.current_value.clone()
97                };
98                let content_box_width = target.content_box_width;
99                let rel_x = if px < target.content_box_x {
100                    0.0
101                } else if content_box_width > 0.0 && px > target.content_box_x + content_box_width
102                {
103                    100000.0
104                } else {
105                    px - target.content_box_x
106                };
107                let char_idx = Self::calculate_exact_char_index_at_offset(
108                    &text_val,
109                    rel_x,
110                    target.font_size,
111                    target.line_height,
112                    target.is_mono,
113                    target.font_family,
114                );
115
116                let now = std::time::Instant::now();
117                let click_count = if let Some((last_time, last_x, last_y, count)) =
118                    self.last_click_info
119                {
120                    if now.duration_since(last_time).as_millis() < 400
121                        && (px - last_x).abs() < 5.0
122                        && (py - last_y).abs() < 5.0
123                    {
124                        count + 1
125                    } else {
126                        1
127                    }
128                } else {
129                    1
130                };
131                self.last_click_info = Some((now, px, py, click_count));
132                self.reset_caret_blink();
133
134                let target_key = target
135                    .input_id
136                    .clone()
137                    .unwrap_or_else(|| format!("input:{}", target.input_index));
138
139                // If the same input is already active, handle multi-click or reposition caret
140                if let Some(ref mut active) = self.active_focus {
141                    let current_key = active
142                        .input_id
143                        .clone()
144                        .unwrap_or_else(|| format!("input:{}", active.input_index));
145                    if current_key == target_key {
146                        if modifiers.shift {
147                            // Shift+click extends the existing selection from its anchor to the clicked index.
148                            active.state.update_selection_drag(char_idx);
149                            self.drag_selection_active = true;
150                        } else if click_count == 2 {
151                            active.state.select_word_at_index(char_idx);
152                            self.drag_selection_active = false;
153                        } else if click_count == 3 {
154                            active.state.select_line_at_index(char_idx);
155                            self.drag_selection_active = false;
156                        } else if click_count >= 4 {
157                            active.state.select_all();
158                            self.drag_selection_active = false;
159                        } else {
160                            active.state.cursor_index.set(char_idx);
161                            active.state.selection_anchor.set(Some(char_idx));
162                            self.drag_selection_active = true;
163                        }
164                        self.sync_active_input_layout();
165                        return PointerDownAction::CaretMoved;
166                    }
167
168                    // Switching away from previous input: persist its undo/redo history in input_states
169                    self.input_states.insert(current_key, active.state.clone());
170                    if let Some(ref blur_cb) = active.on_blur {
171                        blur_cb(strata_dom::Event::new(strata_dom::EventType::Blur));
172                    }
173                }
174
175                // Restore existing input state (with its private undo/redo history) or initialize new one
176                let state = self.input_states.remove(&target_key).unwrap_or_else(|| {
177                    strata_dom::text_input::TextInputState::with_text(&target.current_value)
178                });
179
180                // Sync external value if state was empty
181                if state.text.get().is_empty() && !target.current_value.is_empty() {
182                    state.text.set(target.current_value.clone());
183                }
184
185                if click_count == 2 {
186                    state.select_word_at_index(char_idx);
187                    self.drag_selection_active = false;
188                } else if click_count == 3 {
189                    state.select_line_at_index(char_idx);
190                    self.drag_selection_active = false;
191                } else if click_count >= 4 {
192                    state.select_all();
193                    self.drag_selection_active = false;
194                } else {
195                    state.cursor_index.set(char_idx);
196                    state.selection_anchor.set(Some(char_idx));
197                    self.drag_selection_active = true;
198                }
199                state.is_focused.set(true);
200
201                if let Some(ref focus_cb) = target.on_focus {
202                    focus_cb(strata_dom::Event::new(strata_dom::EventType::Focus));
203                }
204
205                self.active_focus = Some(ActiveInput {
206                    input_index: target.input_index,
207                    input_id: target.input_id,
208                    entity_id: target.entity_id,
209                    state,
210                    on_input: target.on_input,
211                    on_change: target.on_change,
212                    on_submit: target.on_submit,
213                    on_blur: target.on_blur,
214                });
215                self.sync_active_input_layout();
216                input_handled = true;
217            } else if let Some(active) = self.active_focus.take() {
218                let key = active
219                    .input_id
220                    .clone()
221                    .unwrap_or_else(|| format!("input:{}", active.input_index));
222                self.input_states.insert(key, active.state.clone());
223                self.drag_selection_active = false;
224                self.last_click_info = None;
225                if let Some(ref blur_cb) = active.on_blur {
226                    blur_cb(strata_dom::Event::new(strata_dom::EventType::Blur));
227                }
228                self.sync_active_input_layout();
229                input_handled = true;
230            } else {
231                self.drag_selection_active = false;
232            }
233        }
234
235        // Also dispatch PointerDown and MouseDown to DOM listeners
236        let pre_open_outside_ids = strata_dom::hooks::snapshot_open_click_outside_ids();
237        let mut inside_click_stopped = false;
238        self.pointer_capture_target = None;
239        let mut dom_handled = false;
240        let mut captured_target: Option<(Vec<usize>, bool)> = None;
241        if let Some((handler, target_box, eid)) = Self::hit_test_event_with_box_and_entity(
242            &self.root_blueprint,
243            &self.layout_root,
244            px,
245            py,
246            strata_dom::EventType::PointerDown,
247        ) {
248            let target_box_copy = *target_box;
249            let ev = self.create_mouse_event(
250                strata_dom::EventType::PointerDown,
251                px,
252                py,
253                button,
254                1,
255                Some(&target_box_copy),
256            );
257            let capture_req = ev.pointer_capture_requested.clone();
258            let stopped_cell = ev.propagation_stopped.clone();
259            let prevented_cell = ev.default_prevented.clone();
260            handler(ev);
261            dom_handled = true;
262            if stopped_cell.get() || prevented_cell.get() {
263                inside_click_stopped = true;
264            }
265            if let Some(target_path) = self.layout_root.find_path_by_entity_id(eid) {
266                match capture_req.get() {
267                    Some(true) => captured_target = Some((target_path, true)),
268                    Some(false) => {}
269                    None => captured_target = Some((target_path, false)),
270                }
271            }
272        }
273        if let Some((handler, target_box, eid)) = Self::hit_test_event_with_box_and_entity(
274            &self.root_blueprint,
275            &self.layout_root,
276            px,
277            py,
278            strata_dom::EventType::MouseDown,
279        ) {
280            let target_box_copy = *target_box;
281            let ev = self.create_mouse_event(
282                strata_dom::EventType::MouseDown,
283                px,
284                py,
285                button,
286                1,
287                Some(&target_box_copy),
288            );
289            let capture_req = ev.pointer_capture_requested.clone();
290            let stopped_cell = ev.propagation_stopped.clone();
291            let prevented_cell = ev.default_prevented.clone();
292            handler(ev);
293            dom_handled = true;
294            if stopped_cell.get() || prevented_cell.get() {
295                inside_click_stopped = true;
296            }
297            if let Some(target_path) = self.layout_root.find_path_by_entity_id(eid) {
298                match capture_req.get() {
299                    Some(true) => captured_target = Some((target_path, true)),
300                    Some(false) => captured_target = None,
301                    None if captured_target.is_none() => {
302                        captured_target = Some((target_path, false));
303                    }
304                    None => {}
305                }
306            }
307        }
308        self.pointer_capture_target = captured_target;
309
310        if button == 0 {
311            self.active_dom_drag = self.find_draggable_path_at(px, py).map(|source_path| {
312                ActiveDomDrag {
313                    source_path,
314                    start_pos: (px, py),
315                    started: false,
316                    last_over_path: None,
317                    data_transfer: Default::default(),
318                }
319            });
320        }
321
322        if !pre_open_outside_ids.is_empty() && !inside_click_stopped {
323            if strata_dom::hooks::dispatch_click_outside_for_ids(&pre_open_outside_ids) {
324                dom_handled = true;
325            }
326        }
327
328        let focus_changed = if button == 0 {
329            let focus_path = self.find_focus_path_at(px, py);
330            self.set_focus_path(focus_path)
331        } else {
332            false
333        };
334
335        if dom_handled {
336            PointerDownAction::DomListenerInvoked
337        } else if input_handled || focus_changed {
338            PointerDownAction::FocusChanged
339        } else {
340            PointerDownAction::Ignored
341        }
342    }
343
344    /// Dispatches pointer move at (px, py), returning detailed action result.
345    pub fn dispatch_pointer_move_action(&mut self, px: f32, py: f32) -> PointerMoveAction {
346        let mut selection_dragged = false;
347        if self.drag_selection_active {
348            if let Some(ref mut active) = self.active_focus {
349                let mut current_idx = 0;
350                let target_idx = active.input_index;
351                let target_id = active.input_id.as_deref();
352
353                let layout_by_entity = if let Some(eid) = active.entity_id {
354                    self.layout_root.find_by_entity_id(eid)
355                } else {
356                    None
357                };
358                let layout_opt = layout_by_entity.or_else(|| {
359                    Self::find_input_layout(
360                        &self.root_blueprint,
361                        &self.layout_root,
362                        target_idx,
363                        target_id,
364                        &mut current_idx,
365                    )
366                });
367
368                if let Some(layout) = layout_opt {
369                    let rel_x = (px - layout.geometry.content_box.x).max(0.0);
370                    let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
371                    let char_idx = Self::calculate_exact_char_index_at_offset(
372                        &active.state.text.get(),
373                        rel_x,
374                        layout.style.font_size,
375                        layout.style.line_height,
376                        is_mono,
377                        layout.style.font_family,
378                    );
379                    active.state.cursor_index.set(char_idx);
380                    self.reset_caret_blink();
381                    selection_dragged = true;
382                }
383            }
384        }
385
386        let (movement_x, movement_y) = if let Some((wx, wy)) = self.pending_cursor_warp {
387            if (px - wx).abs() <= 2.5 && (py - wy).abs() <= 2.5 {
388                self.pending_cursor_warp = None;
389                self.last_pointer_pos = Some((px, py));
390                (0.0, 0.0)
391            } else {
392                self.pending_cursor_warp = None;
393                let delta = self
394                    .last_pointer_pos
395                    .map(|(lx, ly)| ((px - lx) as f64, (py - ly) as f64))
396                    .unwrap_or((0.0, 0.0));
397                self.last_pointer_pos = Some((px, py));
398                delta
399            }
400        } else {
401            let delta = self
402                .last_pointer_pos
403                .map(|(lx, ly)| ((px - lx) as f64, (py - ly) as f64))
404                .unwrap_or((0.0, 0.0));
405            self.last_pointer_pos = Some((px, py));
406            delta
407        };
408
409        let mut dom_handled = false;
410        let mut requested_warp: Option<(f64, f64)> = None;
411        let capture = self.pointer_capture_target.clone();
412        for ev_type in [
413            strata_dom::EventType::PointerMove,
414            strata_dom::EventType::MouseMove,
415        ] {
416            match capture {
417                Some((ref cap_path, true)) => {
418                    if let Some((handler, target_box, _)) = Self::find_event_at_or_above_path(
419                        &self.root_blueprint,
420                        &self.layout_root,
421                        cap_path,
422                        ev_type,
423                    ) {
424                        let target_box_copy = *target_box;
425                        let mut ev =
426                            self.create_mouse_event(ev_type, px, py, 0, 0, Some(&target_box_copy));
427                        ev.movement_x = movement_x;
428                        ev.movement_y = movement_y;
429                        let capture_req = ev.pointer_capture_requested.clone();
430                        let warp_req = ev.cursor_warp_requested.clone();
431                        handler(ev);
432                        dom_handled = true;
433                        if capture_req.get() == Some(false) {
434                            self.pointer_capture_target = None;
435                        }
436                        if let Some(pos) = warp_req.get() {
437                            requested_warp = Some(pos);
438                        }
439                    }
440                }
441                Some((ref cap_path, false)) => {
442                    let mut hit_eid = None;
443                    if let Some((handler, target_box, eid)) =
444                        Self::hit_test_event_with_box_and_entity(
445                            &self.root_blueprint,
446                            &self.layout_root,
447                            px,
448                            py,
449                            ev_type,
450                        )
451                    {
452                        hit_eid = Some(eid);
453                        let mut ev =
454                            self.create_mouse_event(ev_type, px, py, 0, 0, Some(target_box));
455                        ev.movement_x = movement_x;
456                        ev.movement_y = movement_y;
457                        let warp_req = ev.cursor_warp_requested.clone();
458                        handler(ev);
459                        dom_handled = true;
460                        if let Some(pos) = warp_req.get() {
461                            requested_warp = Some(pos);
462                        }
463                    }
464                    if let Some((handler, target_box, cap_eid)) = Self::find_event_at_or_above_path(
465                        &self.root_blueprint,
466                        &self.layout_root,
467                        cap_path,
468                        ev_type,
469                    ) {
470                        if hit_eid != Some(cap_eid) {
471                            let target_box_copy = *target_box;
472                            let mut ev = self.create_mouse_event(
473                                ev_type,
474                                px,
475                                py,
476                                0,
477                                0,
478                                Some(&target_box_copy),
479                            );
480                            ev.movement_x = movement_x;
481                            ev.movement_y = movement_y;
482                            let warp_req = ev.cursor_warp_requested.clone();
483                            handler(ev);
484                            dom_handled = true;
485                            if let Some(pos) = warp_req.get() {
486                                requested_warp = Some(pos);
487                            }
488                        }
489                    }
490                }
491                None => {
492                    if let Some((handler, target_box)) = Self::hit_test_event_with_box(
493                        &self.root_blueprint,
494                        &self.layout_root,
495                        px,
496                        py,
497                        ev_type,
498                    ) {
499                        let mut ev =
500                            self.create_mouse_event(ev_type, px, py, 0, 0, Some(target_box));
501                        ev.movement_x = movement_x;
502                        ev.movement_y = movement_y;
503                        let warp_req = ev.cursor_warp_requested.clone();
504                        handler(ev);
505                        dom_handled = true;
506                        if let Some(pos) = warp_req.get() {
507                            requested_warp = Some(pos);
508                        }
509                    }
510                }
511            }
512        }
513        if let Some((wx, wy)) = requested_warp {
514            self.warp_cursor(wx as f32, wy as f32);
515        }
516
517        if let Some(mut drag) = self.active_dom_drag.take() {
518            let mut cancel_drag = false;
519            if !drag.started {
520                let (sx, sy) = drag.start_pos;
521                if (px - sx).abs() > 3.0 || (py - sy).abs() > 3.0 {
522                    drag.started = true;
523                    let (invoked, prevented) = self.dispatch_drag_event_at_path(
524                        &drag.source_path,
525                        strata_dom::EventType::DragStart,
526                        sx,
527                        sy,
528                        &drag.data_transfer,
529                    );
530                    if invoked {
531                        dom_handled = true;
532                    }
533                    if prevented {
534                        cancel_drag = true;
535                    }
536                }
537            }
538
539            if drag.started && !cancel_drag {
540                let (drag_invoked, _) = self.dispatch_drag_event_at_path(
541                    &drag.source_path,
542                    strata_dom::EventType::Drag,
543                    px,
544                    py,
545                    &drag.data_transfer,
546                );
547                if drag_invoked {
548                    dom_handled = true;
549                }
550
551                let over_path = self.find_drop_target_path_at(px, py);
552                if over_path != drag.last_over_path {
553                    if let Some(ref old_path) = drag.last_over_path {
554                        let (leave_invoked, _) = self.dispatch_drag_event_at_path(
555                            old_path,
556                            strata_dom::EventType::DragLeave,
557                            px,
558                            py,
559                            &drag.data_transfer,
560                        );
561                        if leave_invoked {
562                            dom_handled = true;
563                        }
564                    }
565                    if let Some(ref new_path) = over_path {
566                        let (enter_invoked, _) = self.dispatch_drag_event_at_path(
567                            new_path,
568                            strata_dom::EventType::DragEnter,
569                            px,
570                            py,
571                            &drag.data_transfer,
572                        );
573                        if enter_invoked {
574                            dom_handled = true;
575                        }
576                    }
577                    drag.last_over_path = over_path.clone();
578                }
579
580                if let Some(ref cur_over) = over_path {
581                    let (over_invoked, _) = self.dispatch_drag_event_at_path(
582                        cur_over,
583                        strata_dom::EventType::DragOver,
584                        px,
585                        py,
586                        &drag.data_transfer,
587                    );
588                    if over_invoked {
589                        dom_handled = true;
590                    }
591                }
592            }
593
594            if !cancel_drag {
595                self.active_dom_drag = Some(drag);
596            }
597        }
598
599        if dom_handled {
600            PointerMoveAction::DomListenerInvoked
601        } else if selection_dragged {
602            PointerMoveAction::SelectionDragged
603        } else {
604            PointerMoveAction::Ignored
605        }
606    }
607
608    /// Dispatches pointer move at (px, py) to update mouse drag text selection and DOM move listeners.
609    pub fn dispatch_pointer_move(&mut self, px: f32, py: f32) -> bool {
610        self.dispatch_pointer_move_action(px, py).is_handled()
611    }
612
613    /// Dispatches pointer up with primary button (`0`), returning detailed action result.
614    pub fn dispatch_pointer_up_action(&mut self, px: f32, py: f32) -> PointerUpAction {
615        self.dispatch_pointer_up_action_with_button(px, py, 0)
616    }
617
618    /// Dispatches pointer up with explicit mouse button (`0` = Left, `1` = Middle, `2` = Right).
619    pub fn dispatch_pointer_up_action_with_button(
620        &mut self,
621        px: f32,
622        py: f32,
623        button: i16,
624    ) -> PointerUpAction {
625        let mut selection_ended = false;
626        if button == 0 && self.drag_selection_active {
627            self.drag_selection_active = false;
628            if let Some(ref mut active) = self.active_focus {
629                if let Some(anchor) = active.state.selection_anchor.get() {
630                    if anchor == active.state.cursor_index.get() {
631                        active.state.selection_anchor.set(None);
632                    }
633                }
634            }
635            selection_ended = true;
636        }
637
638        let capture = self.pointer_capture_target.take();
639        let mut dom_handled = false;
640        for ev_type in [
641            strata_dom::EventType::PointerUp,
642            strata_dom::EventType::MouseUp,
643        ] {
644            match capture {
645                Some((ref cap_path, true)) => {
646                    if let Some((handler, target_box, _)) = Self::find_event_at_or_above_path(
647                        &self.root_blueprint,
648                        &self.layout_root,
649                        cap_path,
650                        ev_type,
651                    ) {
652                        let ev =
653                            self.create_mouse_event(ev_type, px, py, button, 1, Some(target_box));
654                        handler(ev);
655                        dom_handled = true;
656                    }
657                }
658                Some((ref cap_path, false)) => {
659                    let mut hit_eid = None;
660                    if let Some((handler, target_box, eid)) =
661                        Self::hit_test_event_with_box_and_entity(
662                            &self.root_blueprint,
663                            &self.layout_root,
664                            px,
665                            py,
666                            ev_type,
667                        )
668                    {
669                        hit_eid = Some(eid);
670                        let ev =
671                            self.create_mouse_event(ev_type, px, py, button, 1, Some(target_box));
672                        handler(ev);
673                        dom_handled = true;
674                    }
675                    if let Some((handler, target_box, cap_eid)) = Self::find_event_at_or_above_path(
676                        &self.root_blueprint,
677                        &self.layout_root,
678                        cap_path,
679                        ev_type,
680                    ) {
681                        if hit_eid != Some(cap_eid) {
682                            let ev = self.create_mouse_event(
683                                ev_type,
684                                px,
685                                py,
686                                button,
687                                1,
688                                Some(target_box),
689                            );
690                            handler(ev);
691                            dom_handled = true;
692                        }
693                    }
694                }
695                None => {
696                    if let Some((handler, target_box)) = Self::hit_test_event_with_box(
697                        &self.root_blueprint,
698                        &self.layout_root,
699                        px,
700                        py,
701                        ev_type,
702                    ) {
703                        let ev =
704                            self.create_mouse_event(ev_type, px, py, button, 1, Some(target_box));
705                        handler(ev);
706                        dom_handled = true;
707                    }
708                }
709            }
710        }
711
712        if button == 0 {
713            if let Some(drag) = self.active_dom_drag.take() {
714                if drag.started {
715                    let drop_path = self.find_drop_target_path_at(px, py).or(drag.last_over_path);
716                    let mut drop_dispatched = false;
717                    if let Some(ref target_path) = drop_path {
718                        let (invoked, _) = self.dispatch_drag_event_at_path(
719                            target_path,
720                            strata_dom::EventType::Drop,
721                            px,
722                            py,
723                            &drag.data_transfer,
724                        );
725                        if invoked {
726                            drop_dispatched = true;
727                            dom_handled = true;
728                        }
729                    }
730                    if !drop_dispatched {
731                        if let Some((handler, target_box)) = Self::hit_test_event_with_box(
732                            &self.root_blueprint,
733                            &self.layout_root,
734                            px,
735                            py,
736                            strata_dom::EventType::Drop,
737                        ) {
738                            let target_box_copy = *target_box;
739                            let mut ev = self.create_mouse_event(
740                                strata_dom::EventType::Drop,
741                                px,
742                                py,
743                                0,
744                                1,
745                                Some(&target_box_copy),
746                            );
747                            ev.data_transfer = std::rc::Rc::clone(&drag.data_transfer);
748                            ev.data = drag
749                                .data_transfer
750                                .borrow()
751                                .get("text/plain")
752                                .cloned()
753                                .or_else(|| drag.data_transfer.borrow().values().next().cloned());
754                            handler(ev);
755                            dom_handled = true;
756                        }
757                    }
758
759                    let (end_invoked, _) = self.dispatch_drag_event_at_path(
760                        &drag.source_path,
761                        strata_dom::EventType::DragEnd,
762                        px,
763                        py,
764                        &drag.data_transfer,
765                    );
766                    if end_invoked {
767                        dom_handled = true;
768                    }
769                }
770            }
771        }
772
773        if dom_handled {
774            PointerUpAction::DomListenerInvoked
775        } else if selection_ended {
776            PointerUpAction::SelectionEnded
777        } else {
778            PointerUpAction::Ignored
779        }
780    }
781
782    /// Dispatches pointer up to finalize mouse drag text selection and notify DOM up listeners.
783    pub fn dispatch_pointer_up(&mut self, px: f32, py: f32) -> bool {
784        self.dispatch_pointer_up_action(px, py).is_handled()
785    }
786
787    /// Finds the deepest focusable element path at `(px, py)`.
788    pub(crate) fn find_focus_path_at(&self, px: f32, py: f32) -> Option<Vec<usize>> {
789        let hit_path = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py)?;
790        let mut cur = &self.root_blueprint;
791        let is_focusable = |bp: &NodeBlueprint| -> bool {
792            if let NodeBlueprint::Element {
793                tag, attributes, ..
794            } = bp
795            {
796                let tag_lower = Self::tag_as_str(tag).to_ascii_lowercase();
797                if matches!(
798                    tag_lower.as_str(),
799                    "button" | "input" | "textarea" | "select" | "a"
800                ) {
801                    return true;
802                }
803                for attr in attributes {
804                    match attr {
805                        strata_dom::Attribute::EventListener { event, .. }
806                            if *event == strata_dom::EventType::KeyDown
807                                || *event == strata_dom::EventType::KeyUp =>
808                        {
809                            return true;
810                        }
811                        strata_dom::Attribute::Property { key, .. }
812                            if key == "tabindex" || key == "role" =>
813                        {
814                            return true;
815                        }
816                        _ => {}
817                    }
818                }
819            }
820            false
821        };
822        let mut best: Option<Vec<usize>> = if is_focusable(cur) {
823            Some(Vec::new())
824        } else {
825            None
826        };
827        let mut prefix = Vec::with_capacity(hit_path.len());
828        for &idx in &hit_path {
829            let mut flat = Vec::new();
830            match cur {
831                NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
832                    for c in children {
833                        Self::flatten_blueprints(c, &mut flat);
834                    }
835                }
836                _ => break,
837            }
838            if idx >= flat.len() {
839                break;
840            }
841            cur = flat[idx];
842            prefix.push(idx);
843            if is_focusable(cur) {
844                best = Some(prefix.clone());
845            }
846        }
847        best
848    }
849
850    fn keycode_to_dom_key(key: strata_platform::KeyCode, shift: bool) -> String {
851        use strata_platform::KeyCode;
852        match key {
853            KeyCode::ArrowDown => "ArrowDown".to_string(),
854            KeyCode::ArrowUp => "ArrowUp".to_string(),
855            KeyCode::ArrowLeft => "ArrowLeft".to_string(),
856            KeyCode::ArrowRight => "ArrowRight".to_string(),
857            KeyCode::Home => "Home".to_string(),
858            KeyCode::End => "End".to_string(),
859            KeyCode::PageUp => "PageUp".to_string(),
860            KeyCode::PageDown => "PageDown".to_string(),
861            KeyCode::Enter => "Enter".to_string(),
862            KeyCode::Escape => "Escape".to_string(),
863            KeyCode::Tab => "Tab".to_string(),
864            KeyCode::Space => " ".to_string(),
865            KeyCode::Backspace => "Backspace".to_string(),
866            KeyCode::Delete => "Delete".to_string(),
867            KeyCode::Digit0 => "0".to_string(),
868            KeyCode::Digit1 => "1".to_string(),
869            KeyCode::Digit2 => "2".to_string(),
870            KeyCode::Digit3 => "3".to_string(),
871            KeyCode::Digit4 => "4".to_string(),
872            KeyCode::Digit5 => "5".to_string(),
873            KeyCode::Digit6 => "6".to_string(),
874            KeyCode::Digit7 => "7".to_string(),
875            KeyCode::Digit8 => "8".to_string(),
876            KeyCode::Digit9 => "9".to_string(),
877            other => {
878                let dbg = format!("{:?}", other);
879                if let Some(letter) = dbg.strip_prefix("Key") {
880                    if shift {
881                        letter.to_string()
882                    } else {
883                        letter.to_ascii_lowercase()
884                    }
885                } else {
886                    dbg
887                }
888            }
889        }
890    }
891
892    fn dispatch_dom_key_event(
893        &self,
894        event_type: strata_dom::EventType,
895        key: strata_platform::KeyCode,
896        modifiers: strata_platform::Modifiers,
897    ) -> bool {
898        let Some(ref path) = self.current_focus_path else {
899            return false;
900        };
901        let mut chain: Vec<&NodeBlueprint> = Vec::with_capacity(path.len() + 1);
902        let mut cur = &self.root_blueprint;
903        chain.push(cur);
904        for &idx in path {
905            let mut flat = Vec::new();
906            match cur {
907                NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
908                    for c in children {
909                        Self::flatten_blueprints(c, &mut flat);
910                    }
911                }
912                _ => break,
913            }
914            if idx >= flat.len() {
915                break;
916            }
917            cur = flat[idx];
918            chain.push(cur);
919        }
920
921        let dom_key = Self::keycode_to_dom_key(key, modifiers.shift);
922        let mut ev = strata_dom::Event::new(event_type);
923        ev.key = dom_key;
924        ev.ctrl_key = modifiers.ctrl;
925        ev.shift_key = modifiers.shift;
926        ev.alt_key = modifiers.alt;
927        ev.meta_key = modifiers.meta;
928
929        let mut handled = false;
930        for bp in chain.into_iter().rev() {
931            if let NodeBlueprint::Element { attributes, .. } = bp {
932                for attr in attributes {
933                    if let strata_dom::Attribute::EventListener { event, handler } = attr {
934                        if *event == event_type {
935                            handler(ev.clone());
936                            handled = true;
937                            if ev.propagation_stopped.get() {
938                                return true;
939                            }
940                        }
941                    }
942                }
943            }
944        }
945        handled
946    }
947
948    /// Dispatches keyboard events to the active focused input element, returning a fine-grained KeyDispatchResult.
949    pub fn dispatch_key_event(&mut self, event: &PlatformEvent) -> KeyDispatchResult {
950        if self.active_focus.is_none() {
951            match event {
952                PlatformEvent::KeyDown { key, modifiers } => {
953                    if self.dispatch_dom_key_event(strata_dom::EventType::KeyDown, *key, *modifiers)
954                    {
955                        return KeyDispatchResult::NeedsRebuild;
956                    }
957                    let (px, py) = self.last_mouse_pos;
958                    let scrolled = match key {
959                        strata_platform::KeyCode::ArrowDown => {
960                            self.dispatch_scroll(px, py, 0.0, 40.0)
961                        }
962                        strata_platform::KeyCode::ArrowUp => {
963                            self.dispatch_scroll(px, py, 0.0, -40.0)
964                        }
965                        strata_platform::KeyCode::PageDown => {
966                            self.dispatch_scroll(px, py, 0.0, 400.0)
967                        }
968                        strata_platform::KeyCode::PageUp => {
969                            self.dispatch_scroll(px, py, 0.0, -400.0)
970                        }
971                        strata_platform::KeyCode::Home => self.scroll_to_top(px, py),
972                        strata_platform::KeyCode::End => self.scroll_to_bottom(px, py),
973                        _ => false,
974                    };
975                    if scrolled {
976                        return KeyDispatchResult::RedrawOnly;
977                    }
978                }
979                PlatformEvent::KeyUp { key, modifiers } => {
980                    if self.dispatch_dom_key_event(strata_dom::EventType::KeyUp, *key, *modifiers) {
981                        return KeyDispatchResult::NeedsRebuild;
982                    }
983                }
984                _ => {}
985            }
986            return KeyDispatchResult::Ignored;
987        }
988
989        match event {
990            PlatformEvent::ImeCommit(text) => {
991                if !text.is_empty() {
992                    self.reset_caret_blink();
993                    let active = self.active_focus.as_mut().unwrap();
994                    active.state.insert_text(text);
995                    let val = active.state.text.get();
996                    if let Some(ref on_input) = active.on_input {
997                        on_input(strata_dom::Event::with_value(
998                            strata_dom::EventType::Input,
999                            val,
1000                        ));
1001                    }
1002                    self.sync_active_input_layout();
1003                    KeyDispatchResult::NeedsRebuild
1004                } else {
1005                    KeyDispatchResult::Ignored
1006                }
1007            }
1008            PlatformEvent::ImePreedit { .. } => KeyDispatchResult::RedrawOnly,
1009            PlatformEvent::ReceivedCharacter(ch) => {
1010                if !ch.is_control() {
1011                    self.reset_caret_blink();
1012                    let active = self.active_focus.as_mut().unwrap();
1013                    active.state.insert_text(&ch.to_string());
1014                    let val = active.state.text.get();
1015                    if let Some(ref on_input) = active.on_input {
1016                        on_input(strata_dom::Event::with_value(
1017                            strata_dom::EventType::Input,
1018                            val,
1019                        ));
1020                    }
1021                    self.sync_active_input_layout();
1022                    KeyDispatchResult::NeedsRebuild
1023                } else {
1024                    KeyDispatchResult::Ignored
1025                }
1026            }
1027            PlatformEvent::KeyDown { key, modifiers } => {
1028                let mut text_changed = false;
1029                let mut nav_or_sel = false;
1030                let mut submit = false;
1031                let mut blur = false;
1032
1033                let is_cmd = modifiers.ctrl || modifiers.meta;
1034                if is_cmd {
1035                    let cmd = match key {
1036                        strata_platform::KeyCode::KeyA => Some(EditCommand::SelectAll),
1037                        strata_platform::KeyCode::KeyC => Some(EditCommand::Copy),
1038                        strata_platform::KeyCode::KeyX => Some(EditCommand::Cut),
1039                        strata_platform::KeyCode::KeyV => Some(EditCommand::Paste),
1040                        strata_platform::KeyCode::KeyZ if modifiers.shift => {
1041                            Some(EditCommand::Redo)
1042                        }
1043                        strata_platform::KeyCode::KeyZ => Some(EditCommand::Undo),
1044                        strata_platform::KeyCode::KeyY => Some(EditCommand::Redo),
1045                        _ => None,
1046                    };
1047                    if let Some(cmd) = cmd {
1048                        let res = self.apply_edit_command(cmd);
1049                        self.sync_active_input_layout();
1050                        if res {
1051                            return match cmd {
1052                                EditCommand::SelectAll | EditCommand::Copy => {
1053                                    KeyDispatchResult::RedrawOnly
1054                                }
1055                                _ => KeyDispatchResult::NeedsRebuild,
1056                            };
1057                        } else {
1058                            return KeyDispatchResult::Ignored;
1059                        }
1060                    }
1061                }
1062
1063                let active = self.active_focus.as_mut().unwrap();
1064
1065                if !text_changed && !nav_or_sel {
1066                    match key {
1067                        strata_platform::KeyCode::Backspace => {
1068                            if is_cmd {
1069                                active.state.delete_word_backward();
1070                            } else {
1071                                active.state.delete_backward();
1072                            }
1073                            text_changed = true;
1074                        }
1075                        strata_platform::KeyCode::Delete => {
1076                            if is_cmd {
1077                                active.state.delete_word_forward();
1078                            } else {
1079                                active.state.delete_forward();
1080                            }
1081                            text_changed = true;
1082                        }
1083                        strata_platform::KeyCode::ArrowLeft => {
1084                            active.state.move_left(modifiers.shift, is_cmd);
1085                            nav_or_sel = true;
1086                        }
1087                        strata_platform::KeyCode::ArrowRight => {
1088                            active.state.move_right(modifiers.shift, is_cmd);
1089                            nav_or_sel = true;
1090                        }
1091                        strata_platform::KeyCode::Home => {
1092                            active.state.move_home(modifiers.shift);
1093                            nav_or_sel = true;
1094                        }
1095                        strata_platform::KeyCode::End => {
1096                            active.state.move_end(modifiers.shift);
1097                            nav_or_sel = true;
1098                        }
1099                        strata_platform::KeyCode::Enter => {
1100                            submit = true;
1101                        }
1102                        strata_platform::KeyCode::Escape => {
1103                            blur = true;
1104                        }
1105                        _ => {}
1106                    }
1107                }
1108
1109                if text_changed || nav_or_sel {
1110                    self.caret_blink_epoch = std::time::Instant::now();
1111                }
1112
1113                if text_changed {
1114                    let val = active.state.text.get();
1115                    if let Some(ref on_input) = active.on_input {
1116                        on_input(strata_dom::Event::with_value(
1117                            strata_dom::EventType::Input,
1118                            val,
1119                        ));
1120                    }
1121                    self.sync_active_input_layout();
1122                    return KeyDispatchResult::NeedsRebuild;
1123                }
1124
1125                if nav_or_sel {
1126                    return KeyDispatchResult::RedrawOnly;
1127                }
1128
1129                if submit {
1130                    let val = active.state.text.get();
1131                    if let Some(ref on_submit) = active.on_submit {
1132                        on_submit(strata_dom::Event::with_value(
1133                            strata_dom::EventType::Submit,
1134                            val.clone(),
1135                        ));
1136                    }
1137                    if let Some(ref on_change) = active.on_change {
1138                        on_change(strata_dom::Event::with_value(
1139                            strata_dom::EventType::Change,
1140                            val,
1141                        ));
1142                    }
1143                    return KeyDispatchResult::NeedsRebuild;
1144                }
1145
1146                if blur {
1147                    if let Some(ref on_blur) = active.on_blur {
1148                        on_blur(strata_dom::Event::new(strata_dom::EventType::Blur));
1149                    }
1150                    self.active_focus = None;
1151                    return KeyDispatchResult::NeedsRebuild;
1152                }
1153
1154                KeyDispatchResult::Ignored
1155            }
1156            _ => KeyDispatchResult::Ignored,
1157        }
1158    }
1159
1160    /// Dispatches keyboard events to the active focused input element.
1161    /// Returns true if the key event was consumed by the focused input.
1162    pub fn handle_key_event(&mut self, event: &PlatformEvent) -> bool {
1163        self.dispatch_key_event(event).is_handled()
1164    }
1165
1166    /// Creates a fully populated synthetic W3C DOM Event for mouse and pointer interactions,
1167    /// with client, page, screen, and offset coordinates, button identifiers, click detail,
1168    /// and keyboard modifier flags.
1169    pub fn create_mouse_event(
1170        &self,
1171        event_type: strata_dom::EventType,
1172        px: f32,
1173        py: f32,
1174        button: i16,
1175        detail: i32,
1176        target_box: Option<&strata_layout::Rect>,
1177    ) -> strata_dom::Event {
1178        let mut ev = strata_dom::Event::new(event_type);
1179        ev.client_x = px as f64;
1180        ev.client_y = py as f64;
1181        ev.page_x = px as f64;
1182        ev.page_y = py as f64;
1183        ev.screen_x = px as f64;
1184        ev.screen_y = py as f64;
1185        ev.button = button;
1186        ev.buttons = match button {
1187            0 => 1,
1188            1 => 4,
1189            2 => 2,
1190            _ => 0,
1191        };
1192        ev.detail = detail;
1193        if let Some(tb) = target_box {
1194            ev.offset_x = (px - tb.x) as f64;
1195            ev.offset_y = (py - tb.y) as f64;
1196            ev.width = tb.width as f64;
1197            ev.height = tb.height as f64;
1198        } else {
1199            ev.offset_x = px as f64;
1200            ev.offset_y = py as f64;
1201        }
1202        #[cfg(target_os = "linux")]
1203        {
1204            let mods = strata_platform::gtk_current_modifiers();
1205            ev.shift_key = mods.shift;
1206            ev.ctrl_key = mods.ctrl;
1207            ev.alt_key = mods.alt;
1208            ev.meta_key = mods.meta;
1209        }
1210        ev
1211    }
1212
1213    /// Returns `true` when the active pointer capture target or element at `(px, py)` belongs to
1214    /// a retained `<Canvas3D>` viewport tracked by this runtime.
1215    pub fn target_is_retained_canvas3d(&self, px: f32, py: f32) -> bool {
1216        if self.tracked_retained_3d.is_empty() {
1217            return false;
1218        }
1219        let path_is_canvas = |path: &[usize]| -> bool {
1220            let mut current = &self.root_blueprint;
1221            if let NodeBlueprint::Element { tag, .. } = current {
1222                if matches!(tag, Tag::Canvas | Tag::Custom("Canvas3D")) {
1223                    return true;
1224                }
1225            }
1226            for &idx in path {
1227                let mut flat = Vec::new();
1228                match current {
1229                    NodeBlueprint::Element { children, .. }
1230                    | NodeBlueprint::Fragment(children) => {
1231                        for child in children {
1232                            Self::flatten_blueprints(child, &mut flat);
1233                        }
1234                    }
1235                    _ => return false,
1236                }
1237                if idx >= flat.len() {
1238                    return false;
1239                }
1240                current = flat[idx];
1241                if let NodeBlueprint::Element { tag, .. } = current {
1242                    if matches!(tag, Tag::Canvas | Tag::Custom("Canvas3D")) {
1243                        return true;
1244                    }
1245                }
1246            }
1247            false
1248        };
1249        if let Some((ref cap_path, _)) = self.pointer_capture_target {
1250            if path_is_canvas(cap_path) {
1251                return true;
1252            }
1253        }
1254        Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py)
1255            .as_deref()
1256            .is_some_and(path_is_canvas)
1257    }
1258
1259    /// Dispatches a pointer click event at (x, y) coordinates into the application blueprint tree.
1260    /// Returns true if an event listener was invoked.
1261    pub fn dispatch_click(&self, px: f32, py: f32) -> bool {
1262        self.dispatch_mouse_click(px, py, 0, 1)
1263    }
1264
1265    /// Dispatches a mouse click event with specific button (0 = Left, 1 = Middle, 2 = Right) and detail.
1266    pub fn dispatch_mouse_click(&self, px: f32, py: f32, button: i16, detail: i32) -> bool {
1267        let ev_type = if button == 0 {
1268            strata_dom::EventType::Click
1269        } else {
1270            strata_dom::EventType::AuxClick
1271        };
1272
1273        if let Some((handler, target_box)) =
1274            Self::hit_test_event_with_box(&self.root_blueprint, &self.layout_root, px, py, ev_type)
1275        {
1276            let ev = self.create_mouse_event(ev_type, px, py, button, detail, Some(target_box));
1277            handler(ev);
1278            true
1279        } else if button != 0 {
1280            // Fallback to Click listener if AuxClick had no explicit listener
1281            if let Some((handler, target_box)) = Self::hit_test_event_with_box(
1282                &self.root_blueprint,
1283                &self.layout_root,
1284                px,
1285                py,
1286                strata_dom::EventType::Click,
1287            ) {
1288                let ev = self.create_mouse_event(
1289                    strata_dom::EventType::Click,
1290                    px,
1291                    py,
1292                    button,
1293                    detail,
1294                    Some(target_box),
1295                );
1296                handler(ev);
1297                true
1298            } else {
1299                false
1300            }
1301        } else {
1302            false
1303        }
1304    }
1305
1306    /// Dispatches a standard W3C `dblclick` event at (x, y) coordinates to the nearest element with an `ondblclick` listener.
1307    pub fn dispatch_dblclick(&self, px: f32, py: f32) -> bool {
1308        if let Some((handler, target_box)) = Self::hit_test_event_with_box(
1309            &self.root_blueprint,
1310            &self.layout_root,
1311            px,
1312            py,
1313            strata_dom::EventType::DblClick,
1314        ) {
1315            let ev = self.create_mouse_event(
1316                strata_dom::EventType::DblClick,
1317                px,
1318                py,
1319                0,
1320                2,
1321                Some(target_box),
1322            );
1323            handler(ev);
1324            true
1325        } else {
1326            false
1327        }
1328    }
1329
1330    /// Dispatches a W3C `contextmenu` event at (x, y) to the nearest element that registered
1331    /// an `oncontextmenu` listener. Returns false (and leaves the platform default untouched)
1332    /// when nothing at that point listens, so a context menu never appears on arbitrary surfaces.
1333    pub fn dispatch_context_menu(&self, px: f32, py: f32) -> bool {
1334        if let Some((handler, target_box)) = Self::hit_test_event_with_box(
1335            &self.root_blueprint,
1336            &self.layout_root,
1337            px,
1338            py,
1339            strata_dom::EventType::ContextMenu,
1340        ) {
1341            let ev = self.create_mouse_event(
1342                strata_dom::EventType::ContextMenu,
1343                px,
1344                py,
1345                2,
1346                1,
1347                Some(target_box),
1348            );
1349            handler(ev);
1350            true
1351        } else {
1352            false
1353        }
1354    }
1355
1356    /// Records a possible window drag when a primary press lands on a `data-app-region="drag"`
1357    /// surface (the equivalent of `-webkit-app-region: drag`). Interactive children opt out with
1358    /// `data-app-region="no-drag"`. A quick second press toggles maximize, as native title bars do.
1359    pub fn begin_window_drag_candidate(&mut self, px: f32, py: f32) -> bool {
1360        let region = Self::hit_test_property(
1361            &self.root_blueprint,
1362            &self.layout_root,
1363            px,
1364            py,
1365            "data-app-region",
1366        );
1367        let is_drag = region.as_deref() == Some("drag")
1368            || self
1369                .csd_controller
1370                .hit_test(self.viewport_width, self.viewport_height, px, py)
1371                == strata_platform::CsdHitZone::Titlebar;
1372
1373        if !is_drag {
1374            self.pending_window_drag = None;
1375            return false;
1376        }
1377        let now = std::time::Instant::now();
1378        if let Some((t, lx, ly)) = self.last_drag_click.take() {
1379            if now.duration_since(t).as_millis() < 400
1380                && (px - lx).abs() < 5.0
1381                && (py - ly).abs() < 5.0
1382            {
1383                // Cancel pending drag candidate on double-click gesture so movement doesn't interfere
1384                self.pending_window_drag = None;
1385                return true;
1386            }
1387        }
1388        self.last_drag_click = Some((now, px, py));
1389        self.pending_window_drag = Some((px, py));
1390        false
1391    }
1392
1393    /// Starts a native window move once the pointer travelled past the drag threshold.
1394    /// Returns true when the window's maximized state changed (such as unmaximizing on drag).
1395    pub fn poll_window_drag(&mut self, px: f32, py: f32) -> bool {
1396        if let Some((sx, sy)) = self.pending_window_drag {
1397            if (px - sx).abs() > 4.0 || (py - sy).abs() > 4.0 {
1398                self.pending_window_drag = None;
1399                self.last_drag_click = None;
1400                #[cfg(target_os = "linux")]
1401                {
1402                    let was_max = strata_platform::gtk_is_maximized();
1403                    strata_platform::gtk_begin_window_drag(sx / self.viewport_width.max(1.0), sy);
1404                    let now_max = strata_platform::gtk_is_maximized();
1405                    return was_max != now_max;
1406                }
1407                #[cfg(not(target_os = "linux"))]
1408                {
1409                    return true;
1410                }
1411            }
1412        }
1413        false
1414    }
1415
1416    /// Finds the deepest ancestor path at `(px, py)` that is draggable (`draggable="true"` or has an `ondragstart` listener).
1417    pub(crate) fn find_draggable_path_at(&self, px: f32, py: f32) -> Option<Vec<usize>> {
1418        let hit_path = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py)?;
1419        for len in (0..=hit_path.len()).rev() {
1420            let prefix = &hit_path[..len];
1421            let Some(NodeBlueprint::Element { attributes, .. }) =
1422                Self::find_blueprint_at_path(&self.root_blueprint, prefix)
1423            else {
1424                continue;
1425            };
1426            let mut explicit_draggable: Option<bool> = None;
1427            let mut has_drag_listener = false;
1428            for attr in attributes {
1429                match attr {
1430                    strata_dom::Attribute::Property { key, value } if key == "draggable" => {
1431                        explicit_draggable = Some(!value.eq_ignore_ascii_case("false"));
1432                    }
1433                    strata_dom::Attribute::EventListener { event, .. }
1434                        if matches!(
1435                            event,
1436                            strata_dom::EventType::DragStart | strata_dom::EventType::Drag
1437                        ) =>
1438                    {
1439                        has_drag_listener = true;
1440                    }
1441                    _ => {}
1442                }
1443            }
1444            if explicit_draggable == Some(true)
1445                || (explicit_draggable.is_none() && has_drag_listener)
1446            {
1447                return Some(prefix.to_vec());
1448            }
1449        }
1450        None
1451    }
1452
1453    /// Resolves the drop-target element path at `(px, py)`, preferring the nearest ancestor registering
1454    /// a `DragEnter`, `DragOver`, `DragLeave`, or `Drop` listener so moving across child nodes inside a drop zone
1455    /// does not emit spurious `dragleave` / `dragenter` transitions.
1456    pub(crate) fn find_drop_target_path_at(&self, px: f32, py: f32) -> Option<Vec<usize>> {
1457        let hit_path = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py)?;
1458        for len in (0..=hit_path.len()).rev() {
1459            let prefix = &hit_path[..len];
1460            let Some(NodeBlueprint::Element { attributes, .. }) =
1461                Self::find_blueprint_at_path(&self.root_blueprint, prefix)
1462            else {
1463                continue;
1464            };
1465            let is_drop_zone = attributes.iter().any(|attr| {
1466                matches!(
1467                    attr,
1468                    strata_dom::Attribute::EventListener {
1469                        event: strata_dom::EventType::DragEnter
1470                            | strata_dom::EventType::DragOver
1471                            | strata_dom::EventType::DragLeave
1472                            | strata_dom::EventType::Drop,
1473                        ..
1474                    }
1475                )
1476            });
1477            if is_drop_zone {
1478                return Some(prefix.to_vec());
1479            }
1480        }
1481        Some(hit_path)
1482    }
1483
1484    /// Dispatches a drag-and-drop `EventType` (`DragStart`, `Drag`, `DragEnter`, `DragOver`, `DragLeave`, `Drop`, `DragEnd`)
1485    /// at or above `path`, returning `(listener_invoked, default_prevented)`.
1486    pub(crate) fn dispatch_drag_event_at_path(
1487        &self,
1488        path: &[usize],
1489        event_type: strata_dom::EventType,
1490        px: f32,
1491        py: f32,
1492        data_transfer: &std::rc::Rc<
1493            std::cell::RefCell<std::collections::HashMap<String, String>>,
1494        >,
1495    ) -> (bool, bool) {
1496        if let Some((handler, target_box, _)) = Self::find_event_at_or_above_path(
1497            &self.root_blueprint,
1498            &self.layout_root,
1499            path,
1500            event_type,
1501        ) {
1502            let target_box_copy = *target_box;
1503            let mut ev =
1504                self.create_mouse_event(event_type, px, py, 0, 1, Some(&target_box_copy));
1505            ev.data_transfer = std::rc::Rc::clone(data_transfer);
1506            ev.data = data_transfer
1507                .borrow()
1508                .get("text/plain")
1509                .cloned()
1510                .or_else(|| data_transfer.borrow().values().next().cloned());
1511            let prevented_cell = ev.default_prevented.clone();
1512            handler(ev);
1513            return (true, prevented_cell.get());
1514        }
1515        (false, false)
1516    }
1517
1518    pub(crate) fn find_first_event_listener<'a>(
1519        blueprint: &'a NodeBlueprint,
1520        layout: &'a LayoutNode,
1521        event_type: strata_dom::EventType,
1522    ) -> Option<(
1523        std::rc::Rc<dyn Fn(strata_dom::Event)>,
1524        &'a strata_layout::Rect,
1525    )> {
1526        if let NodeBlueprint::Element { attributes, .. } = blueprint {
1527            for attr in attributes {
1528                if let strata_dom::Attribute::EventListener { event, handler } = attr {
1529                    if *event == event_type {
1530                        return Some((handler.clone(), &layout.geometry.border_box));
1531                    }
1532                }
1533            }
1534        }
1535        for (_idx, child_bp, child_layout) in Self::paired_blueprint_children(blueprint, layout) {
1536            if let Some(found) =
1537                Self::find_first_event_listener(child_bp, child_layout, event_type)
1538            {
1539                return Some(found);
1540            }
1541        }
1542        None
1543    }
1544
1545    /// Dispatches an OS file drop (`PlatformEvent::FileDrop`) to the drop target under `last_mouse_pos`
1546    /// (or the primary `ondrop` listener in the tree), populating `event.files` and `event.data`.
1547    pub fn dispatch_file_drop(&mut self, paths: Vec<std::path::PathBuf>) -> bool {
1548        if paths.is_empty() {
1549            return false;
1550        }
1551        let (px, py) = self.last_mouse_pos;
1552        let hit = Self::hit_test_event_with_box(
1553            &self.root_blueprint,
1554            &self.layout_root,
1555            px,
1556            py,
1557            strata_dom::EventType::Drop,
1558        )
1559        .or_else(|| {
1560            Self::find_first_event_listener(
1561                &self.root_blueprint,
1562                &self.layout_root,
1563                strata_dom::EventType::Drop,
1564            )
1565        });
1566
1567        if let Some((handler, target_box)) = hit {
1568            let target_box_copy = *target_box;
1569            let mut ev = self.create_mouse_event(
1570                strata_dom::EventType::Drop,
1571                px,
1572                py,
1573                0,
1574                1,
1575                Some(&target_box_copy),
1576            );
1577            if let Some(first) = paths.first() {
1578                let first_str = first.to_string_lossy().into_owned();
1579                ev.data = Some(first_str.clone());
1580                ev.set_data("text/uri-list", first_str.clone());
1581                ev.set_data("text/plain", first_str);
1582            }
1583            ev.files = paths;
1584            handler(ev);
1585            return true;
1586        }
1587        false
1588    }
1589}