1use super::*;
4
5#[derive(Default)]
6pub(crate) struct BubblingOutcome {
7 pub handled: bool,
8 pub default_prevented: bool,
9 pub propagation_stopped: bool,
10 pub capture_requested: Option<bool>,
11 pub capture_entity: Option<strata_primitives::EntityId>,
12 pub cursor_warp_requested: Option<(f64, f64)>,
13 pub target_entity: Option<strata_primitives::EntityId>,
14 pub chain_entities: Vec<strata_primitives::EntityId>,
15 pub invoked_entities: Vec<strata_primitives::EntityId>,
16}
17
18impl AppRuntime {
19 pub fn current_cursor(&self) -> strata_platform::window::CursorIcon {
21 self.current_cursor
22 }
23
24 pub fn dispatch_pointer_down_action(&mut self, px: f32, py: f32) -> PointerDownAction {
27 self.dispatch_pointer_down_action_with_modifiers(
28 px,
29 py,
30 strata_platform::Modifiers::default(),
31 )
32 }
33
34 pub fn dispatch_pointer_down(&mut self, px: f32, py: f32) -> bool {
37 self.dispatch_pointer_down_action(px, py).is_handled()
38 }
39
40 pub fn dispatch_pointer_down_with_modifiers(
44 &mut self,
45 px: f32,
46 py: f32,
47 modifiers: strata_platform::Modifiers,
48 ) -> bool {
49 self.dispatch_pointer_down_action_with_modifiers(px, py, modifiers)
50 .is_handled()
51 }
52
53 pub fn dispatch_pointer_down_action_with_modifiers(
56 &mut self,
57 px: f32,
58 py: f32,
59 modifiers: strata_platform::Modifiers,
60 ) -> PointerDownAction {
61 self.dispatch_pointer_down_action_with_button_and_modifiers(px, py, 0, modifiers)
62 }
63
64 pub fn dispatch_pointer_down_action_with_button_and_modifiers(
68 &mut self,
69 px: f32,
70 py: f32,
71 button: i16,
72 modifiers: strata_platform::Modifiers,
73 ) -> PointerDownAction {
74 if Self::hit_test_property(
77 &self.root_blueprint,
78 &self.layout_root,
79 px,
80 py,
81 "data-keep-focus",
82 )
83 .is_some()
84 {
85 self.drag_selection_active = false;
86 return PointerDownAction::Ignored;
87 }
88
89 let mut input_handled = false;
90 if button == 0 {
91 if let Some(target) =
92 Self::hit_test_input(&self.root_blueprint, &self.layout_root, px, py)
93 {
94 let target_key = target
95 .input_id
96 .clone()
97 .unwrap_or_else(|| format!("input:{}", target.input_index));
98 let text_val = if let Some(ref active) = self.active_focus {
99 let current_key = active
100 .input_id
101 .clone()
102 .unwrap_or_else(|| format!("input:{}", active.input_index));
103 if current_key == target_key {
104 active.state.text.get()
105 } else {
106 target.current_value.clone()
107 }
108 } else {
109 target.current_value.clone()
110 };
111 let is_password = !target.is_multiline
112 && self.input_is_password(
113 target.input_index,
114 target.input_id.as_deref(),
115 target.entity_id,
116 );
117 let measure_val = if is_password {
118 Self::mask_password_text(&text_val)
119 } else {
120 text_val
121 };
122 let (active_scroll_x, active_scroll_y) = self
123 .active_focus
124 .as_ref()
125 .and_then(|active| {
126 let current_key = active
127 .input_id
128 .clone()
129 .unwrap_or_else(|| format!("input:{}", active.input_index));
130 if current_key == target_key {
131 Some((active.state.scroll_x.get(), active.state.scroll_y.get()))
132 } else {
133 None
134 }
135 })
136 .or_else(|| {
137 if target.is_multiline {
138 target
139 .input_id
140 .as_deref()
141 .filter(|id| !id.is_empty())
142 .and_then(|id| self.scroll_offsets_by_id.get(id).copied())
143 .or_else(|| {
144 Self::find_layout_for_focus(
145 &self.root_blueprint,
146 &self.layout_root,
147 target.input_index,
148 target.input_id.as_deref(),
149 target.entity_id,
150 )
151 .map(|n| (n.geometry.scroll_offset.x, n.geometry.scroll_offset.y))
152 })
153 .filter(|(_, y)| *y > 0.0)
154 } else {
155 None
156 }
157 })
158 .or_else(|| {
159 self.input_states
160 .get(&target_key)
161 .map(|s| (s.scroll_x.get(), s.scroll_y.get()))
162 })
163 .unwrap_or((0.0, 0.0));
164 let char_idx = Self::cursor_index_at_input_point(
165 &measure_val,
166 target.is_multiline,
167 px,
168 py,
169 target.content_box_x,
170 target.content_box_y,
171 target.content_box_width,
172 active_scroll_x,
173 active_scroll_y,
174 target.font_size,
175 target.line_height,
176 target.is_mono,
177 target.font_family,
178 );
179
180 let now = self.now();
181 let click_count = if let Some((last_time, last_x, last_y, count)) =
182 self.last_click_info
183 {
184 if now.duration_since(last_time).as_millis() < 400
185 && (px - last_x).abs() < 5.0
186 && (py - last_y).abs() < 5.0
187 {
188 count + 1
189 } else {
190 1
191 }
192 } else {
193 1
194 };
195 self.last_click_info = Some((now, px, py, click_count));
196 self.reset_caret_blink();
197
198 let target_key = target
199 .input_id
200 .clone()
201 .unwrap_or_else(|| format!("input:{}", target.input_index));
202
203 if let Some(ref mut active) = self.active_focus {
205 let current_key = active
206 .input_id
207 .clone()
208 .unwrap_or_else(|| format!("input:{}", active.input_index));
209 if current_key == target_key {
210 if modifiers.shift {
211 active.state.update_selection_drag(char_idx);
213 self.drag_selection_active = true;
214 } else if click_count == 2 {
215 if is_password {
216 active.state.select_all();
217 } else {
218 active.state.select_word_at_index(char_idx);
219 }
220 self.drag_selection_active = false;
221 } else if click_count == 3 {
222 active.state.select_line_at_index(char_idx);
223 self.drag_selection_active = false;
224 } else if click_count >= 4 {
225 active.state.select_all();
226 self.drag_selection_active = false;
227 } else {
228 active.state.cursor_index.set(char_idx);
229 active.state.selection_anchor.set(Some(char_idx));
230 self.drag_selection_active = true;
231 }
232 self.sync_active_input_layout_and_scroll_caret();
233 return PointerDownAction::CaretMoved;
234 }
235
236 self.input_states.insert(current_key, active.state.clone());
238 if let Some(ref blur_cb) = active.on_blur {
239 blur_cb(strata_dom::Event::new(strata_dom::EventType::Blur));
240 }
241 }
242
243 let state = self.input_states.remove(&target_key).unwrap_or_else(|| {
245 strata_dom::text_input::TextInputState::with_text(&target.current_value)
246 });
247
248 if state.text.get().is_empty() && !target.current_value.is_empty() {
250 state.text.set(target.current_value.clone());
251 }
252 if target.is_multiline {
253 state.scroll_y.set(active_scroll_y);
254 }
255
256 if click_count == 2 {
257 if is_password {
258 state.select_all();
259 } else {
260 state.select_word_at_index(char_idx);
261 }
262 self.drag_selection_active = false;
263 } else if click_count == 3 {
264 state.select_line_at_index(char_idx);
265 self.drag_selection_active = false;
266 } else if click_count >= 4 {
267 state.select_all();
268 self.drag_selection_active = false;
269 } else {
270 state.cursor_index.set(char_idx);
271 state.selection_anchor.set(Some(char_idx));
272 self.drag_selection_active = true;
273 }
274 state.is_focused.set(true);
275
276 if let Some(ref focus_cb) = target.on_focus {
277 focus_cb(strata_dom::Event::new(strata_dom::EventType::Focus));
278 }
279
280 self.active_focus = Some(ActiveInput {
281 input_index: target.input_index,
282 input_id: target.input_id,
283 entity_id: target.entity_id,
284 is_multiline: target.is_multiline,
285 state,
286 on_input: target.on_input,
287 on_change: target.on_change,
288 on_submit: target.on_submit,
289 on_blur: target.on_blur,
290 });
291 self.sync_active_input_layout_and_scroll_caret();
292 input_handled = true;
293 } else if let Some(active) = self.active_focus.take() {
294 if !active.is_multiline {
295 active.state.scroll_x.set(0.0);
296 if let Some(layout) = Self::find_layout_for_focus_mut(
297 &self.root_blueprint,
298 &mut self.layout_root,
299 active.input_index,
300 active.input_id.as_deref(),
301 active.entity_id,
302 ) {
303 layout.geometry.scroll_offset.x = 0.0;
304 }
305 }
306 let key = active
307 .input_id
308 .clone()
309 .unwrap_or_else(|| format!("input:{}", active.input_index));
310 self.input_states.insert(key, active.state.clone());
311 self.drag_selection_active = false;
312 self.last_click_info = None;
313 if let Some(ref blur_cb) = active.on_blur {
314 blur_cb(strata_dom::Event::new(strata_dom::EventType::Blur));
315 }
316 self.sync_active_input_layout();
317 input_handled = true;
318 } else {
319 self.drag_selection_active = false;
320 }
321 }
322
323 let pre_open_outside_ids = strata_dom::hooks::snapshot_open_click_outside_ids();
325 let mut inside_click_stopped = self.point_hits_non_backdrop_top_layer_portal(px, py);
326 self.pointer_capture_target = None;
327 let mut dom_handled = false;
328 let mut captured_target: Option<(Vec<usize>, bool)> = None;
329 let pd_outcome = self.dispatch_bubbling_event_detailed_at(
330 strata_dom::EventType::PointerDown,
331 px,
332 py,
333 button,
334 1,
335 |_| {},
336 );
337 if pd_outcome.handled {
338 dom_handled = true;
339 if pd_outcome.propagation_stopped || pd_outcome.default_prevented {
340 inside_click_stopped = true;
341 }
342 if let Some(cap_eid) = pd_outcome.capture_entity.or(pd_outcome.target_entity) {
343 if let Some(target_path) = self.layout_root.find_path_by_entity_id(cap_eid) {
344 match pd_outcome.capture_requested {
345 Some(true) => captured_target = Some((target_path, true)),
346 Some(false) => {}
347 None => captured_target = Some((target_path, false)),
348 }
349 }
350 }
351 }
352 let md_outcome = self.dispatch_bubbling_event_detailed_at(
353 strata_dom::EventType::MouseDown,
354 px,
355 py,
356 button,
357 1,
358 |_| {},
359 );
360 if md_outcome.handled {
361 dom_handled = true;
362 if md_outcome.propagation_stopped || md_outcome.default_prevented {
363 inside_click_stopped = true;
364 }
365 if let Some(cap_eid) = md_outcome.capture_entity.or(md_outcome.target_entity) {
366 if let Some(target_path) = self.layout_root.find_path_by_entity_id(cap_eid) {
367 match md_outcome.capture_requested {
368 Some(true) => captured_target = Some((target_path, true)),
369 Some(false) => captured_target = None,
370 None if captured_target.is_none() => {
371 captured_target = Some((target_path, false));
372 }
373 None => {}
374 }
375 }
376 }
377 }
378 self.pointer_capture_target = captured_target;
379
380 if button == 0 {
381 self.active_dom_drag = self.find_draggable_path_at(px, py).map(|source_path| {
382 ActiveDomDrag {
383 source_path,
384 start_pos: (px, py),
385 started: false,
386 last_over_path: None,
387 data_transfer: Default::default(),
388 }
389 });
390 }
391
392 if !pre_open_outside_ids.is_empty()
393 && !inside_click_stopped
394 && strata_dom::hooks::dispatch_click_outside_for_ids(&pre_open_outside_ids)
395 {
396 dom_handled = true;
397 }
398
399 let focus_changed = if button == 0 {
400 let focus_path = self.find_focus_path_at(px, py);
401 self.set_focus_path(focus_path)
402 } else {
403 false
404 };
405
406 if dom_handled {
407 PointerDownAction::DomListenerInvoked
408 } else if input_handled || focus_changed {
409 PointerDownAction::FocusChanged
410 } else {
411 PointerDownAction::Ignored
412 }
413 }
414
415 pub fn dispatch_pointer_move_action(&mut self, px: f32, py: f32) -> PointerMoveAction {
417 let mut selection_dragged = false;
418 if self.drag_selection_active {
419 let is_password = self
420 .active_focus
421 .as_ref()
422 .is_some_and(|a| !a.is_multiline && self.active_input_is_password(a));
423 if let Some(ref mut active) = self.active_focus {
424 let layout_opt = Self::find_layout_for_focus(
425 &self.root_blueprint,
426 &self.layout_root,
427 active.input_index,
428 active.input_id.as_deref(),
429 active.entity_id,
430 );
431
432 if let Some(layout) = layout_opt {
433 let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
434 let raw_text = active.state.text.get();
435 let measure_text = if is_password {
436 Self::mask_password_text(&raw_text)
437 } else {
438 raw_text
439 };
440 let char_idx = Self::cursor_index_at_input_point(
441 &measure_text,
442 active.is_multiline,
443 px,
444 py,
445 layout.geometry.content_box.x,
446 layout.geometry.content_box.y,
447 layout.geometry.content_box.width,
448 active.state.scroll_x.get(),
449 active.state.scroll_y.get(),
450 layout.style.font_size,
451 layout.style.line_height,
452 is_mono,
453 layout.style.font_family,
454 );
455 active.state.cursor_index.set(char_idx);
456 self.reset_caret_blink();
457 self.sync_active_input_layout_and_scroll_caret();
458 self.mark_paint_dirty();
459 selection_dragged = true;
460 }
461 }
462 }
463
464 let (movement_x, movement_y) = if let Some((wx, wy)) = self.pending_cursor_warp {
465 if (px - wx).abs() <= 2.5 && (py - wy).abs() <= 2.5 {
466 self.pending_cursor_warp = None;
467 self.last_pointer_pos = Some((px, py));
468 (0.0, 0.0)
469 } else {
470 self.pending_cursor_warp = None;
471 let delta = self
472 .last_pointer_pos
473 .map(|(lx, ly)| ((px - lx) as f64, (py - ly) as f64))
474 .unwrap_or((0.0, 0.0));
475 self.last_pointer_pos = Some((px, py));
476 delta
477 }
478 } else {
479 let delta = self
480 .last_pointer_pos
481 .map(|(lx, ly)| ((px - lx) as f64, (py - ly) as f64))
482 .unwrap_or((0.0, 0.0));
483 self.last_pointer_pos = Some((px, py));
484 delta
485 };
486
487 let mut dom_handled = false;
488 let mut requested_warp: Option<(f64, f64)> = None;
489 let capture = self.pointer_capture_target.clone();
490 for ev_type in [
491 strata_dom::EventType::PointerMove,
492 strata_dom::EventType::MouseMove,
493 ] {
494 match capture {
495 Some((ref cap_path, true)) => {
496 if let Some((handler, target_box, _)) = Self::find_event_at_or_above_path(
497 &self.root_blueprint,
498 &self.layout_root,
499 cap_path,
500 ev_type,
501 ) {
502 let target_box_copy = *target_box;
503 let mut ev =
504 self.create_mouse_event(ev_type, px, py, 0, 0, Some(&target_box_copy));
505 ev.movement_x = movement_x;
506 ev.movement_y = movement_y;
507 let capture_req = ev.pointer_capture_requested.clone();
508 let warp_req = ev.cursor_warp_requested.clone();
509 handler(ev);
510 dom_handled = true;
511 if capture_req.get() == Some(false) {
512 self.pointer_capture_target = None;
513 }
514 if let Some(pos) = warp_req.get() {
515 requested_warp = Some(pos);
516 }
517 }
518 }
519 Some((ref cap_path, false)) => {
520 let outcome = self.dispatch_bubbling_event_detailed_at(
521 ev_type,
522 px,
523 py,
524 0,
525 0,
526 |ev| {
527 ev.movement_x = movement_x;
528 ev.movement_y = movement_y;
529 },
530 );
531 if outcome.handled {
532 dom_handled = true;
533 if let Some(pos) = outcome.cursor_warp_requested {
534 requested_warp = Some(pos);
535 }
536 }
537 if let Some((handler, target_box, cap_eid)) = Self::find_event_at_or_above_path(
538 &self.root_blueprint,
539 &self.layout_root,
540 cap_path,
541 ev_type,
542 ) {
543 let suppressed_by_bubble_stop = outcome.propagation_stopped
544 && outcome.chain_entities.contains(&cap_eid);
545 if !outcome.invoked_entities.contains(&cap_eid) && !suppressed_by_bubble_stop
546 {
547 let target_box_copy = *target_box;
548 let mut ev = self.create_mouse_event(
549 ev_type,
550 px,
551 py,
552 0,
553 0,
554 Some(&target_box_copy),
555 );
556 ev.movement_x = movement_x;
557 ev.movement_y = movement_y;
558 let warp_req = ev.cursor_warp_requested.clone();
559 handler(ev);
560 dom_handled = true;
561 if let Some(pos) = warp_req.get() {
562 requested_warp = Some(pos);
563 }
564 }
565 }
566 }
567 None => {
568 let outcome = self.dispatch_bubbling_event_detailed_at(
569 ev_type,
570 px,
571 py,
572 0,
573 0,
574 |ev| {
575 ev.movement_x = movement_x;
576 ev.movement_y = movement_y;
577 },
578 );
579 if outcome.handled {
580 dom_handled = true;
581 if let Some(pos) = outcome.cursor_warp_requested {
582 requested_warp = Some(pos);
583 }
584 }
585 }
586 }
587 }
588 if let Some((wx, wy)) = requested_warp {
589 self.warp_cursor(wx as f32, wy as f32);
590 }
591
592 if let Some(mut drag) = self.active_dom_drag.take() {
593 let mut cancel_drag = false;
594 if !drag.started {
595 let (sx, sy) = drag.start_pos;
596 if (px - sx).abs() > 3.0 || (py - sy).abs() > 3.0 {
597 drag.started = true;
598 let (invoked, prevented) = self.dispatch_drag_event_at_path(
599 &drag.source_path,
600 strata_dom::EventType::DragStart,
601 sx,
602 sy,
603 &drag.data_transfer,
604 );
605 if invoked {
606 dom_handled = true;
607 }
608 if prevented {
609 cancel_drag = true;
610 }
611 }
612 }
613
614 if drag.started && !cancel_drag {
615 let (drag_invoked, _) = self.dispatch_drag_event_at_path(
616 &drag.source_path,
617 strata_dom::EventType::Drag,
618 px,
619 py,
620 &drag.data_transfer,
621 );
622 if drag_invoked {
623 dom_handled = true;
624 }
625
626 let over_path = self.find_drop_target_path_at(px, py);
627 if over_path != drag.last_over_path {
628 if let Some(ref old_path) = drag.last_over_path {
629 let (leave_invoked, _) = self.dispatch_drag_event_at_path(
630 old_path,
631 strata_dom::EventType::DragLeave,
632 px,
633 py,
634 &drag.data_transfer,
635 );
636 if leave_invoked {
637 dom_handled = true;
638 }
639 }
640 if let Some(ref new_path) = over_path {
641 let (enter_invoked, _) = self.dispatch_drag_event_at_path(
642 new_path,
643 strata_dom::EventType::DragEnter,
644 px,
645 py,
646 &drag.data_transfer,
647 );
648 if enter_invoked {
649 dom_handled = true;
650 }
651 }
652 drag.last_over_path = over_path.clone();
653 }
654
655 if let Some(ref cur_over) = over_path {
656 let (over_invoked, _) = self.dispatch_drag_event_at_path(
657 cur_over,
658 strata_dom::EventType::DragOver,
659 px,
660 py,
661 &drag.data_transfer,
662 );
663 if over_invoked {
664 dom_handled = true;
665 }
666 }
667 }
668
669 if !cancel_drag {
670 self.active_dom_drag = Some(drag);
671 }
672 }
673
674 if dom_handled {
675 PointerMoveAction::DomListenerInvoked
676 } else if selection_dragged {
677 PointerMoveAction::SelectionDragged
678 } else {
679 PointerMoveAction::Ignored
680 }
681 }
682
683 pub fn dispatch_pointer_move(&mut self, px: f32, py: f32) -> bool {
685 self.dispatch_pointer_move_action(px, py).is_handled()
686 }
687
688 pub fn dispatch_pointer_up_action(&mut self, px: f32, py: f32) -> PointerUpAction {
690 self.dispatch_pointer_up_action_with_button(px, py, 0)
691 }
692
693 pub fn dispatch_pointer_up_action_with_button(
695 &mut self,
696 px: f32,
697 py: f32,
698 button: i16,
699 ) -> PointerUpAction {
700 let mut selection_ended = false;
701 if button == 0 && self.drag_selection_active {
702 self.drag_selection_active = false;
703 if let Some(ref mut active) = self.active_focus {
704 if let Some(anchor) = active.state.selection_anchor.get() {
705 if anchor == active.state.cursor_index.get() {
706 active.state.selection_anchor.set(None);
707 }
708 }
709 }
710 selection_ended = true;
711 }
712
713 let capture = self.pointer_capture_target.take();
714 let mut dom_handled = false;
715 for ev_type in [
716 strata_dom::EventType::PointerUp,
717 strata_dom::EventType::MouseUp,
718 ] {
719 match capture {
720 Some((ref cap_path, true)) => {
721 if let Some((handler, target_box, _)) = Self::find_event_at_or_above_path(
722 &self.root_blueprint,
723 &self.layout_root,
724 cap_path,
725 ev_type,
726 ) {
727 let ev =
728 self.create_mouse_event(ev_type, px, py, button, 1, Some(target_box));
729 handler(ev);
730 dom_handled = true;
731 }
732 }
733 Some((ref cap_path, false)) => {
734 let outcome = self.dispatch_bubbling_event_detailed_at(
735 ev_type,
736 px,
737 py,
738 button,
739 1,
740 |_| {},
741 );
742 if outcome.handled {
743 dom_handled = true;
744 }
745 if let Some((handler, target_box, cap_eid)) = Self::find_event_at_or_above_path(
746 &self.root_blueprint,
747 &self.layout_root,
748 cap_path,
749 ev_type,
750 ) {
751 let suppressed_by_bubble_stop = outcome.propagation_stopped
752 && outcome.chain_entities.contains(&cap_eid);
753 if !outcome.invoked_entities.contains(&cap_eid) && !suppressed_by_bubble_stop
754 {
755 let ev = self.create_mouse_event(
756 ev_type,
757 px,
758 py,
759 button,
760 1,
761 Some(target_box),
762 );
763 handler(ev);
764 dom_handled = true;
765 }
766 }
767 }
768 None => {
769 let outcome = self.dispatch_bubbling_event_detailed_at(
770 ev_type,
771 px,
772 py,
773 button,
774 1,
775 |_| {},
776 );
777 if outcome.handled {
778 dom_handled = true;
779 }
780 }
781 }
782 }
783
784 if button == 0 {
785 if let Some(drag) = self.active_dom_drag.take() {
786 if drag.started {
787 let drop_path = self.find_drop_target_path_at(px, py).or(drag.last_over_path);
788 let mut drop_dispatched = false;
789 if let Some(ref target_path) = drop_path {
790 let (invoked, _) = self.dispatch_drag_event_at_path(
791 target_path,
792 strata_dom::EventType::Drop,
793 px,
794 py,
795 &drag.data_transfer,
796 );
797 if invoked {
798 drop_dispatched = true;
799 dom_handled = true;
800 }
801 }
802 if !drop_dispatched {
803 if let Some((handler, target_box)) = Self::hit_test_event_with_box(
804 &self.root_blueprint,
805 &self.layout_root,
806 px,
807 py,
808 strata_dom::EventType::Drop,
809 ) {
810 let target_box_copy = *target_box;
811 let mut ev = self.create_mouse_event(
812 strata_dom::EventType::Drop,
813 px,
814 py,
815 0,
816 1,
817 Some(&target_box_copy),
818 );
819 ev.data_transfer = std::rc::Rc::clone(&drag.data_transfer);
820 ev.data = drag
821 .data_transfer
822 .borrow()
823 .get("text/plain")
824 .cloned()
825 .or_else(|| drag.data_transfer.borrow().values().next().cloned());
826 handler(ev);
827 dom_handled = true;
828 }
829 }
830
831 let (end_invoked, _) = self.dispatch_drag_event_at_path(
832 &drag.source_path,
833 strata_dom::EventType::DragEnd,
834 px,
835 py,
836 &drag.data_transfer,
837 );
838 if end_invoked {
839 dom_handled = true;
840 }
841 }
842 }
843 }
844
845 if dom_handled {
846 PointerUpAction::DomListenerInvoked
847 } else if selection_ended {
848 PointerUpAction::SelectionEnded
849 } else {
850 PointerUpAction::Ignored
851 }
852 }
853
854 pub fn dispatch_pointer_up(&mut self, px: f32, py: f32) -> bool {
856 self.dispatch_pointer_up_action(px, py).is_handled()
857 }
858
859 pub(crate) fn find_focus_path_at(&self, px: f32, py: f32) -> Option<Vec<usize>> {
861 let hit_path = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py)?;
862 let mut cur = &self.root_blueprint;
863 let is_focusable = |bp: &NodeBlueprint| -> bool {
864 if let NodeBlueprint::Element {
865 tag, attributes, ..
866 } = bp
867 {
868 let tag_lower = Self::tag_as_str(tag).to_ascii_lowercase();
869 if matches!(
870 tag_lower.as_str(),
871 "button" | "input" | "textarea" | "select" | "a"
872 ) {
873 return true;
874 }
875 for attr in attributes {
876 match attr {
877 strata_dom::Attribute::EventListener { event, .. }
878 if *event == strata_dom::EventType::KeyDown
879 || *event == strata_dom::EventType::KeyUp =>
880 {
881 return true;
882 }
883 strata_dom::Attribute::Property { key, .. }
884 if key == "tabindex" || key == "role" =>
885 {
886 return true;
887 }
888 _ => {}
889 }
890 }
891 }
892 false
893 };
894 let mut best: Option<Vec<usize>> = if is_focusable(cur) {
895 Some(Vec::new())
896 } else {
897 None
898 };
899 let mut prefix = Vec::with_capacity(hit_path.len());
900 for &idx in &hit_path {
901 let mut flat = Vec::new();
902 match cur {
903 NodeBlueprint::Element { children, .. } | NodeBlueprint::Fragment(children) => {
904 for c in children {
905 Self::flatten_blueprints(c, &mut flat);
906 }
907 }
908 _ => break,
909 }
910 if idx >= flat.len() {
911 break;
912 }
913 cur = flat[idx];
914 prefix.push(idx);
915 if is_focusable(cur) {
916 best = Some(prefix.clone());
917 }
918 }
919 best
920 }
921
922 fn keycode_to_dom_key(key: strata_platform::KeyCode, shift: bool) -> String {
923 use strata_platform::KeyCode;
924 match key {
925 KeyCode::ArrowDown => "ArrowDown".to_string(),
926 KeyCode::ArrowUp => "ArrowUp".to_string(),
927 KeyCode::ArrowLeft => "ArrowLeft".to_string(),
928 KeyCode::ArrowRight => "ArrowRight".to_string(),
929 KeyCode::Home => "Home".to_string(),
930 KeyCode::End => "End".to_string(),
931 KeyCode::PageUp => "PageUp".to_string(),
932 KeyCode::PageDown => "PageDown".to_string(),
933 KeyCode::Enter => "Enter".to_string(),
934 KeyCode::Escape => "Escape".to_string(),
935 KeyCode::Tab => "Tab".to_string(),
936 KeyCode::Space => " ".to_string(),
937 KeyCode::Backspace => "Backspace".to_string(),
938 KeyCode::Delete => "Delete".to_string(),
939 KeyCode::Digit0 => if shift { ")" } else { "0" }.to_string(),
940 KeyCode::Digit1 => if shift { "!" } else { "1" }.to_string(),
941 KeyCode::Digit2 => if shift { "@" } else { "2" }.to_string(),
942 KeyCode::Digit3 => if shift { "#" } else { "3" }.to_string(),
943 KeyCode::Digit4 => if shift { "$" } else { "4" }.to_string(),
944 KeyCode::Digit5 => if shift { "%" } else { "5" }.to_string(),
945 KeyCode::Digit6 => if shift { "^" } else { "6" }.to_string(),
946 KeyCode::Digit7 => if shift { "&" } else { "7" }.to_string(),
947 KeyCode::Digit8 => if shift { "*" } else { "8" }.to_string(),
948 KeyCode::Digit9 => if shift { "(" } else { "9" }.to_string(),
949 KeyCode::Slash => if shift { "?" } else { "/" }.to_string(),
950 KeyCode::Comma => if shift { "<" } else { "," }.to_string(),
951 KeyCode::Period => if shift { ">" } else { "." }.to_string(),
952 KeyCode::Minus => if shift { "_" } else { "-" }.to_string(),
953 KeyCode::Equals => if shift { "+" } else { "=" }.to_string(),
954 KeyCode::BracketLeft => if shift { "{" } else { "[" }.to_string(),
955 KeyCode::BracketRight => if shift { "}" } else { "]" }.to_string(),
956 KeyCode::Semicolon => if shift { ":" } else { ";" }.to_string(),
957 KeyCode::Quote => if shift { "\"" } else { "'" }.to_string(),
958 KeyCode::Backslash => if shift { "|" } else { "\\" }.to_string(),
959 KeyCode::Backquote => if shift { "~" } else { "`" }.to_string(),
960 other => {
961 let dbg = format!("{:?}", other);
962 if let Some(letter) = dbg.strip_prefix("Key") {
963 if shift {
964 letter.to_string()
965 } else {
966 letter.to_ascii_lowercase()
967 }
968 } else {
969 dbg
970 }
971 }
972 }
973 }
974
975 fn dispatch_global_shortcut_for_key(
976 key: strata_platform::KeyCode,
977 modifiers: strata_platform::Modifiers,
978 ) -> bool {
979 let dom_key = Self::keycode_to_dom_key(key, false);
980 strata_dom::hooks::dispatch_global_keydown(
981 &dom_key,
982 modifiers.ctrl,
983 modifiers.shift,
984 modifiers.alt,
985 modifiers.meta,
986 )
987 }
988
989 fn dispatch_dom_event_along_focus_path(&self, ev: strata_dom::Event) -> (bool, bool, bool) {
992 let fallback_path;
993 let path: &[usize] = if let Some(ref p) = self.current_focus_path {
994 p.as_slice()
995 } else if let Some(ref active) = self.active_focus {
996 if let Some(p) = active
997 .entity_id
998 .and_then(|eid| self.layout_root.find_path_by_entity_id(eid))
999 {
1000 fallback_path = p;
1001 &fallback_path
1002 } else {
1003 return (false, false, false);
1004 }
1005 } else {
1006 return (false, false, false);
1007 };
1008
1009 let chain = Self::resolve_chain_for_path(&self.root_blueprint, &self.layout_root, path);
1010 let event_type = ev.event_type;
1011 let mut handled = false;
1012 let mut default_prevented = false;
1013 for (bp, _) in chain.into_iter().rev() {
1014 if let NodeBlueprint::Element { attributes, .. } = bp {
1015 for attr in attributes {
1016 if let strata_dom::Attribute::EventListener { event, handler } = attr {
1017 if *event == event_type {
1018 let call_ev = ev.clone();
1019 let prevented_cell = call_ev.default_prevented.clone();
1020 let stopped_cell = call_ev.propagation_stopped.clone();
1021 handler(call_ev);
1022 handled = true;
1023 if prevented_cell.get() {
1024 default_prevented = true;
1025 }
1026 if stopped_cell.get() {
1027 return (true, default_prevented, true);
1028 }
1029 }
1030 }
1031 }
1032 }
1033 }
1034 (handled, default_prevented, false)
1035 }
1036
1037 fn dispatch_dom_key_event(
1038 &self,
1039 event_type: strata_dom::EventType,
1040 key: strata_platform::KeyCode,
1041 modifiers: strata_platform::Modifiers,
1042 ) -> (bool, bool, bool) {
1043 let dom_key = Self::keycode_to_dom_key(key, modifiers.shift);
1044 let mut ev = strata_dom::Event::new(event_type);
1045 ev.key = dom_key;
1046 ev.ctrl_key = modifiers.ctrl;
1047 ev.shift_key = modifiers.shift;
1048 ev.alt_key = modifiers.alt;
1049 ev.meta_key = modifiers.meta;
1050 self.dispatch_dom_event_along_focus_path(ev)
1051 }
1052
1053 pub fn dispatch_key_event(&mut self, event: &PlatformEvent) -> KeyDispatchResult {
1055 if self.active_focus.is_none() {
1056 match event {
1057 PlatformEvent::KeyDown { key, modifiers } => {
1058 self.last_dom_keydown_consumed_char = None;
1059 let (dom_handled, dom_default_prevented, dom_stopped) = self
1060 .dispatch_dom_key_event(strata_dom::EventType::KeyDown, *key, *modifiers);
1061 if dom_handled && !modifiers.ctrl && !modifiers.alt && !modifiers.meta {
1062 let dom_key = Self::keycode_to_dom_key(*key, modifiers.shift);
1063 let mut chars = dom_key.chars();
1064 if let (Some(ch), None) = (chars.next(), chars.next()) {
1065 if !ch.is_control() {
1066 self.last_dom_keydown_consumed_char = Some((ch, self.now()));
1067 }
1068 }
1069 }
1070 if dom_default_prevented || dom_stopped {
1071 return KeyDispatchResult::NeedsRebuild;
1072 }
1073 if Self::dispatch_global_shortcut_for_key(*key, *modifiers) || dom_handled {
1074 return KeyDispatchResult::NeedsRebuild;
1075 }
1076 let (px, py) = self.last_mouse_pos;
1077 let scrolled = match key {
1078 strata_platform::KeyCode::ArrowDown => {
1079 self.dispatch_scroll(px, py, 0.0, 40.0)
1080 }
1081 strata_platform::KeyCode::ArrowUp => {
1082 self.dispatch_scroll(px, py, 0.0, -40.0)
1083 }
1084 strata_platform::KeyCode::PageDown => {
1085 self.dispatch_scroll(px, py, 0.0, 400.0)
1086 }
1087 strata_platform::KeyCode::PageUp => {
1088 self.dispatch_scroll(px, py, 0.0, -400.0)
1089 }
1090 strata_platform::KeyCode::Home => self.scroll_to_top(px, py),
1091 strata_platform::KeyCode::End => self.scroll_to_bottom(px, py),
1092 _ => false,
1093 };
1094 if scrolled {
1095 return KeyDispatchResult::RedrawOnly;
1096 }
1097 }
1098 PlatformEvent::KeyUp { key, modifiers } => {
1099 self.last_dom_keydown_consumed_char = None;
1100 if self
1101 .dispatch_dom_key_event(strata_dom::EventType::KeyUp, *key, *modifiers)
1102 .0
1103 {
1104 return KeyDispatchResult::NeedsRebuild;
1105 }
1106 }
1107 PlatformEvent::ReceivedCharacter(ch) => {
1108 if !ch.is_control() && self.current_focus_path.is_some() {
1109 if let Some((prev, ts)) = self.last_dom_keydown_consumed_char.take() {
1110 if prev == *ch
1111 && self.elapsed_since(ts) < std::time::Duration::from_millis(50)
1112 {
1113 return KeyDispatchResult::Ignored;
1114 }
1115 }
1116 let text = ch.to_string();
1117 let mut key_ev = strata_dom::Event::new(strata_dom::EventType::KeyDown);
1118 key_ev.key = text.clone();
1119 key_ev.data = Some(text.clone());
1120 key_ev.input_type = "insertText".to_string();
1121 let (key_handled, _, _) =
1122 self.dispatch_dom_event_along_focus_path(key_ev);
1123 if key_handled {
1124 return KeyDispatchResult::NeedsRebuild;
1125 }
1126 let mut input_ev =
1127 strata_dom::Event::with_value(strata_dom::EventType::Input, text.clone());
1128 input_ev.data = Some(text);
1129 input_ev.input_type = "insertText".to_string();
1130 if self.dispatch_dom_event_along_focus_path(input_ev).0 {
1131 return KeyDispatchResult::NeedsRebuild;
1132 }
1133 }
1134 }
1135 PlatformEvent::ImeCommit(text) => {
1136 self.last_dom_keydown_consumed_char = None;
1137 if !text.is_empty() && self.current_focus_path.is_some() {
1138 let mut input_ev = strata_dom::Event::with_value(
1139 strata_dom::EventType::Input,
1140 text.clone(),
1141 );
1142 input_ev.data = Some(text.clone());
1143 input_ev.input_type = "insertCompositionText".to_string();
1144 if self.dispatch_dom_event_along_focus_path(input_ev).0 {
1145 return KeyDispatchResult::NeedsRebuild;
1146 }
1147 let mut any_handled = false;
1148 for ch in text.chars() {
1149 if ch.is_control() {
1150 continue;
1151 }
1152 let s = ch.to_string();
1153 let mut key_ev = strata_dom::Event::new(strata_dom::EventType::KeyDown);
1154 key_ev.key = s.clone();
1155 key_ev.data = Some(s);
1156 key_ev.input_type = "insertCompositionText".to_string();
1157 if self.dispatch_dom_event_along_focus_path(key_ev).0 {
1158 any_handled = true;
1159 }
1160 }
1161 if any_handled {
1162 return KeyDispatchResult::NeedsRebuild;
1163 }
1164 }
1165 }
1166 _ => {}
1167 }
1168 return KeyDispatchResult::Ignored;
1169 }
1170
1171 match event {
1172 PlatformEvent::ImeCommit(text) => {
1173 if !text.is_empty() {
1174 self.reset_caret_blink();
1175 let active = self.active_focus.as_mut().unwrap();
1176 active.state.insert_text(text);
1177 let val = active.state.text.get();
1178 if let Some(ref on_input) = active.on_input {
1179 on_input(strata_dom::Event::with_value(
1180 strata_dom::EventType::Input,
1181 val,
1182 ));
1183 }
1184 self.sync_active_input_layout_and_scroll_caret();
1185 KeyDispatchResult::NeedsRebuild
1186 } else {
1187 KeyDispatchResult::Ignored
1188 }
1189 }
1190 PlatformEvent::ImePreedit { .. } => KeyDispatchResult::RedrawOnly,
1191 PlatformEvent::ReceivedCharacter(ch) => {
1192 if !ch.is_control() {
1193 self.reset_caret_blink();
1194 let active = self.active_focus.as_mut().unwrap();
1195 active.state.insert_text(&ch.to_string());
1196 let val = active.state.text.get();
1197 if let Some(ref on_input) = active.on_input {
1198 on_input(strata_dom::Event::with_value(
1199 strata_dom::EventType::Input,
1200 val,
1201 ));
1202 }
1203 self.sync_active_input_layout_and_scroll_caret();
1204 KeyDispatchResult::NeedsRebuild
1205 } else {
1206 KeyDispatchResult::Ignored
1207 }
1208 }
1209 PlatformEvent::KeyUp { key, modifiers } => {
1210 if self
1211 .dispatch_dom_key_event(strata_dom::EventType::KeyUp, *key, *modifiers)
1212 .0
1213 {
1214 KeyDispatchResult::NeedsRebuild
1215 } else {
1216 KeyDispatchResult::Ignored
1217 }
1218 }
1219 PlatformEvent::KeyDown { key, modifiers } => {
1220 let (dom_handled, dom_default_prevented, _) =
1221 self.dispatch_dom_key_event(strata_dom::EventType::KeyDown, *key, *modifiers);
1222 if dom_default_prevented {
1223 return KeyDispatchResult::NeedsRebuild;
1224 }
1225
1226 let mut text_changed = false;
1227 let mut nav_or_sel = false;
1228 let mut submit = false;
1229 let mut blur = false;
1230
1231 let is_cmd = modifiers.ctrl || modifiers.meta;
1232 if is_cmd && !modifiers.alt {
1233 let cmd = match key {
1234 strata_platform::KeyCode::KeyA => Some(EditCommand::SelectAll),
1235 strata_platform::KeyCode::KeyC => Some(EditCommand::Copy),
1236 strata_platform::KeyCode::KeyX => Some(EditCommand::Cut),
1237 strata_platform::KeyCode::KeyV => Some(EditCommand::Paste),
1238 strata_platform::KeyCode::KeyZ if modifiers.shift => {
1239 Some(EditCommand::Redo)
1240 }
1241 strata_platform::KeyCode::KeyZ => Some(EditCommand::Undo),
1242 strata_platform::KeyCode::KeyY => Some(EditCommand::Redo),
1243 _ => None,
1244 };
1245 if let Some(cmd) = cmd {
1246 let res = self.apply_edit_command(cmd);
1247 if matches!(cmd, EditCommand::Copy | EditCommand::SelectAll) {
1248 self.sync_active_input_layout();
1249 } else {
1250 self.sync_active_input_layout_and_scroll_caret();
1251 }
1252 if res {
1253 return match cmd {
1254 EditCommand::SelectAll | EditCommand::Copy => {
1255 self.mark_paint_dirty();
1256 KeyDispatchResult::RedrawOnly
1257 }
1258 _ => KeyDispatchResult::NeedsRebuild,
1259 };
1260 } else if dom_handled {
1261 return KeyDispatchResult::NeedsRebuild;
1262 } else {
1263 return KeyDispatchResult::Ignored;
1264 }
1265 }
1266 }
1267
1268 let is_global_candidate = is_cmd
1269 || modifiers.alt
1270 || matches!(
1271 key,
1272 strata_platform::KeyCode::Escape
1273 | strata_platform::KeyCode::F1
1274 | strata_platform::KeyCode::F2
1275 | strata_platform::KeyCode::F3
1276 | strata_platform::KeyCode::F4
1277 | strata_platform::KeyCode::F5
1278 | strata_platform::KeyCode::F6
1279 | strata_platform::KeyCode::F7
1280 | strata_platform::KeyCode::F8
1281 | strata_platform::KeyCode::F9
1282 | strata_platform::KeyCode::F10
1283 | strata_platform::KeyCode::F11
1284 | strata_platform::KeyCode::F12
1285 );
1286 if is_global_candidate && Self::dispatch_global_shortcut_for_key(*key, *modifiers) {
1287 return KeyDispatchResult::NeedsRebuild;
1288 }
1289
1290 let is_multiline = self.active_focus.as_ref().is_some_and(|a| a.is_multiline);
1291 if is_multiline {
1292 match key {
1293 strata_platform::KeyCode::ArrowUp => {
1294 self.move_active_input_vertical(-1, false, modifiers.shift);
1295 nav_or_sel = true;
1296 }
1297 strata_platform::KeyCode::ArrowDown => {
1298 self.move_active_input_vertical(1, false, modifiers.shift);
1299 nav_or_sel = true;
1300 }
1301 strata_platform::KeyCode::PageUp => {
1302 self.move_active_input_vertical(-1, true, modifiers.shift);
1303 nav_or_sel = true;
1304 }
1305 strata_platform::KeyCode::PageDown => {
1306 self.move_active_input_vertical(1, true, modifiers.shift);
1307 nav_or_sel = true;
1308 }
1309 strata_platform::KeyCode::Home if !is_cmd => {
1310 self.move_active_input_line_edge(false, modifiers.shift);
1311 nav_or_sel = true;
1312 }
1313 strata_platform::KeyCode::End if !is_cmd => {
1314 self.move_active_input_line_edge(true, modifiers.shift);
1315 nav_or_sel = true;
1316 }
1317 _ => {}
1318 }
1319 }
1320
1321 if !text_changed && !nav_or_sel {
1322 let active = self.active_focus.as_mut().unwrap();
1323 match key {
1324 strata_platform::KeyCode::Backspace => {
1325 if is_cmd {
1326 active.state.delete_word_backward();
1327 } else {
1328 active.state.delete_backward();
1329 }
1330 text_changed = true;
1331 }
1332 strata_platform::KeyCode::Delete => {
1333 if is_cmd {
1334 active.state.delete_word_forward();
1335 } else {
1336 active.state.delete_forward();
1337 }
1338 text_changed = true;
1339 }
1340 strata_platform::KeyCode::ArrowLeft => {
1341 active.state.move_left(modifiers.shift, is_cmd);
1342 nav_or_sel = true;
1343 }
1344 strata_platform::KeyCode::ArrowRight => {
1345 active.state.move_right(modifiers.shift, is_cmd);
1346 nav_or_sel = true;
1347 }
1348 strata_platform::KeyCode::Home => {
1349 active.state.move_home(modifiers.shift);
1350 nav_or_sel = true;
1351 }
1352 strata_platform::KeyCode::End => {
1353 active.state.move_end(modifiers.shift);
1354 nav_or_sel = true;
1355 }
1356 strata_platform::KeyCode::Enter => {
1357 if active.is_multiline && !is_cmd {
1358 active.state.insert_text("\n");
1359 text_changed = true;
1360 } else {
1361 submit = true;
1362 }
1363 }
1364 strata_platform::KeyCode::Escape => {
1365 blur = true;
1366 }
1367 _ => {}
1368 }
1369 }
1370
1371 if text_changed || nav_or_sel {
1372 self.caret_blink_epoch = self.now();
1373 }
1374
1375 if text_changed {
1376 let active = self.active_focus.as_ref().unwrap();
1377 let val = active.state.text.get();
1378 if let Some(ref on_input) = active.on_input {
1379 on_input(strata_dom::Event::with_value(
1380 strata_dom::EventType::Input,
1381 val,
1382 ));
1383 }
1384 self.sync_active_input_layout_and_scroll_caret();
1385 return KeyDispatchResult::NeedsRebuild;
1386 }
1387
1388 if nav_or_sel {
1389 self.sync_active_input_layout_and_scroll_caret();
1390 self.mark_paint_dirty();
1391 return KeyDispatchResult::RedrawOnly;
1392 }
1393
1394 if submit {
1395 let active = self.active_focus.as_ref().unwrap();
1396 let val = active.state.text.get();
1397 if let Some(ref on_submit) = active.on_submit {
1398 on_submit(strata_dom::Event::with_value(
1399 strata_dom::EventType::Submit,
1400 val.clone(),
1401 ));
1402 }
1403 if let Some(ref on_change) = active.on_change {
1404 on_change(strata_dom::Event::with_value(
1405 strata_dom::EventType::Change,
1406 val,
1407 ));
1408 }
1409 return KeyDispatchResult::NeedsRebuild;
1410 }
1411
1412 if blur {
1413 let active = self.active_focus.take().unwrap();
1414 if !active.is_multiline {
1415 active.state.scroll_x.set(0.0);
1416 }
1417 if let Some(ref on_blur) = active.on_blur {
1418 on_blur(strata_dom::Event::new(strata_dom::EventType::Blur));
1419 }
1420 return KeyDispatchResult::NeedsRebuild;
1421 }
1422
1423 if Self::dispatch_global_shortcut_for_key(*key, *modifiers) || dom_handled {
1424 return KeyDispatchResult::NeedsRebuild;
1425 }
1426
1427 KeyDispatchResult::Ignored
1428 }
1429 _ => KeyDispatchResult::Ignored,
1430 }
1431 }
1432
1433 pub fn handle_key_event(&mut self, event: &PlatformEvent) -> bool {
1436 self.dispatch_key_event(event).is_handled()
1437 }
1438
1439 pub fn create_mouse_event(
1443 &self,
1444 event_type: strata_dom::EventType,
1445 px: f32,
1446 py: f32,
1447 button: i16,
1448 detail: i32,
1449 target_box: Option<&strata_layout::Rect>,
1450 ) -> strata_dom::Event {
1451 let mut ev = strata_dom::Event::new(event_type);
1452 ev.client_x = px as f64;
1453 ev.client_y = py as f64;
1454 ev.page_x = px as f64;
1455 ev.page_y = py as f64;
1456 ev.screen_x = px as f64;
1457 ev.screen_y = py as f64;
1458 ev.button = button;
1459 ev.buttons = match button {
1460 0 => 1,
1461 1 => 4,
1462 2 => 2,
1463 _ => 0,
1464 };
1465 ev.detail = detail;
1466 if let Some(tb) = target_box {
1467 ev.offset_x = (px - tb.x) as f64;
1468 ev.offset_y = (py - tb.y) as f64;
1469 ev.width = tb.width as f64;
1470 ev.height = tb.height as f64;
1471 } else {
1472 ev.offset_x = px as f64;
1473 ev.offset_y = py as f64;
1474 }
1475 #[cfg(target_os = "linux")]
1476 {
1477 let mods = strata_platform::gtk_current_modifiers();
1478 ev.shift_key = mods.shift;
1479 ev.ctrl_key = mods.ctrl;
1480 ev.alt_key = mods.alt;
1481 ev.meta_key = mods.meta;
1482 }
1483 ev
1484 }
1485
1486 pub fn target_is_retained_canvas3d(&self, px: f32, py: f32) -> bool {
1489 if self.tracked_retained_3d.is_empty() {
1490 return false;
1491 }
1492 let path_is_canvas = |path: &[usize]| -> bool {
1493 let mut current = &self.root_blueprint;
1494 if let NodeBlueprint::Element { tag, .. } = current {
1495 if matches!(tag, Tag::Canvas | Tag::Custom("Canvas3D")) {
1496 return true;
1497 }
1498 }
1499 for &idx in path {
1500 let mut flat = Vec::new();
1501 match current {
1502 NodeBlueprint::Element { children, .. }
1503 | NodeBlueprint::Fragment(children) => {
1504 for child in children {
1505 Self::flatten_blueprints(child, &mut flat);
1506 }
1507 }
1508 _ => return false,
1509 }
1510 if idx >= flat.len() {
1511 return false;
1512 }
1513 current = flat[idx];
1514 if let NodeBlueprint::Element { tag, .. } = current {
1515 if matches!(tag, Tag::Canvas | Tag::Custom("Canvas3D")) {
1516 return true;
1517 }
1518 }
1519 }
1520 false
1521 };
1522 if let Some((ref cap_path, _)) = self.pointer_capture_target {
1523 if path_is_canvas(cap_path) {
1524 return true;
1525 }
1526 }
1527 Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py)
1528 .as_deref()
1529 .is_some_and(path_is_canvas)
1530 }
1531
1532 pub(crate) fn hit_test_event_chain_at(
1537 &self,
1538 px: f32,
1539 py: f32,
1540 event_type: strata_dom::EventType,
1541 ) -> Option<Vec<(&NodeBlueprint, &LayoutNode)>> {
1542 let visual_path =
1543 Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py)?;
1544 let mut chain =
1545 Self::resolve_chain_for_path(&self.root_blueprint, &self.layout_root, &visual_path);
1546 let listener_idx = chain.iter().rposition(|(bp, _)| {
1547 matches!(
1548 bp,
1549 NodeBlueprint::Element { attributes, .. }
1550 if attributes.iter().any(|a| matches!(
1551 a,
1552 strata_dom::Attribute::EventListener { event, .. } if *event == event_type
1553 ))
1554 )
1555 })?;
1556 chain.truncate(listener_idx + 1);
1557 Some(chain)
1558 }
1559
1560 pub(crate) fn dispatch_bubbling_event_detailed_at(
1564 &self,
1565 event_type: strata_dom::EventType,
1566 px: f32,
1567 py: f32,
1568 button: i16,
1569 detail: i32,
1570 configure: impl Fn(&mut strata_dom::Event),
1571 ) -> BubblingOutcome {
1572 let Some(chain) = self.hit_test_event_chain_at(px, py, event_type) else {
1573 return BubblingOutcome::default();
1574 };
1575 let Some((_, target_layout)) = chain.last() else {
1576 return BubblingOutcome::default();
1577 };
1578 let chain_entities: Vec<strata_primitives::EntityId> = chain
1579 .iter()
1580 .filter_map(|(_, l)| l.entity_id.is_valid().then_some(l.entity_id))
1581 .collect();
1582 let mut ev = self.create_mouse_event(
1583 event_type,
1584 px,
1585 py,
1586 button,
1587 detail,
1588 Some(&target_layout.geometry.border_box),
1589 );
1590 let target_entity = if target_layout.entity_id.is_valid() {
1591 ev.target_id = u32::try_from(target_layout.entity_id.0).ok();
1592 Some(target_layout.entity_id)
1593 } else {
1594 None
1595 };
1596 configure(&mut ev);
1597
1598 let mut handled = false;
1599 let mut default_prevented = false;
1600 let mut capture_requested = None;
1601 let mut capture_entity = target_entity;
1602 let mut invoked_entities = Vec::new();
1603 let stopped_cell = ev.propagation_stopped.clone();
1604 let prevented_cell = ev.default_prevented.clone();
1605 let capture_cell = ev.pointer_capture_requested.clone();
1606 let warp_cell = ev.cursor_warp_requested.clone();
1607
1608 for &(bp, node_layout) in chain.iter().rev() {
1609 if let NodeBlueprint::Element { attributes, .. } = bp {
1610 let current_eid = if node_layout.entity_id.is_valid() {
1611 u32::try_from(node_layout.entity_id.0).ok()
1612 } else {
1613 None
1614 };
1615 let mut node_invoked = false;
1616 for attr in attributes {
1617 if let strata_dom::Attribute::EventListener { event, handler } = attr {
1618 if *event == event_type {
1619 let prev_cap = capture_cell.get();
1620 let call_ev = ev.clone();
1621 call_ev.current_target_id.set(current_eid);
1622 handler(call_ev);
1623 handled = true;
1624 node_invoked = true;
1625 if prevented_cell.get() {
1626 default_prevented = true;
1627 }
1628 if let Some(cap) = capture_cell.get() {
1629 if capture_cell.get() != prev_cap || capture_requested.is_none() {
1630 capture_requested = Some(cap);
1631 if node_layout.entity_id.is_valid() {
1632 capture_entity = Some(node_layout.entity_id);
1633 }
1634 }
1635 }
1636 }
1637 }
1638 }
1639 if node_invoked && node_layout.entity_id.is_valid() {
1640 invoked_entities.push(node_layout.entity_id);
1641 }
1642 if stopped_cell.get() {
1643 break;
1644 }
1645 }
1646 }
1647 BubblingOutcome {
1648 handled,
1649 default_prevented,
1650 propagation_stopped: stopped_cell.get(),
1651 capture_requested,
1652 capture_entity,
1653 cursor_warp_requested: warp_cell.get(),
1654 target_entity,
1655 chain_entities,
1656 invoked_entities,
1657 }
1658 }
1659
1660 pub(crate) fn dispatch_bubbling_event_at(
1665 &self,
1666 event_type: strata_dom::EventType,
1667 px: f32,
1668 py: f32,
1669 button: i16,
1670 detail: i32,
1671 configure: impl Fn(&mut strata_dom::Event),
1672 ) -> (bool, bool) {
1673 let outcome =
1674 self.dispatch_bubbling_event_detailed_at(event_type, px, py, button, detail, configure);
1675 (outcome.handled, outcome.default_prevented)
1676 }
1677
1678 pub fn dispatch_click(&self, px: f32, py: f32) -> bool {
1681 self.dispatch_mouse_click(px, py, 0, 1)
1682 }
1683
1684 pub fn dispatch_mouse_click(&self, px: f32, py: f32, button: i16, detail: i32) -> bool {
1687 if button == 0 {
1688 self.dispatch_bubbling_event_at(
1689 strata_dom::EventType::Click,
1690 px,
1691 py,
1692 button,
1693 detail,
1694 |_| {},
1695 )
1696 .0
1697 } else {
1698 let (aux_handled, _) = self.dispatch_bubbling_event_at(
1699 strata_dom::EventType::AuxClick,
1700 px,
1701 py,
1702 button,
1703 detail,
1704 |_| {},
1705 );
1706 if aux_handled {
1707 return true;
1708 }
1709 self.dispatch_bubbling_event_at(
1711 strata_dom::EventType::Click,
1712 px,
1713 py,
1714 button,
1715 detail,
1716 |_| {},
1717 )
1718 .0
1719 }
1720 }
1721
1722 pub fn dispatch_dblclick(&self, px: f32, py: f32) -> bool {
1725 self.dispatch_bubbling_event_at(strata_dom::EventType::DblClick, px, py, 0, 2, |_| {})
1726 .0
1727 }
1728
1729 pub fn dispatch_context_menu(&self, px: f32, py: f32) -> bool {
1733 self.dispatch_bubbling_event_at(
1734 strata_dom::EventType::ContextMenu,
1735 px,
1736 py,
1737 2,
1738 1,
1739 |_| {},
1740 )
1741 .0
1742 }
1743
1744 pub fn begin_window_drag_candidate(&mut self, px: f32, py: f32) -> bool {
1748 let region = Self::hit_test_property(
1749 &self.root_blueprint,
1750 &self.layout_root,
1751 px,
1752 py,
1753 "data-app-region",
1754 );
1755 let is_drag = region.as_deref() == Some("drag")
1756 || self
1757 .csd_controller
1758 .hit_test(self.viewport_width, self.viewport_height, px, py)
1759 == strata_platform::CsdHitZone::Titlebar;
1760
1761 if !is_drag {
1762 self.pending_window_drag = None;
1763 return false;
1764 }
1765 let now = self.now();
1766 if let Some((t, lx, ly)) = self.last_drag_click.take() {
1767 if now.duration_since(t).as_millis() < 400
1768 && (px - lx).abs() < 5.0
1769 && (py - ly).abs() < 5.0
1770 {
1771 self.pending_window_drag = None;
1773 return true;
1774 }
1775 }
1776 self.last_drag_click = Some((now, px, py));
1777 self.pending_window_drag = Some((px, py));
1778 false
1779 }
1780
1781 pub fn poll_window_drag(&mut self, px: f32, py: f32) -> bool {
1784 if let Some((sx, sy)) = self.pending_window_drag {
1785 if (px - sx).abs() > 4.0 || (py - sy).abs() > 4.0 {
1786 self.pending_window_drag = None;
1787 self.last_drag_click = None;
1788 #[cfg(target_os = "linux")]
1789 {
1790 let was_max = strata_platform::gtk_is_maximized();
1791 strata_platform::gtk_begin_window_drag(sx / self.viewport_width.max(1.0), sy);
1792 let now_max = strata_platform::gtk_is_maximized();
1793 return was_max != now_max;
1794 }
1795 #[cfg(not(target_os = "linux"))]
1796 {
1797 return true;
1798 }
1799 }
1800 }
1801 false
1802 }
1803
1804 pub(crate) fn find_draggable_path_at(&self, px: f32, py: f32) -> Option<Vec<usize>> {
1806 let hit_path = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py)?;
1807 for len in (0..=hit_path.len()).rev() {
1808 let prefix = &hit_path[..len];
1809 let Some(NodeBlueprint::Element { attributes, .. }) =
1810 Self::find_blueprint_at_path(&self.root_blueprint, prefix)
1811 else {
1812 continue;
1813 };
1814 let mut explicit_draggable: Option<bool> = None;
1815 let mut has_drag_listener = false;
1816 for attr in attributes {
1817 match attr {
1818 strata_dom::Attribute::Property { key, value } if key == "draggable" => {
1819 explicit_draggable = Some(!value.eq_ignore_ascii_case("false"));
1820 }
1821 strata_dom::Attribute::EventListener {
1822 event: strata_dom::EventType::DragStart | strata_dom::EventType::Drag,
1823 ..
1824 } => {
1825 has_drag_listener = true;
1826 }
1827 _ => {}
1828 }
1829 }
1830 if explicit_draggable == Some(true)
1831 || (explicit_draggable.is_none() && has_drag_listener)
1832 {
1833 return Some(prefix.to_vec());
1834 }
1835 }
1836 None
1837 }
1838
1839 pub(crate) fn find_drop_target_path_at(&self, px: f32, py: f32) -> Option<Vec<usize>> {
1843 let hit_path = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, px, py)?;
1844 for len in (0..=hit_path.len()).rev() {
1845 let prefix = &hit_path[..len];
1846 let Some(NodeBlueprint::Element { attributes, .. }) =
1847 Self::find_blueprint_at_path(&self.root_blueprint, prefix)
1848 else {
1849 continue;
1850 };
1851 let is_drop_zone = attributes.iter().any(|attr| {
1852 matches!(
1853 attr,
1854 strata_dom::Attribute::EventListener {
1855 event: strata_dom::EventType::DragEnter
1856 | strata_dom::EventType::DragOver
1857 | strata_dom::EventType::DragLeave
1858 | strata_dom::EventType::Drop,
1859 ..
1860 }
1861 )
1862 });
1863 if is_drop_zone {
1864 return Some(prefix.to_vec());
1865 }
1866 }
1867 Some(hit_path)
1868 }
1869
1870 pub(crate) fn dispatch_drag_event_at_path(
1873 &self,
1874 path: &[usize],
1875 event_type: strata_dom::EventType,
1876 px: f32,
1877 py: f32,
1878 data_transfer: &std::rc::Rc<
1879 std::cell::RefCell<std::collections::HashMap<String, String>>,
1880 >,
1881 ) -> (bool, bool) {
1882 if let Some((handler, target_box, _)) = Self::find_event_at_or_above_path(
1883 &self.root_blueprint,
1884 &self.layout_root,
1885 path,
1886 event_type,
1887 ) {
1888 let target_box_copy = *target_box;
1889 let mut ev =
1890 self.create_mouse_event(event_type, px, py, 0, 1, Some(&target_box_copy));
1891 ev.data_transfer = std::rc::Rc::clone(data_transfer);
1892 ev.data = data_transfer
1893 .borrow()
1894 .get("text/plain")
1895 .cloned()
1896 .or_else(|| data_transfer.borrow().values().next().cloned());
1897 let prevented_cell = ev.default_prevented.clone();
1898 handler(ev);
1899 return (true, prevented_cell.get());
1900 }
1901 (false, false)
1902 }
1903
1904 pub(crate) fn find_first_event_listener<'a>(
1905 blueprint: &'a NodeBlueprint,
1906 layout: &'a LayoutNode,
1907 event_type: strata_dom::EventType,
1908 ) -> Option<(
1909 std::rc::Rc<dyn Fn(strata_dom::Event)>,
1910 &'a strata_layout::Rect,
1911 )> {
1912 if let NodeBlueprint::Element { attributes, .. } = blueprint {
1913 for attr in attributes {
1914 if let strata_dom::Attribute::EventListener { event, handler } = attr {
1915 if *event == event_type {
1916 return Some((handler.clone(), &layout.geometry.border_box));
1917 }
1918 }
1919 }
1920 }
1921 for (_idx, child_bp, child_layout) in Self::paired_blueprint_children(blueprint, layout) {
1922 if let Some(found) =
1923 Self::find_first_event_listener(child_bp, child_layout, event_type)
1924 {
1925 return Some(found);
1926 }
1927 }
1928 None
1929 }
1930
1931 pub fn dispatch_file_drop(&mut self, paths: Vec<std::path::PathBuf>) -> bool {
1934 if paths.is_empty() {
1935 return false;
1936 }
1937 let (px, py) = self.last_mouse_pos;
1938 let hit = Self::hit_test_event_with_box(
1939 &self.root_blueprint,
1940 &self.layout_root,
1941 px,
1942 py,
1943 strata_dom::EventType::Drop,
1944 )
1945 .or_else(|| {
1946 Self::find_first_event_listener(
1947 &self.root_blueprint,
1948 &self.layout_root,
1949 strata_dom::EventType::Drop,
1950 )
1951 });
1952
1953 if let Some((handler, target_box)) = hit {
1954 let target_box_copy = *target_box;
1955 let mut ev = self.create_mouse_event(
1956 strata_dom::EventType::Drop,
1957 px,
1958 py,
1959 0,
1960 1,
1961 Some(&target_box_copy),
1962 );
1963 if let Some(first) = paths.first() {
1964 let first_str = first.to_string_lossy().into_owned();
1965 ev.data = Some(first_str.clone());
1966 ev.set_data("text/uri-list", first_str.clone());
1967 ev.set_data("text/plain", first_str);
1968 }
1969 ev.files = paths;
1970 handler(ev);
1971 return true;
1972 }
1973 false
1974 }
1975}