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