1use crate::{
19 Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, BackGestureEvent, Bounds, ClickEvent,
20 DispatchPhase, Display, Element, ElementId, Entity, EntityId, ExternalDragPayload,
21 ExternalDragPayloadSource, FileDropEvent, FocusHandle, Global, GlobalElementId, Hitbox,
22 HitboxBehavior, HitboxId, InspectorElementId, IsZero, KeyContext, KeyDownEvent, KeyUpEvent,
23 KeyboardButton, KeyboardClickEvent, LayoutId, LongPressEvent, ModifiersChangedEvent,
24 MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent, MouseMoveEvent,
25 MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels,
26 Point, Render, ScrollEvent, SharedString, Size, Style, StyleRefinement, Styled, Task,
27 TooltipId, TouchPhase, Visibility, Window, WindowControlArea, point, px, size,
28};
29use collections::HashMap;
30use gpui_util::ResultExt;
31use refineable::Refineable;
32use smallvec::SmallVec;
33use std::{
34 any::{Any, TypeId},
35 cell::{Cell, RefCell},
36 cmp::Ordering,
37 fmt::Debug,
38 marker::PhantomData,
39 mem,
40 rc::Rc,
41 sync::Arc,
42 time::Duration,
43};
44
45use super::ImageCacheProvider;
46
47#[cfg(feature = "stacker")]
48type StackSafe<T> = stacksafe::StackSafe<T>;
49#[cfg(not(feature = "stacker"))]
50type StackSafe<T> = T;
51
52const DRAG_THRESHOLD: f64 = 2.;
53const DEFAULT_TOOLTIP_SHOW_DELAY: Duration = Duration::from_millis(500);
54const HOVERABLE_TOOLTIP_HIDE_DELAY: Duration = Duration::from_millis(500);
55
56pub struct GroupStyle {
58 pub group: SharedString,
60
61 pub style: Box<StyleRefinement>,
64}
65
66pub struct DragMoveEvent<T> {
68 pub event: MouseMoveEvent,
70
71 pub bounds: Bounds<Pixels>,
73 drag: PhantomData<T>,
74 dragged_item: Arc<dyn Any>,
75}
76
77impl<T: 'static> DragMoveEvent<T> {
78 pub fn drag<'b>(&self, cx: &'b App) -> &'b T {
80 cx.active_drag
81 .as_ref()
82 .and_then(|drag| drag.value.downcast_ref::<T>())
83 .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
84 }
85
86 pub fn dragged_item(&self) -> &dyn Any {
88 self.dragged_item.as_ref()
89 }
90}
91
92impl Interactivity {
93 #[cfg(any(feature = "inspector", debug_assertions))]
95 #[track_caller]
96 pub fn new() -> Interactivity {
97 Interactivity {
98 source_location: Some(core::panic::Location::caller()),
99 ..Default::default()
100 }
101 }
102
103 #[cfg(not(any(feature = "inspector", debug_assertions)))]
105 pub fn new() -> Interactivity {
106 Interactivity::default()
107 }
108
109 pub fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
111 #[cfg(any(feature = "inspector", debug_assertions))]
112 {
113 self.source_location
114 }
115
116 #[cfg(not(any(feature = "inspector", debug_assertions)))]
117 {
118 None
119 }
120 }
121
122 pub fn on_mouse_down(
127 &mut self,
128 button: MouseButton,
129 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
130 ) {
131 self.mouse_down_listeners
132 .push(Box::new(move |event, phase, hitbox, window, cx| {
133 if phase == DispatchPhase::Bubble
134 && event.button == button
135 && hitbox.is_hovered(window)
136 {
137 (listener)(event, window, cx)
138 }
139 }));
140 }
141
142 pub fn capture_any_mouse_down(
147 &mut self,
148 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
149 ) {
150 self.mouse_down_listeners
151 .push(Box::new(move |event, phase, hitbox, window, cx| {
152 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
153 (listener)(event, window, cx)
154 }
155 }));
156 }
157
158 pub fn on_any_mouse_down(
163 &mut self,
164 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
165 ) {
166 self.mouse_down_listeners
167 .push(Box::new(move |event, phase, hitbox, window, cx| {
168 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
169 (listener)(event, window, cx)
170 }
171 }));
172 }
173
174 pub fn on_mouse_pressure(
179 &mut self,
180 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
181 ) {
182 self.mouse_pressure_listeners
183 .push(Box::new(move |event, phase, hitbox, window, cx| {
184 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
185 (listener)(event, window, cx)
186 }
187 }));
188 }
189
190 pub fn capture_mouse_pressure(
195 &mut self,
196 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
197 ) {
198 self.mouse_pressure_listeners
199 .push(Box::new(move |event, phase, hitbox, window, cx| {
200 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
201 (listener)(event, window, cx)
202 }
203 }));
204 }
205
206 pub fn on_mouse_up(
211 &mut self,
212 button: MouseButton,
213 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
214 ) {
215 self.mouse_up_listeners
216 .push(Box::new(move |event, phase, hitbox, window, cx| {
217 if phase == DispatchPhase::Bubble
218 && event.button == button
219 && hitbox.is_hovered(window)
220 {
221 (listener)(event, window, cx)
222 }
223 }));
224 }
225
226 pub fn capture_any_mouse_up(
231 &mut self,
232 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
233 ) {
234 self.mouse_up_listeners
235 .push(Box::new(move |event, phase, hitbox, window, cx| {
236 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
237 (listener)(event, window, cx)
238 }
239 }));
240 }
241
242 pub fn on_any_mouse_up(
247 &mut self,
248 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
249 ) {
250 self.mouse_up_listeners
251 .push(Box::new(move |event, phase, hitbox, window, cx| {
252 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
253 (listener)(event, window, cx)
254 }
255 }));
256 }
257
258 pub fn on_mouse_down_out(
264 &mut self,
265 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
266 ) {
267 self.mouse_down_listeners
268 .push(Box::new(move |event, phase, hitbox, window, cx| {
269 if phase == DispatchPhase::Capture
270 && !window.has_active_prompt()
271 && !hitbox.contains(&window.mouse_position())
272 {
273 (listener)(event, window, cx)
274 }
275 }));
276 }
277
278 pub fn on_mouse_up_out(
284 &mut self,
285 button: MouseButton,
286 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
287 ) {
288 self.mouse_up_listeners
289 .push(Box::new(move |event, phase, hitbox, window, cx| {
290 if phase == DispatchPhase::Capture
291 && event.button == button
292 && !hitbox.is_hovered(window)
293 {
294 (listener)(event, window, cx);
295 }
296 }));
297 }
298
299 pub fn on_mouse_move(
304 &mut self,
305 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
306 ) {
307 self.mouse_move_listeners
308 .push(Box::new(move |event, phase, hitbox, window, cx| {
309 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
310 (listener)(event, window, cx);
311 }
312 }));
313 }
314
315 pub fn on_mouse_exit(
320 &mut self,
321 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
322 ) {
323 self.mouse_exit_listeners
324 .push(Box::new(move |event, phase, hitbox, window, cx| {
325 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
326 (listener)(event, window, cx);
327 }
328 }));
329 }
330
331 pub fn on_file_drop_exit(
339 &mut self,
340 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
341 ) {
342 self.file_drop_exit_listeners
343 .push(Box::new(move |event, phase, hitbox, window, cx| {
344 if phase == DispatchPhase::Bubble
345 && matches!(event, FileDropEvent::Exited)
346 && hitbox.id.is_hovered_ignoring_last_input(window)
347 {
348 (listener)(event, window, cx);
349 }
350 }));
351 }
352
353 pub fn on_drag_move<T>(
361 &mut self,
362 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
363 ) where
364 T: 'static,
365 {
366 self.mouse_move_listeners
367 .push(Box::new(move |event, phase, hitbox, window, cx| {
368 if phase == DispatchPhase::Capture
369 && let Some(drag) = &cx.active_drag
370 && drag.value.as_ref().type_id() == TypeId::of::<T>()
371 {
372 (listener)(
373 &DragMoveEvent {
374 event: event.clone(),
375 bounds: hitbox.bounds,
376 drag: PhantomData,
377 dragged_item: Arc::clone(&drag.value),
378 },
379 window,
380 cx,
381 );
382 }
383 }));
384 }
385
386 pub fn on_scroll(&mut self, listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static) {
391 self.scroll_listeners
392 .push(Box::new(move |event, phase, hitbox, window, cx| {
393 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
394 (listener)(event, window, cx);
395 }
396 }));
397 }
398
399 #[deprecated(note = "renamed to `on_scroll`")]
401 pub fn on_scroll_wheel(
402 &mut self,
403 listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static,
404 ) {
405 self.on_scroll(listener);
406 }
407
408 pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
412 self.pinch_listeners
413 .push(Box::new(move |event, phase, hitbox, window, cx| {
414 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
415 (listener)(event, window, cx);
416 }
417 }));
418 }
419
420 pub fn on_back_gesture(
425 &mut self,
426 listener: impl Fn(&BackGestureEvent, &mut Window, &mut App) + 'static,
427 ) {
428 self.back_gesture_listeners
429 .push(Box::new(move |event, phase, hitbox, window, cx| {
430 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
431 (listener)(event, window, cx);
432 window.prevent_default();
433 cx.stop_propagation();
434 }
435 }));
436 }
437
438 pub fn capture_pinch(
442 &mut self,
443 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
444 ) {
445 self.pinch_listeners
446 .push(Box::new(move |event, phase, _hitbox, window, cx| {
447 if phase == DispatchPhase::Capture {
448 (listener)(event, window, cx);
449 } else {
450 cx.propagate();
451 }
452 }));
453 }
454
455 pub fn capture_action<A: Action>(
460 &mut self,
461 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
462 ) {
463 self.action_listeners.push((
464 TypeId::of::<A>(),
465 Box::new(move |action, phase, window, cx| {
466 let action = action.downcast_ref().unwrap();
467 if phase == DispatchPhase::Capture {
468 (listener)(action, window, cx)
469 } else {
470 cx.propagate();
471 }
472 }),
473 ));
474 }
475
476 #[track_caller]
481 #[inline(always)]
482 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
483 self.action_listeners.push((
484 TypeId::of::<A>(),
485 Box::new(move |action, phase, window, cx| {
486 let action = action.downcast_ref().unwrap();
487 if phase == DispatchPhase::Bubble {
488 (listener)(action, window, cx)
489 }
490 }),
491 ));
492 }
493
494 pub fn on_boxed_action(
501 &mut self,
502 action: &dyn Action,
503 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
504 ) {
505 let action = action.boxed_clone();
506 self.action_listeners.push((
507 (*action).type_id(),
508 Box::new(move |_, phase, window, cx| {
509 if phase == DispatchPhase::Bubble {
510 (listener)(&*action, window, cx)
511 }
512 }),
513 ));
514 }
515
516 pub fn on_key_down(
521 &mut self,
522 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
523 ) {
524 self.key_down_listeners
525 .push(Box::new(move |event, phase, window, cx| {
526 if phase == DispatchPhase::Bubble {
527 (listener)(event, window, cx)
528 }
529 }));
530 }
531
532 pub fn capture_key_down(
537 &mut self,
538 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
539 ) {
540 self.key_down_listeners
541 .push(Box::new(move |event, phase, window, cx| {
542 if phase == DispatchPhase::Capture {
543 listener(event, window, cx)
544 }
545 }));
546 }
547
548 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
553 self.key_up_listeners
554 .push(Box::new(move |event, phase, window, cx| {
555 if phase == DispatchPhase::Bubble {
556 listener(event, window, cx)
557 }
558 }));
559 }
560
561 pub fn capture_key_up(
566 &mut self,
567 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
568 ) {
569 self.key_up_listeners
570 .push(Box::new(move |event, phase, window, cx| {
571 if phase == DispatchPhase::Capture {
572 listener(event, window, cx)
573 }
574 }));
575 }
576
577 pub fn on_modifiers_changed(
582 &mut self,
583 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
584 ) {
585 self.modifiers_changed_listeners.push(Box::new(listener));
586 }
587
588 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
593 self.drop_listeners.push((
594 TypeId::of::<T>(),
595 Box::new(move |dragged_value, window, cx| {
596 listener(dragged_value.downcast_ref().unwrap(), window, cx);
597 }),
598 ));
599 }
600
601 pub fn can_drop(
604 &mut self,
605 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
606 ) {
607 self.can_drop_predicate = Some(Box::new(predicate));
608 }
609
610 #[inline(always)]
615 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
616 where
617 Self: Sized,
618 {
619 self.click_listeners.push(Rc::new(listener));
620 }
621
622 pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
627 where
628 Self: Sized,
629 {
630 self.aux_click_listeners.push(Rc::new(listener));
631 }
632
633 pub fn on_drag<T, W>(
640 &mut self,
641 value: T,
642 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
643 ) where
644 Self: Sized,
645 T: 'static,
646 W: 'static + Render,
647 {
648 debug_assert!(
649 self.drag_listener.is_none(),
650 "calling on_drag more than once on the same element is not supported"
651 );
652 self.drag_listener = Some(DragListener {
653 value: Arc::new(value),
654 render: Box::new(move |value, offset, window, cx| {
655 constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
656 }),
657 external_payload: None,
658 });
659 }
660
661 pub fn external_drag_payload<T>(
666 &mut self,
667 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
668 ) where
669 Self: Sized,
670 T: 'static,
671 {
672 let Some(drag_listener) = self.drag_listener.as_mut() else {
673 debug_assert!(false, "external_drag_payload must be called after on_drag");
674 return;
675 };
676 debug_assert!(
677 drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
678 "external_drag_payload must use the same dragged value type as on_drag"
679 );
680 debug_assert!(
681 drag_listener.external_payload.is_none(),
682 "calling external_drag_payload more than once on the same element is not supported"
683 );
684 drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
685 resolver(value.downcast_ref::<T>()?, window, cx)
686 }));
687 }
688
689 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
700 where
701 Self: Sized,
702 {
703 debug_assert!(
704 self.hover_listener.is_none(),
705 "calling on_hover more than once on the same element is not supported"
706 );
707 self.hover_listener = Some(Box::new(listener));
708 }
709
710 pub fn hover_listener_mode(&mut self, mode: HoverListenerMode)
714 where
715 Self: Sized,
716 {
717 self.hover_listener_mode = mode;
718 }
719
720 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
723 where
724 Self: Sized,
725 {
726 debug_assert!(
727 self.tooltip_builder.is_none(),
728 "calling tooltip more than once on the same element is not supported"
729 );
730 self.tooltip_builder = Some(TooltipBuilder {
731 build: Rc::new(build_tooltip),
732 hoverable: false,
733 });
734 }
735
736 pub fn hoverable_tooltip(
740 &mut self,
741 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
742 ) where
743 Self: Sized,
744 {
745 debug_assert!(
746 self.tooltip_builder.is_none(),
747 "calling tooltip more than once on the same element is not supported"
748 );
749 self.tooltip_builder = Some(TooltipBuilder {
750 build: Rc::new(build_tooltip),
751 hoverable: true,
752 });
753 }
754
755 pub fn tooltip_show_delay(&mut self, delay: Duration) {
760 self.tooltip_show_delay = Some(delay);
761 }
762
763 pub fn occlude_mouse(&mut self) {
768 self.hitbox_behavior = HitboxBehavior::BlockMouse;
769 }
770
771 pub fn window_control_area(&mut self, area: WindowControlArea) {
774 self.window_control = Some(area);
775 }
776
777 pub fn block_mouse_except_scroll(&mut self) {
782 self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
783 }
784
785 fn has_pinch_listeners(&self) -> bool {
786 !self.pinch_listeners.is_empty()
787 }
788}
789
790pub trait InteractiveElement: Sized {
793 fn interactivity(&mut self) -> &mut Interactivity;
795
796 fn group(mut self, group: impl Into<SharedString>) -> Self {
798 self.interactivity().group = Some(group.into());
799 self
800 }
801
802 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
804 self.interactivity().element_id = Some(id.into());
805
806 Stateful { element: self }
807 }
808
809 fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
813 self.interactivity().focusable = true;
814 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
815 self
816 }
817
818 fn tab_stop(mut self, tab_stop: bool) -> Self {
825 self.interactivity().tab_stop = tab_stop;
826 self
827 }
828
829 fn tab_index(mut self, index: isize) -> Self {
834 self.interactivity().focusable = true;
835 self.interactivity().tab_index = Some(index);
836 self.interactivity().tab_stop = true;
837 self
838 }
839
840 fn tab_group(mut self) -> Self {
845 self.interactivity().tab_group = true;
846 if self.interactivity().tab_index.is_none() {
847 self.interactivity().tab_index = Some(0);
848 }
849 self
850 }
851
852 fn key_context<C, E>(mut self, key_context: C) -> Self
855 where
856 C: TryInto<KeyContext, Error = E>,
857 E: std::fmt::Display,
858 {
859 if let Some(key_context) = key_context.try_into().log_err() {
860 self.interactivity().key_context = Some(key_context);
861 }
862 self
863 }
864
865 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
867 debug_assert!(
868 self.interactivity().hover_style.is_none(),
869 "hover style already set"
870 );
871 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
872 self
873 }
874
875 fn group_hover(
877 mut self,
878 group_name: impl Into<SharedString>,
879 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
880 ) -> Self {
881 self.interactivity().group_hover_style = Some(GroupStyle {
882 group: group_name.into(),
883 style: Box::new(f(StyleRefinement::default())),
884 });
885 self
886 }
887
888 #[inline(always)]
893 fn on_mouse_down(
894 mut self,
895 button: MouseButton,
896 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
897 ) -> Self {
898 self.interactivity().on_mouse_down(button, listener);
899 self
900 }
901
902 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
909 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
910 self.interactivity().debug_selector = Some(f());
911 self
912 }
913
914 #[cfg(not(any(test, all(debug_assertions, feature = "test-support"))))]
921 #[inline]
922 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
923 self
924 }
925
926 fn capture_any_mouse_down(
931 mut self,
932 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
933 ) -> Self {
934 self.interactivity().capture_any_mouse_down(listener);
935 self
936 }
937
938 fn on_any_mouse_down(
943 mut self,
944 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
945 ) -> Self {
946 self.interactivity().on_any_mouse_down(listener);
947 self
948 }
949
950 fn on_mouse_up(
955 mut self,
956 button: MouseButton,
957 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
958 ) -> Self {
959 self.interactivity().on_mouse_up(button, listener);
960 self
961 }
962
963 fn capture_any_mouse_up(
968 mut self,
969 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
970 ) -> Self {
971 self.interactivity().capture_any_mouse_up(listener);
972 self
973 }
974
975 fn on_mouse_pressure(
980 mut self,
981 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
982 ) -> Self {
983 self.interactivity().on_mouse_pressure(listener);
984 self
985 }
986
987 fn capture_mouse_pressure(
992 mut self,
993 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
994 ) -> Self {
995 self.interactivity().capture_mouse_pressure(listener);
996 self
997 }
998
999 fn on_mouse_down_out(
1005 mut self,
1006 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
1007 ) -> Self {
1008 self.interactivity().on_mouse_down_out(listener);
1009 self
1010 }
1011
1012 fn on_mouse_up_out(
1018 mut self,
1019 button: MouseButton,
1020 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
1021 ) -> Self {
1022 self.interactivity().on_mouse_up_out(button, listener);
1023 self
1024 }
1025
1026 fn on_mouse_move(
1031 mut self,
1032 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
1033 ) -> Self {
1034 self.interactivity().on_mouse_move(listener);
1035 self
1036 }
1037
1038 fn on_mouse_exit(
1043 mut self,
1044 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
1045 ) -> Self {
1046 self.interactivity().on_mouse_exit(listener);
1047 self
1048 }
1049
1050 fn on_file_drop_exit(
1058 mut self,
1059 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
1060 ) -> Self {
1061 self.interactivity().on_file_drop_exit(listener);
1062 self
1063 }
1064
1065 fn on_drag_move<T: 'static>(
1073 mut self,
1074 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
1075 ) -> Self {
1076 self.interactivity().on_drag_move(listener);
1077 self
1078 }
1079
1080 fn on_scroll(
1085 mut self,
1086 listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static,
1087 ) -> Self {
1088 self.interactivity().on_scroll(listener);
1089 self
1090 }
1091
1092 #[deprecated(note = "renamed to `on_scroll`")]
1094 fn on_scroll_wheel(
1095 self,
1096 listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static,
1097 ) -> Self {
1098 self.on_scroll(listener)
1099 }
1100
1101 fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
1106 self.interactivity().on_pinch(listener);
1107 self
1108 }
1109
1110 fn on_back_gesture(
1117 mut self,
1118 listener: impl Fn(&BackGestureEvent, &mut Window, &mut App) + 'static,
1119 ) -> Self {
1120 self.interactivity().on_back_gesture(listener);
1121 self
1122 }
1123
1124 fn capture_pinch(
1129 mut self,
1130 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
1131 ) -> Self {
1132 self.interactivity().capture_pinch(listener);
1133 self
1134 }
1135 fn capture_action<A: Action>(
1140 mut self,
1141 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1142 ) -> Self {
1143 self.interactivity().capture_action(listener);
1144 self
1145 }
1146
1147 #[track_caller]
1152 #[inline(always)]
1153 fn on_action<A: Action>(
1154 mut self,
1155 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1156 ) -> Self {
1157 self.interactivity().on_action(listener);
1158 self
1159 }
1160
1161 fn on_boxed_action(
1168 mut self,
1169 action: &dyn Action,
1170 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1171 ) -> Self {
1172 self.interactivity().on_boxed_action(action, listener);
1173 self
1174 }
1175
1176 fn on_key_down(
1181 mut self,
1182 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1183 ) -> Self {
1184 self.interactivity().on_key_down(listener);
1185 self
1186 }
1187
1188 fn capture_key_down(
1193 mut self,
1194 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1195 ) -> Self {
1196 self.interactivity().capture_key_down(listener);
1197 self
1198 }
1199
1200 fn on_key_up(
1205 mut self,
1206 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1207 ) -> Self {
1208 self.interactivity().on_key_up(listener);
1209 self
1210 }
1211
1212 fn capture_key_up(
1217 mut self,
1218 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1219 ) -> Self {
1220 self.interactivity().capture_key_up(listener);
1221 self
1222 }
1223
1224 #[inline(always)]
1229 fn on_modifiers_changed(
1230 mut self,
1231 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1232 ) -> Self {
1233 self.interactivity().on_modifiers_changed(listener);
1234 self
1235 }
1236
1237 fn drag_over<S: 'static>(
1239 mut self,
1240 f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1241 ) -> Self {
1242 self.interactivity().drag_over_styles.push((
1243 TypeId::of::<S>(),
1244 Box::new(move |currently_dragged: &dyn Any, window, cx| {
1245 f(
1246 StyleRefinement::default(),
1247 currently_dragged.downcast_ref::<S>().unwrap(),
1248 window,
1249 cx,
1250 )
1251 }),
1252 ));
1253 self
1254 }
1255
1256 fn group_drag_over<S: 'static>(
1258 mut self,
1259 group_name: impl Into<SharedString>,
1260 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1261 ) -> Self {
1262 self.interactivity().group_drag_over_styles.push((
1263 TypeId::of::<S>(),
1264 GroupStyle {
1265 group: group_name.into(),
1266 style: Box::new(f(StyleRefinement::default())),
1267 },
1268 ));
1269 self
1270 }
1271
1272 fn on_drop<T: 'static>(
1277 mut self,
1278 listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1279 ) -> Self {
1280 self.interactivity().on_drop(listener);
1281 self
1282 }
1283
1284 fn can_drop(
1287 mut self,
1288 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1289 ) -> Self {
1290 self.interactivity().can_drop(predicate);
1291 self
1292 }
1293
1294 fn occlude(mut self) -> Self {
1298 self.interactivity().occlude_mouse();
1299 self
1300 }
1301
1302 fn window_control_area(mut self, area: WindowControlArea) -> Self {
1305 self.interactivity().window_control_area(area);
1306 self
1307 }
1308
1309 fn block_mouse_except_scroll(mut self) -> Self {
1314 self.interactivity().block_mouse_except_scroll();
1315 self
1316 }
1317
1318 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1321 where
1322 Self: Sized,
1323 {
1324 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1325 self
1326 }
1327
1328 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1331 where
1332 Self: Sized,
1333 {
1334 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1335 self
1336 }
1337
1338 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1343 where
1344 Self: Sized,
1345 {
1346 self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1347 self
1348 }
1349}
1350
1351pub trait StatefulInteractiveElement: InteractiveElement {
1354 fn role(mut self, role: accesskit::Role) -> Self {
1358 debug_assert!(
1359 role != accesskit::Role::GenericContainer,
1360 "GenericContainer is filtered out of the a11y tree and has no effect"
1361 );
1362 self.interactivity().override_role = Some(role);
1363 self
1364 }
1365
1366 fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self {
1374 self.interactivity().aria.author_id = Some(id.into());
1375 self
1376 }
1377
1378 fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1380 self.interactivity().aria.label = Some(label.into());
1381 self
1382 }
1383
1384 fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
1389 self.interactivity().aria.description = Some(description.into());
1390 self
1391 }
1392
1393 fn aria_keyshortcuts(mut self, keyshortcuts: impl Into<SharedString>) -> Self {
1399 self.interactivity().aria.keyshortcuts = Some(keyshortcuts.into());
1400 self
1401 }
1402
1403 fn aria_active_descendant(mut self) -> Self {
1419 self.interactivity().report_active_descendant_focus = true;
1420 self
1421 }
1422
1423 fn a11y_synthetic_children(
1433 mut self,
1434 f: impl FnOnce(&mut crate::A11ySubtreeBuilder) + 'static,
1435 ) -> Self {
1436 self.interactivity().a11y_synthetic_children = Some(Box::new(f));
1437 self
1438 }
1439
1440 fn aria_selected(mut self, selected: bool) -> Self {
1442 self.interactivity().aria.selected = Some(selected);
1443 self
1444 }
1445
1446 fn aria_expanded(mut self, expanded: bool) -> Self {
1448 self.interactivity().aria.expanded = Some(expanded);
1449 self
1450 }
1451
1452 fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1454 self.interactivity().aria.toggled = Some(toggled);
1455 self
1456 }
1457
1458 fn aria_numeric_value(mut self, value: f64) -> Self {
1460 self.interactivity().aria.numeric_value = Some(value);
1461 self
1462 }
1463
1464 fn aria_numeric_value_step(mut self, step: f64) -> Self {
1467 self.interactivity().aria.numeric_value_step = Some(step);
1468 self
1469 }
1470
1471 fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
1474 self.interactivity().aria.value = Some(value.into());
1475 self
1476 }
1477
1478 fn aria_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1481 self.interactivity().aria.placeholder = Some(placeholder.into());
1482 self
1483 }
1484
1485 fn aria_min_numeric_value(mut self, value: f64) -> Self {
1487 self.interactivity().aria.min_numeric_value = Some(value);
1488 self
1489 }
1490
1491 fn aria_max_numeric_value(mut self, value: f64) -> Self {
1493 self.interactivity().aria.max_numeric_value = Some(value);
1494 self
1495 }
1496
1497 fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1499 self.interactivity().aria.orientation = Some(orientation);
1500 self
1501 }
1502
1503 fn aria_level(mut self, level: usize) -> Self {
1505 self.interactivity().aria.level = Some(level);
1506 self
1507 }
1508
1509 fn aria_position_in_set(mut self, position: usize) -> Self {
1511 self.interactivity().aria.position_in_set = Some(position);
1512 self
1513 }
1514
1515 fn aria_size_of_set(mut self, size: usize) -> Self {
1517 self.interactivity().aria.size_of_set = Some(size);
1518 self
1519 }
1520
1521 fn aria_row_index(mut self, index: usize) -> Self {
1523 self.interactivity().aria.row_index = Some(index);
1524 self
1525 }
1526
1527 fn aria_column_index(mut self, index: usize) -> Self {
1529 self.interactivity().aria.column_index = Some(index);
1530 self
1531 }
1532
1533 fn aria_row_count(mut self, count: usize) -> Self {
1535 self.interactivity().aria.row_count = Some(count);
1536 self
1537 }
1538
1539 fn aria_column_count(mut self, count: usize) -> Self {
1541 self.interactivity().aria.column_count = Some(count);
1542 self
1543 }
1544
1545 #[inline(always)]
1550 fn on_a11y_action(
1551 mut self,
1552 action: accesskit::Action,
1553 listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1554 + 'static,
1555 ) -> Self {
1556 self.interactivity()
1557 .a11y_action_listeners
1558 .push((action, Box::new(listener)));
1559 self
1560 }
1561
1562 fn focusable(mut self) -> Self {
1564 self.interactivity().focusable = true;
1565 self
1566 }
1567
1568 fn overflow_scroll(mut self) -> Self {
1570 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1571 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1572 self
1573 }
1574
1575 fn overflow_x_scroll(mut self) -> Self {
1577 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1578 self
1579 }
1580
1581 fn overflow_y_scroll(mut self) -> Self {
1583 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1584 self
1585 }
1586
1587 fn restrict_scroll_to_axis(mut self) -> Self {
1591 self.interactivity().base_style.restrict_scroll_to_axis = Some(true);
1592 self
1593 }
1594
1595 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1597 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1598 self
1599 }
1600
1601 fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1603 self.interactivity().scroll_anchor = scroll_anchor;
1604 self
1605 }
1606
1607 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1609 where
1610 Self: Sized,
1611 {
1612 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1613 self
1614 }
1615
1616 fn group_active(
1618 mut self,
1619 group_name: impl Into<SharedString>,
1620 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1621 ) -> Self
1622 where
1623 Self: Sized,
1624 {
1625 self.interactivity().group_active_style = Some(GroupStyle {
1626 group: group_name.into(),
1627 style: Box::new(f(StyleRefinement::default())),
1628 });
1629 self
1630 }
1631
1632 #[inline(always)]
1637 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1638 where
1639 Self: Sized,
1640 {
1641 self.interactivity().on_click(listener);
1642 self
1643 }
1644
1645 fn on_aux_click(
1650 mut self,
1651 listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1652 ) -> Self
1653 where
1654 Self: Sized,
1655 {
1656 self.interactivity().on_aux_click(listener);
1657 self
1658 }
1659
1660 fn on_drag<T, W>(
1668 mut self,
1669 value: T,
1670 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1671 ) -> Self
1672 where
1673 Self: Sized,
1674 T: 'static,
1675 W: 'static + Render,
1676 {
1677 self.interactivity().on_drag(value, constructor);
1678 self
1679 }
1680
1681 fn external_drag_payload<T>(
1687 mut self,
1688 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
1689 ) -> Self
1690 where
1691 Self: Sized,
1692 T: 'static,
1693 {
1694 self.interactivity().external_drag_payload(resolver);
1695 self
1696 }
1697
1698 fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1709 where
1710 Self: Sized,
1711 {
1712 self.interactivity().on_hover(listener);
1713 self
1714 }
1715
1716 fn hover_listener_mode(mut self, mode: HoverListenerMode) -> Self
1720 where
1721 Self: Sized,
1722 {
1723 self.interactivity().hover_listener_mode(mode);
1724 self
1725 }
1726
1727 fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1730 where
1731 Self: Sized,
1732 {
1733 self.interactivity().tooltip(build_tooltip);
1734 self
1735 }
1736
1737 fn hoverable_tooltip(
1741 mut self,
1742 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1743 ) -> Self
1744 where
1745 Self: Sized,
1746 {
1747 self.interactivity().hoverable_tooltip(build_tooltip);
1748 self
1749 }
1750
1751 fn tooltip_show_delay(mut self, delay: Duration) -> Self
1756 where
1757 Self: Sized,
1758 {
1759 self.interactivity().tooltip_show_delay(delay);
1760 self
1761 }
1762}
1763
1764pub(crate) type MouseDownListener =
1765 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1766pub(crate) type MouseUpListener =
1767 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1768pub(crate) type MousePressureListener =
1769 Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1770pub(crate) type MouseMoveListener =
1771 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1772pub(crate) type MouseExitListener =
1773 Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1774
1775pub(crate) type FileDropExitListener =
1776 Box<dyn Fn(&FileDropEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1777
1778pub(crate) type ScrollListener =
1779 Box<dyn Fn(&ScrollEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1780
1781pub(crate) type PinchListener =
1782 Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1783
1784pub(crate) type BackGestureListener =
1785 Box<dyn Fn(&BackGestureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1786
1787pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1788
1789#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1792pub enum HoverListenerMode {
1793 #[default]
1796 InputModalityAware,
1797 InputModalityIndependent,
1801}
1802
1803impl HoverListenerMode {
1804 fn is_hovered(self, hitbox: &Hitbox, window: &Window) -> bool {
1805 match self {
1806 Self::InputModalityAware => hitbox.is_hovered(window),
1807 Self::InputModalityIndependent => hitbox.id.is_hovered_ignoring_last_input(window),
1808 }
1809 }
1810}
1811
1812pub(crate) struct DragListener {
1813 value: Arc<dyn Any>,
1814 render: Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>,
1815 external_payload: Option<ExternalDragPayloadResolver>,
1816}
1817
1818type ExternalDragPayloadResolver =
1819 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
1820
1821type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1822
1823type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1824
1825pub(crate) struct TooltipBuilder {
1826 build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1827 hoverable: bool,
1828}
1829
1830pub(crate) type KeyDownListener =
1831 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1832
1833pub(crate) type KeyUpListener =
1834 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1835
1836pub(crate) type ModifiersChangedListener =
1837 Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1838
1839pub(crate) type ActionListener =
1840 Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1841
1842#[track_caller]
1844pub fn div() -> Div {
1845 #[allow(unused_mut)]
1846 let mut interactivity = InteractivityBox::new();
1847 #[cfg(any(feature = "inspector", debug_assertions))]
1848 {
1849 interactivity.source_location = Some(core::panic::Location::caller());
1850 }
1851 Div {
1852 interactivity,
1853 children: SmallVec::default(),
1854 prepaint_listener: None,
1855 image_cache: None,
1856 prepaint_order_fn: None,
1857 }
1858}
1859
1860enum InteractivityBox {
1864 Arena(crate::ArenaBox<Interactivity>),
1865 Heap(Box<Interactivity>),
1866}
1867
1868impl InteractivityBox {
1869 #[inline]
1871 fn new() -> Self {
1872 if crate::window::draw_in_progress() {
1873 Self::Arena(crate::window::with_element_arena(|arena| {
1874 arena.alloc(Interactivity::default)
1875 }))
1876 } else {
1877 Self::Heap(Box::default())
1878 }
1879 }
1880}
1881
1882impl std::ops::Deref for InteractivityBox {
1883 type Target = Interactivity;
1884
1885 #[inline]
1886 fn deref(&self) -> &Interactivity {
1887 match self {
1888 Self::Arena(interactivity) => interactivity,
1889 Self::Heap(interactivity) => interactivity,
1890 }
1891 }
1892}
1893
1894impl std::ops::DerefMut for InteractivityBox {
1895 #[inline]
1896 fn deref_mut(&mut self) -> &mut Interactivity {
1897 match self {
1898 Self::Arena(interactivity) => interactivity,
1899 Self::Heap(interactivity) => interactivity,
1900 }
1901 }
1902}
1903
1904pub struct Div {
1906 interactivity: InteractivityBox,
1909 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1910 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1911 image_cache: Option<Box<dyn ImageCacheProvider>>,
1912 prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1913}
1914
1915impl Div {
1916 pub fn on_children_prepainted(
1919 mut self,
1920 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1921 ) -> Self {
1922 self.prepaint_listener = Some(Box::new(listener));
1923 self
1924 }
1925
1926 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1928 self.image_cache = Some(Box::new(cache));
1929 self
1930 }
1931
1932 pub fn with_dynamic_prepaint_order(
1941 mut self,
1942 order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1943 ) -> Self {
1944 self.prepaint_order_fn = Some(Box::new(order_fn));
1945 self
1946 }
1947}
1948
1949pub struct DivFrameState {
1956 child_layout_ids: SmallVec<[LayoutId; 2]>,
1957}
1958
1959#[derive(Clone)]
1961pub struct DivInspectorState {
1962 #[cfg(any(feature = "inspector", debug_assertions))]
1966 pub base_style: Box<StyleRefinement>,
1967 pub bounds: Bounds<Pixels>,
1969 pub content_size: Size<Pixels>,
1971}
1972
1973impl Styled for Div {
1974 fn style(&mut self) -> &mut StyleRefinement {
1975 &mut self.interactivity.base_style
1976 }
1977}
1978
1979impl InteractiveElement for Div {
1980 fn interactivity(&mut self) -> &mut Interactivity {
1981 &mut self.interactivity
1982 }
1983}
1984
1985impl ParentElement for Div {
1986 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1987 #[cfg(feature = "stacker")]
1988 self.children
1989 .extend(elements.into_iter().map(StackSafe::new));
1990 #[cfg(not(feature = "stacker"))]
1991 self.children.extend(elements);
1992 }
1993}
1994
1995impl Element for Div {
1996 type RequestLayoutState = DivFrameState;
1997 type PrepaintState = Option<Hitbox>;
1998
1999 fn id(&self) -> Option<ElementId> {
2000 self.interactivity.element_id.clone()
2001 }
2002
2003 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
2004 self.interactivity.source_location()
2005 }
2006
2007 fn a11y_role(&self) -> Option<accesskit::Role> {
2008 self.interactivity
2011 .override_role
2012 .filter(|role| *role != accesskit::Role::GenericContainer)
2013 }
2014
2015 fn write_a11y_info(&self, node: &mut accesskit::Node) {
2016 self.interactivity.write_a11y_info(node);
2017 }
2018
2019 fn a11y_synthetic_children(
2020 &mut self,
2021 _prepaint: &mut Self::PrepaintState,
2022 builder: &mut crate::A11ySubtreeBuilder,
2023 ) {
2024 if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
2025 f(builder);
2026 }
2027 }
2028
2029 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2030 fn request_layout(
2031 &mut self,
2032 global_id: Option<&GlobalElementId>,
2033 inspector_id: Option<&InspectorElementId>,
2034 window: &mut Window,
2035 cx: &mut App,
2036 ) -> (LayoutId, Self::RequestLayoutState) {
2037 let mut child_layout_ids = SmallVec::new();
2038 let image_cache = self
2039 .image_cache
2040 .as_mut()
2041 .map(|provider| provider.provide(window, cx));
2042
2043 let layout_id = window.with_image_cache(image_cache, |window| {
2044 self.interactivity.request_layout(
2045 global_id,
2046 inspector_id,
2047 window,
2048 cx,
2049 |style, window, cx| {
2050 window.with_text_style(style.text_style().cloned(), |window| {
2051 child_layout_ids = self
2052 .children
2053 .iter_mut()
2054 .map(|child| child.request_layout(window, cx))
2055 .collect::<SmallVec<_>>();
2056 window.request_layout(style, child_layout_ids.iter().copied(), cx)
2057 })
2058 },
2059 )
2060 });
2061
2062 (layout_id, DivFrameState { child_layout_ids })
2063 }
2064
2065 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2066 fn prepaint(
2067 &mut self,
2068 global_id: Option<&GlobalElementId>,
2069 inspector_id: Option<&InspectorElementId>,
2070 bounds: Bounds<Pixels>,
2071 request_layout: &mut Self::RequestLayoutState,
2072 window: &mut Window,
2073 cx: &mut App,
2074 ) -> Option<Hitbox> {
2075 let image_cache = self
2076 .image_cache
2077 .as_mut()
2078 .map(|provider| provider.provide(window, cx));
2079
2080 let has_prepaint_listener = self.prepaint_listener.is_some();
2081 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
2082 request_layout.child_layout_ids.len()
2083 } else {
2084 0
2085 });
2086
2087 let mut child_min = point(Pixels::MAX, Pixels::MAX);
2088 let mut child_max = Point::default();
2089 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
2090 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
2091 }
2092 let content_size = if request_layout.child_layout_ids.is_empty() {
2093 bounds.size
2094 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2095 let mut state = scroll_handle.0.borrow_mut();
2096 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
2097 for child_layout_id in &request_layout.child_layout_ids {
2098 let child_bounds = window.layout_bounds(*child_layout_id);
2099 child_min = child_min.min(&child_bounds.origin);
2100 child_max = child_max.max(&child_bounds.bottom_right());
2101 state.child_bounds.push(child_bounds);
2102 }
2103 (child_max - child_min).into()
2104 } else {
2105 for child_layout_id in &request_layout.child_layout_ids {
2106 let child_bounds = window.layout_bounds(*child_layout_id);
2107 child_min = child_min.min(&child_bounds.origin);
2108 child_max = child_max.max(&child_bounds.bottom_right());
2109
2110 if has_prepaint_listener {
2111 children_bounds.push(child_bounds);
2112 }
2113 }
2114 (child_max - child_min).into()
2115 };
2116
2117 if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2118 scroll_handle.scroll_to_active_item();
2119 }
2120
2121 self.interactivity.prepaint(
2122 global_id,
2123 inspector_id,
2124 bounds,
2125 content_size,
2126 window,
2127 cx,
2128 |style, scroll_offset, hitbox, window, cx| {
2129 if style.display == Display::None {
2131 return hitbox;
2132 }
2133
2134 window.with_image_cache(image_cache, |window| {
2135 window.with_element_offset(scroll_offset, |window| {
2136 if let Some(order_fn) = &self.prepaint_order_fn {
2137 let order = order_fn(window, cx);
2138 for idx in order {
2139 if let Some(child) = self.children.get_mut(idx) {
2140 child.prepaint(window, cx);
2141 }
2142 }
2143 } else {
2144 for child in &mut self.children {
2145 child.prepaint(window, cx);
2146 }
2147 }
2148 });
2149
2150 if let Some(listener) = self.prepaint_listener.as_ref() {
2151 listener(children_bounds, window, cx);
2152 }
2153 });
2154
2155 hitbox
2156 },
2157 )
2158 }
2159
2160 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2161 fn paint(
2162 &mut self,
2163 global_id: Option<&GlobalElementId>,
2164 inspector_id: Option<&InspectorElementId>,
2165 bounds: Bounds<Pixels>,
2166 _request_layout: &mut Self::RequestLayoutState,
2167 hitbox: &mut Option<Hitbox>,
2168 window: &mut Window,
2169 cx: &mut App,
2170 ) {
2171 let image_cache = self
2172 .image_cache
2173 .as_mut()
2174 .map(|provider| provider.provide(window, cx));
2175
2176 window.with_image_cache(image_cache, |window| {
2177 self.interactivity.paint(
2178 global_id,
2179 inspector_id,
2180 bounds,
2181 hitbox.as_ref(),
2182 window,
2183 cx,
2184 |style, window, cx| {
2185 if style.display == Display::None {
2187 return;
2188 }
2189
2190 for child in &mut self.children {
2191 child.paint(window, cx);
2192 }
2193 },
2194 )
2195 });
2196 }
2197}
2198
2199#[derive(Default)]
2200pub(crate) struct AriaProperties {
2201 pub(crate) author_id: Option<SharedString>,
2202 pub(crate) label: Option<SharedString>,
2203 pub(crate) description: Option<SharedString>,
2204 pub(crate) keyshortcuts: Option<SharedString>,
2205 pub(crate) selected: Option<bool>,
2206 pub(crate) expanded: Option<bool>,
2207 pub(crate) toggled: Option<accesskit::Toggled>,
2208 pub(crate) numeric_value: Option<f64>,
2209 pub(crate) min_numeric_value: Option<f64>,
2210 pub(crate) max_numeric_value: Option<f64>,
2211 pub(crate) numeric_value_step: Option<f64>,
2212 pub(crate) value: Option<SharedString>,
2213 pub(crate) placeholder: Option<SharedString>,
2214 pub(crate) orientation: Option<accesskit::Orientation>,
2215 pub(crate) level: Option<usize>,
2216 pub(crate) position_in_set: Option<usize>,
2217 pub(crate) size_of_set: Option<usize>,
2218 pub(crate) row_index: Option<usize>,
2219 pub(crate) column_index: Option<usize>,
2220 pub(crate) row_count: Option<usize>,
2221 pub(crate) column_count: Option<usize>,
2222}
2223
2224#[derive(Default)]
2227pub struct Interactivity {
2228 pub element_id: Option<ElementId>,
2230 pub active: Option<bool>,
2232 pub hovered: Option<bool>,
2235 pub(crate) tooltip_id: Option<TooltipId>,
2236 pub(crate) content_size: Size<Pixels>,
2237 pub(crate) key_context: Option<KeyContext>,
2238 pub(crate) focusable: bool,
2239 pub(crate) tracked_focus_handle: Option<FocusHandle>,
2240 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2241 pub(crate) scroll_anchor: Option<ScrollAnchor>,
2242 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2243 pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2244 pub(crate) group: Option<SharedString>,
2245 pub base_style: Box<StyleRefinement>,
2248 pub(crate) focus_style: Option<Box<StyleRefinement>>,
2249 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2250 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2251 pub(crate) hover_style: Option<Box<StyleRefinement>>,
2252 pub(crate) group_hover_style: Option<GroupStyle>,
2253 pub(crate) active_style: Option<Box<StyleRefinement>>,
2254 pub(crate) group_active_style: Option<GroupStyle>,
2255 pub(crate) drag_over_styles: Vec<(
2256 TypeId,
2257 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2258 )>,
2259 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
2260 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
2261 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
2262 pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
2263 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
2264 pub(crate) mouse_exit_listeners: Vec<MouseExitListener>,
2265 pub(crate) file_drop_exit_listeners: Vec<FileDropExitListener>,
2266 pub(crate) scroll_listeners: Vec<ScrollListener>,
2267 pub(crate) pinch_listeners: Vec<PinchListener>,
2268 pub(crate) back_gesture_listeners: Vec<BackGestureListener>,
2269 pub(crate) key_down_listeners: Vec<KeyDownListener>,
2270 pub(crate) key_up_listeners: Vec<KeyUpListener>,
2271 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
2272 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
2273 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
2274 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
2275 pub(crate) click_listeners: Vec<ClickListener>,
2276 pub(crate) aux_click_listeners: Vec<ClickListener>,
2277 pub(crate) drag_listener: Option<DragListener>,
2278 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2279 pub(crate) hover_listener_mode: HoverListenerMode,
2280 pub(crate) tooltip_builder: Option<TooltipBuilder>,
2281 pub(crate) tooltip_show_delay: Option<Duration>,
2282 pub(crate) window_control: Option<WindowControlArea>,
2283 pub(crate) hitbox_behavior: HitboxBehavior,
2284 pub(crate) tab_index: Option<isize>,
2285 pub(crate) tab_group: bool,
2286 pub(crate) tab_stop: bool,
2287
2288 pub(crate) a11y_action_listeners:
2289 Vec<(accesskit::Action, crate::window::a11y::A11yActionListener)>,
2290 pub(crate) a11y_synthetic_children: Option<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2291 pub(crate) report_active_descendant_focus: bool,
2292 pub(crate) override_role: Option<accesskit::Role>,
2293 pub(crate) aria: AriaProperties,
2294
2295 #[cfg(any(feature = "inspector", debug_assertions))]
2296 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2297
2298 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2299 pub(crate) debug_selector: Option<String>,
2300}
2301
2302impl Interactivity {
2303 pub fn request_layout(
2305 &mut self,
2306 global_id: Option<&GlobalElementId>,
2307 _inspector_id: Option<&InspectorElementId>,
2308 window: &mut Window,
2309 cx: &mut App,
2310 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2311 ) -> LayoutId {
2312 #[cfg(any(feature = "inspector", debug_assertions))]
2313 window.with_inspector_state(
2314 _inspector_id,
2315 cx,
2316 |inspector_state: &mut Option<DivInspectorState>, _window| {
2317 if let Some(inspector_state) = inspector_state {
2318 self.base_style = inspector_state.base_style.clone();
2319 } else {
2320 *inspector_state = Some(DivInspectorState {
2321 base_style: self.base_style.clone(),
2322 bounds: Default::default(),
2323 content_size: Default::default(),
2324 })
2325 }
2326 },
2327 );
2328
2329 window.with_optional_element_state::<InteractiveElementState, _>(
2330 global_id,
2331 |element_state, window| {
2332 let mut element_state =
2333 element_state.map(|element_state| element_state.unwrap_or_default());
2334
2335 if let Some(element_state) = element_state.as_ref()
2336 && cx.has_active_drag()
2337 {
2338 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2339 *pending_mouse_down.borrow_mut() = None;
2340 }
2341 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2342 *clicked_state.borrow_mut() = ElementClickedState::default();
2343 }
2344 }
2345
2346 if self.focusable
2351 && self.tracked_focus_handle.is_none()
2352 && let Some(element_state) = element_state.as_mut()
2353 {
2354 let mut handle = element_state
2355 .focus_handle
2356 .get_or_insert_with(|| cx.focus_handle())
2357 .clone()
2358 .tab_stop(self.tab_stop);
2359
2360 if let Some(index) = self.tab_index {
2361 handle = handle.tab_index(index);
2362 }
2363
2364 self.tracked_focus_handle = Some(handle);
2365 }
2366
2367 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2368 let scroll_handle_state = scroll_handle.0.borrow();
2369 self.scroll_offset = Some(scroll_handle_state.offset.clone());
2370 self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2371 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2372 || self.base_style.overflow.y == Some(Overflow::Scroll))
2373 && let Some(element_state) = element_state.as_mut()
2374 {
2375 self.scroll_offset = Some(
2376 element_state
2377 .scroll_offset
2378 .get_or_insert_with(Rc::default)
2379 .clone(),
2380 );
2381 self.ongoing_scroll = Some(
2382 element_state
2383 .ongoing_scroll
2384 .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2385 .clone(),
2386 );
2387 }
2388
2389 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2390 let layout_id = f(style, window, cx);
2391 (layout_id, element_state)
2392 },
2393 )
2394 }
2395
2396 pub fn prepaint<R>(
2398 &mut self,
2399 global_id: Option<&GlobalElementId>,
2400 _inspector_id: Option<&InspectorElementId>,
2401 bounds: Bounds<Pixels>,
2402 content_size: Size<Pixels>,
2403 window: &mut Window,
2404 cx: &mut App,
2405 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2406 ) -> R {
2407 self.content_size = content_size;
2408
2409 #[cfg(any(feature = "inspector", debug_assertions))]
2410 window.with_inspector_state(
2411 _inspector_id,
2412 cx,
2413 |inspector_state: &mut Option<DivInspectorState>, _window| {
2414 if let Some(inspector_state) = inspector_state {
2415 inspector_state.bounds = bounds;
2416 inspector_state.content_size = content_size;
2417 }
2418 },
2419 );
2420
2421 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2422 window.set_focus_handle(focus_handle, cx);
2423
2424 if window.a11y.is_active() {
2425 if let Some(global_id) = global_id {
2426 let node_id = global_id.accesskit_node_id();
2427 window.a11y.set_focusable(node_id, focus_handle.id);
2428 if focus_handle.is_focused(window) {
2429 window.a11y.set_focus(node_id);
2430 }
2431 } else if focus_handle.is_focused(window) {
2432 window
2436 .a11y
2437 .note_focus_without_node(focus_handle.id, "it has no element id");
2438 }
2439 }
2440 }
2441
2442 if self.report_active_descendant_focus && window.a11y.is_active() {
2443 if let Some(global_id) = global_id {
2444 window
2445 .a11y
2446 .set_active_descendant(global_id.accesskit_node_id());
2447 }
2448 }
2449 window.with_optional_element_state::<InteractiveElementState, _>(
2450 global_id,
2451 |element_state, window| {
2452 let mut element_state =
2453 element_state.map(|element_state| element_state.unwrap_or_default());
2454 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2455
2456 if let Some(element_state) = element_state.as_mut() {
2457 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2458 let clicked_state = clicked_state.borrow();
2459 self.active = Some(clicked_state.element);
2460 }
2461 if self.hover_style.is_some() || self.group_hover_style.is_some() {
2462 element_state
2463 .hover_state
2464 .get_or_insert_with(Default::default);
2465 }
2466 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2467 if self.tooltip_builder.is_some() {
2468 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2469 } else {
2470 if let Some(long_press_tooltip_active) =
2472 element_state.long_press_tooltip_active.as_ref()
2473 {
2474 long_press_tooltip_active.set(false);
2475 }
2476 element_state.active_tooltip.take();
2477 }
2478 }
2479 }
2480
2481 window.with_text_style(style.text_style().cloned(), |window| {
2482 window.with_content_mask(
2483 style.overflow_mask(bounds, window.rem_size()),
2484 |window| {
2485 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2486 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2487 } else {
2488 None
2489 };
2490
2491 let scroll_offset =
2492 self.clamp_scroll_position(bounds, &style, window, cx);
2493 let result = window.with_element_opacity(style.opacity, |window| {
2494 f(&style, scroll_offset, hitbox, window, cx)
2495 });
2496 (result, element_state)
2497 },
2498 )
2499 })
2500 },
2501 )
2502 }
2503
2504 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2505 self.hitbox_behavior != HitboxBehavior::Normal
2506 || self.window_control.is_some()
2507 || style.mouse_cursor.is_some()
2508 || self.group.is_some()
2509 || self.scroll_offset.is_some()
2510 || self.tracked_focus_handle.is_some()
2511 || self.hover_style.is_some()
2512 || self.group_hover_style.is_some()
2513 || self.hover_listener.is_some()
2514 || !self.mouse_up_listeners.is_empty()
2515 || !self.mouse_pressure_listeners.is_empty()
2516 || !self.mouse_down_listeners.is_empty()
2517 || !self.mouse_move_listeners.is_empty()
2518 || !self.mouse_exit_listeners.is_empty()
2519 || !self.file_drop_exit_listeners.is_empty()
2520 || !self.click_listeners.is_empty()
2521 || !self.aux_click_listeners.is_empty()
2522 || !self.scroll_listeners.is_empty()
2523 || self.has_pinch_listeners()
2524 || !self.back_gesture_listeners.is_empty()
2525 || self.drag_listener.is_some()
2526 || !self.drop_listeners.is_empty()
2527 || !self.drag_over_styles.is_empty()
2528 || self.tooltip_builder.is_some()
2529 || window.is_inspector_picking(cx)
2530 }
2531
2532 fn clamp_scroll_position(
2533 &self,
2534 bounds: Bounds<Pixels>,
2535 style: &Style,
2536 window: &mut Window,
2537 _cx: &mut App,
2538 ) -> Point<Pixels> {
2539 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2540 const ROUNDING_FACTOR: f32 = 100.0;
2541 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2542 }
2543
2544 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2545 let mut scroll_to_bottom = false;
2546 let mut tracked_scroll_handle = self
2547 .tracked_scroll_handle
2548 .as_ref()
2549 .map(|handle| handle.0.borrow_mut());
2550 if let Some(scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2551 scroll_handle_state.overflow = style.overflow;
2552 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2553 }
2554
2555 let rem_size = window.rem_size();
2556 let padding = style
2561 .padding
2562 .to_pixels(bounds.size.into(), rem_size)
2563 .map(|edge| window.pixel_snap(*edge));
2564 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2565 let padded_content_size = self.content_size + padding_size;
2572 let scroll_max = Point::from(padded_content_size - bounds.size)
2573 .map(round_to_two_decimals)
2574 .max(&Default::default());
2575 let mut scroll_offset = scroll_offset.borrow_mut();
2578
2579 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2580 if scroll_to_bottom {
2581 scroll_offset.y = -scroll_max.y;
2582 } else {
2583 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2584 }
2585
2586 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2587 scroll_handle_state.max_offset = scroll_max;
2588 scroll_handle_state.bounds = bounds;
2589 }
2590
2591 *scroll_offset
2592 } else {
2593 Point::default()
2594 }
2595 }
2596
2597 pub fn paint(
2606 &mut self,
2607 global_id: Option<&GlobalElementId>,
2608 _inspector_id: Option<&InspectorElementId>,
2609 bounds: Bounds<Pixels>,
2610 hitbox: Option<&Hitbox>,
2611 window: &mut Window,
2612 cx: &mut App,
2613 f: impl FnOnce(&Style, &mut Window, &mut App),
2614 ) {
2615 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2616 window.with_optional_element_state::<InteractiveElementState, _>(
2617 global_id,
2618 |element_state, window| {
2619 let mut element_state =
2620 element_state.map(|element_state| element_state.unwrap_or_default());
2621
2622 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2623
2624 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2625 if let Some(debug_selector) = &self.debug_selector {
2626 window
2627 .next_frame
2628 .record_debug_bounds(debug_selector.clone(), bounds);
2629 }
2630
2631 self.paint_hover_group_handler(window, cx);
2632
2633 if style.visibility == Visibility::Hidden {
2634 return ((), element_state);
2635 }
2636
2637 let mut tab_group = None;
2638 if self.tab_group {
2639 tab_group = self.tab_index;
2640 }
2641
2642 window.with_element_opacity(style.opacity, |window| {
2643 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2644 window.with_text_style(style.text_style().cloned(), |window| {
2645 window.with_content_mask(
2646 style.overflow_mask(bounds, window.rem_size()),
2647 |window| {
2648 window.with_tab_group(tab_group, |window| {
2649 if let Some(focus_handle) = &self.tracked_focus_handle {
2658 window.next_frame.tab_stops.insert(focus_handle);
2659 }
2660 if let Some(hitbox) = hitbox {
2661 #[cfg(debug_assertions)]
2662 self.paint_debug_info(
2663 global_id, hitbox, &style, window, cx,
2664 );
2665
2666 if let Some(drag) = cx.active_drag.as_ref() {
2667 if let Some(mouse_cursor) = drag.cursor_style {
2668 window.set_window_cursor_style(mouse_cursor);
2669 }
2670 } else {
2671 if let Some(mouse_cursor) = style.mouse_cursor {
2672 window.set_cursor_style(mouse_cursor, hitbox);
2673 }
2674 }
2675
2676 if let Some(group) = self.group.clone() {
2677 GroupHitboxes::push(group, hitbox.id, cx);
2678 }
2679
2680 if let Some(area) = self.window_control {
2681 window.insert_window_control_hitbox(
2682 area,
2683 hitbox.clone(),
2684 );
2685 }
2686
2687 self.paint_mouse_listeners(
2688 hitbox,
2689 element_state.as_mut(),
2690 window,
2691 cx,
2692 );
2693 self.paint_scroll_listener(hitbox, &style, window, cx);
2694 }
2695
2696 self.paint_keyboard_listeners(window, cx);
2697
2698 if window.a11y.is_active() {
2699 if let Some(global_id) = global_id {
2700 if !self.a11y_action_listeners.is_empty() {
2701 let node_id = global_id.accesskit_node_id();
2702 for (action, listener) in
2703 self.a11y_action_listeners.drain(..)
2704 {
2705 window.on_a11y_action(
2706 node_id, action, listener,
2707 );
2708 }
2709 }
2710 }
2711 }
2712
2713 f(&style, window, cx);
2714
2715 if let Some(_hitbox) = hitbox {
2716 #[cfg(any(feature = "inspector", debug_assertions))]
2717 window.insert_inspector_hitbox(
2718 _hitbox.id,
2719 _inspector_id,
2720 cx,
2721 );
2722
2723 if let Some(group) = self.group.as_ref() {
2724 GroupHitboxes::pop(group, cx);
2725 }
2726 }
2727 })
2728 },
2729 );
2730 });
2731 });
2732 });
2733
2734 ((), element_state)
2735 },
2736 );
2737 }
2738
2739 #[cfg(debug_assertions)]
2740 fn paint_debug_info(
2741 &self,
2742 global_id: Option<&GlobalElementId>,
2743 hitbox: &Hitbox,
2744 style: &Style,
2745 window: &mut Window,
2746 cx: &mut App,
2747 ) {
2748 use crate::{BorderStyle, TextAlign};
2749
2750 if let Some(global_id) = global_id
2751 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2752 && hitbox.is_hovered(window)
2753 {
2754 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2755 let element_id = format!("{global_id:?}");
2756 let str_len = element_id.len();
2757
2758 let render_debug_text = |window: &mut Window| {
2759 if let Some(text) = window
2760 .text_system()
2761 .shape_text(
2762 element_id.into(),
2763 FONT_SIZE,
2764 &[window.text_style().to_run(str_len)],
2765 None,
2766 None,
2767 )
2768 .ok()
2769 .and_then(|mut text| text.pop())
2770 {
2771 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2772 .ok();
2773
2774 let text_bounds = crate::Bounds {
2775 origin: hitbox.origin,
2776 size: text.size(FONT_SIZE),
2777 };
2778 if let Some(source_location) = self.source_location
2779 && text_bounds.contains(&window.mouse_position())
2780 && window.modifiers().secondary(cx)
2781 {
2782 let secondary_held = window.modifiers().secondary(cx);
2783 window.on_key_event({
2784 move |e: &crate::ModifiersChangedEvent, _phase, window, cx| {
2785 if e.modifiers.secondary(cx) != secondary_held
2786 && text_bounds.contains(&window.mouse_position())
2787 {
2788 window.refresh();
2789 }
2790 }
2791 });
2792
2793 let was_hovered = hitbox.is_hovered(window);
2794 let current_view = window.current_view();
2795 window.on_mouse_event({
2796 let hitbox = hitbox.clone();
2797 move |_: &MouseMoveEvent, phase, window, cx| {
2798 if phase == DispatchPhase::Capture {
2799 let hovered = hitbox.is_hovered(window);
2800 if hovered != was_hovered {
2801 cx.notify(current_view)
2802 }
2803 }
2804 }
2805 });
2806
2807 window.on_mouse_event({
2808 let hitbox = hitbox.clone();
2809 move |e: &crate::MouseDownEvent, phase, window, cx| {
2810 if text_bounds.contains(&e.position)
2811 && phase.capture()
2812 && hitbox.is_hovered(window)
2813 {
2814 cx.stop_propagation();
2815 let Ok(dir) = std::env::current_dir() else {
2816 return;
2817 };
2818
2819 eprintln!(
2820 "This element was created at:\n{}:{}:{}",
2821 dir.join(source_location.file()).to_string_lossy(),
2822 source_location.line(),
2823 source_location.column()
2824 );
2825 }
2826 }
2827 });
2828 window.paint_quad(crate::outline(
2829 crate::Bounds {
2830 origin: hitbox.origin
2831 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2832 size: crate::Size {
2833 width: text_bounds.size.width,
2834 height: crate::px(1.),
2835 },
2836 },
2837 crate::red(),
2838 BorderStyle::default(),
2839 ))
2840 }
2841 }
2842 };
2843
2844 window.with_text_style(
2845 Some(crate::TextStyleRefinement {
2846 color: Some(crate::red()),
2847 line_height: Some(FONT_SIZE.into()),
2848 background_color: Some(crate::white()),
2849 ..Default::default()
2850 }),
2851 render_debug_text,
2852 )
2853 }
2854 }
2855
2856 fn paint_mouse_listeners(
2857 &mut self,
2858 hitbox: &Hitbox,
2859 element_state: Option<&mut InteractiveElementState>,
2860 window: &mut Window,
2861 cx: &mut App,
2862 ) {
2863 let is_focused = self
2864 .tracked_focus_handle
2865 .as_ref()
2866 .map(|handle| handle.is_focused(window))
2867 .unwrap_or(false);
2868
2869 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2873 let hitbox = hitbox.clone();
2874 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2875 if phase == DispatchPhase::Bubble
2876 && hitbox.is_hovered(window)
2877 && !window.default_prevented()
2878 {
2879 window.focus(&focus_handle, cx);
2880 window.prevent_default();
2883 }
2884 });
2885 }
2886
2887 for listener in self.mouse_down_listeners.drain(..) {
2888 let hitbox = hitbox.clone();
2889 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2890 listener(event, phase, &hitbox, window, cx);
2891 })
2892 }
2893
2894 for listener in self.mouse_up_listeners.drain(..) {
2895 let hitbox = hitbox.clone();
2896 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2897 listener(event, phase, &hitbox, window, cx);
2898 })
2899 }
2900
2901 for listener in self.mouse_pressure_listeners.drain(..) {
2902 let hitbox = hitbox.clone();
2903 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2904 listener(event, phase, &hitbox, window, cx);
2905 })
2906 }
2907
2908 for listener in self.mouse_move_listeners.drain(..) {
2909 let hitbox = hitbox.clone();
2910 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2911 listener(event, phase, &hitbox, window, cx);
2912 })
2913 }
2914
2915 for listener in self.mouse_exit_listeners.drain(..) {
2916 let hitbox = hitbox.clone();
2917 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2918 listener(event, phase, &hitbox, window, cx);
2919 })
2920 }
2921
2922 for listener in self.file_drop_exit_listeners.drain(..) {
2923 let hitbox = hitbox.clone();
2924 window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
2925 listener(event, phase, &hitbox, window, cx);
2926 })
2927 }
2928
2929 for listener in self.scroll_listeners.drain(..) {
2930 let hitbox = hitbox.clone();
2931 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
2932 listener(event, phase, &hitbox, window, cx);
2933 })
2934 }
2935
2936 for listener in self.pinch_listeners.drain(..) {
2937 let hitbox = hitbox.clone();
2938 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2939 listener(event, phase, &hitbox, window, cx);
2940 })
2941 }
2942
2943 for listener in self.back_gesture_listeners.drain(..) {
2944 let hitbox = hitbox.clone();
2945 window.on_mouse_event(move |event: &BackGestureEvent, phase, window, cx| {
2946 listener(event, phase, &hitbox, window, cx);
2947 })
2948 }
2949
2950 if self.hover_style.is_some()
2951 || self.base_style.mouse_cursor.is_some()
2952 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2953 {
2954 let hitbox = hitbox.clone();
2955 let hover_state = self.hover_style.as_ref().and_then(|_| {
2956 element_state
2957 .as_ref()
2958 .and_then(|state| state.hover_state.as_ref())
2959 .cloned()
2960 });
2961 let current_view = window.current_view();
2962
2963 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2964 let hovered = hitbox.is_hovered(window);
2965 let was_hovered = hover_state
2966 .as_ref()
2967 .is_some_and(|state| state.borrow().element);
2968 if phase == DispatchPhase::Capture && hovered != was_hovered {
2969 if let Some(hover_state) = &hover_state {
2970 hover_state.borrow_mut().element = hovered;
2971 cx.notify(current_view);
2972 }
2973 }
2974 });
2975 }
2976
2977 if let Some(group_hover) = self.group_hover_style.as_ref() {
2978 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2979 let hover_state = element_state
2980 .as_ref()
2981 .and_then(|element| element.hover_state.as_ref())
2982 .cloned();
2983 let current_view = window.current_view();
2984
2985 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2986 let group_hovered = group_hitbox_id.is_hovered(window);
2987 let was_group_hovered = hover_state
2988 .as_ref()
2989 .is_some_and(|state| state.borrow().group);
2990 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2991 if let Some(hover_state) = &hover_state {
2992 hover_state.borrow_mut().group = group_hovered;
2993 cx.notify(current_view);
2994 }
2995 }
2996 });
2997 }
2998 }
2999
3000 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
3001
3002 let mut drag_listener = mem::take(&mut self.drag_listener);
3003 let drop_listeners = mem::take(&mut self.drop_listeners);
3004 let click_listeners = mem::take(&mut self.click_listeners);
3005 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
3006 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
3007
3008 if !drop_listeners.is_empty() {
3009 let hitbox = hitbox.clone();
3010 window.on_mouse_event({
3011 move |_: &MouseUpEvent, phase, window, cx| {
3012 if let Some(drag) = &cx.active_drag
3013 && phase == DispatchPhase::Bubble
3014 && hitbox.is_hovered(window)
3015 {
3016 let drag_state_type = drag.value.as_ref().type_id();
3017 for (drop_state_type, listener) in &drop_listeners {
3018 if *drop_state_type == drag_state_type {
3019 let drag = cx
3020 .active_drag
3021 .take()
3022 .expect("checked for type drag state type above");
3023
3024 let mut can_drop = true;
3025 if let Some(predicate) = &can_drop_predicate {
3026 can_drop = predicate(drag.value.as_ref(), window, cx);
3027 }
3028
3029 if can_drop {
3030 listener(drag.value.as_ref(), window, cx);
3031 window.refresh();
3032 cx.stop_propagation();
3033 }
3034 }
3035 }
3036 }
3037 }
3038 });
3039 }
3040
3041 if let Some(element_state) = element_state {
3042 if !click_listeners.is_empty()
3043 || !aux_click_listeners.is_empty()
3044 || drag_listener.is_some()
3045 {
3046 let pending_mouse_down = element_state
3047 .pending_mouse_down
3048 .get_or_insert_with(Default::default)
3049 .clone();
3050
3051 let pending_keyboard_down = element_state
3052 .pending_keyboard_down
3053 .get_or_insert_with(Default::default)
3054 .clone();
3055
3056 let clicked_state = element_state
3057 .clicked_state
3058 .get_or_insert_with(Default::default)
3059 .clone();
3060
3061 window.on_mouse_event({
3062 let pending_mouse_down = pending_mouse_down.clone();
3063 let hitbox = hitbox.clone();
3064 let has_aux_click_listeners = !aux_click_listeners.is_empty();
3065 move |event: &MouseDownEvent, phase, window, _cx| {
3066 if phase == DispatchPhase::Bubble
3067 && (event.button == MouseButton::Left || has_aux_click_listeners)
3068 && hitbox.is_hovered(window)
3069 {
3070 *pending_mouse_down.borrow_mut() = Some(event.clone());
3071 window.refresh();
3072 }
3073 }
3074 });
3075
3076 window.on_mouse_event({
3077 let pending_mouse_down = pending_mouse_down.clone();
3078 let hitbox = hitbox.clone();
3079 move |event: &MouseMoveEvent, phase, window, cx| {
3080 if phase == DispatchPhase::Capture {
3081 return;
3082 }
3083
3084 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3085 if let Some(mouse_down) = pending_mouse_down.clone()
3086 && !cx.has_active_drag()
3087 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
3088 && let Some(listener) = drag_listener.take()
3089 && mouse_down.button == MouseButton::Left
3090 {
3091 *clicked_state.borrow_mut() = ElementClickedState::default();
3092 let cursor_offset = event.position - hitbox.origin;
3093 let drag = (listener.render)(
3094 listener.value.as_ref(),
3095 cursor_offset,
3096 window,
3097 cx,
3098 );
3099 let external_payload_source =
3100 listener.external_payload.map(|external_payload| {
3101 let value = listener.value.clone();
3102 Box::new(move |window: &mut Window, cx: &mut App| {
3103 external_payload(value.as_ref(), window, cx)
3104 })
3105 as ExternalDragPayloadSource
3106 });
3107 cx.active_drag = Some(AnyDrag {
3108 view: drag,
3109 value: listener.value,
3110 cursor_offset,
3111 cursor_style: drag_cursor_style,
3112 external_payload_source,
3113 });
3114 pending_mouse_down.take();
3115 window.refresh();
3116 cx.stop_propagation();
3117 }
3118 }
3119 });
3120
3121 if is_focused {
3122 window.on_key_event({
3132 let pending_keyboard_down = pending_keyboard_down.clone();
3133 move |event: &KeyDownEvent, phase, window, _cx| {
3134 if phase.bubble() && !window.default_prevented() {
3135 let stroke = &event.keystroke;
3136 let is_activation_key = (stroke.key.eq("enter")
3137 || stroke.key.eq("space"))
3138 && !stroke.modifiers.modified();
3139 *pending_keyboard_down.borrow_mut() =
3140 is_activation_key.then_some(window.focus_generation);
3141 }
3142 }
3143 });
3144
3145 window.on_key_event({
3147 let click_listeners = click_listeners.clone();
3148 let hitbox = hitbox.clone();
3149 move |event: &KeyUpEvent, phase, window, cx| {
3150 if phase.bubble() && !window.default_prevented() {
3151 let stroke = &event.keystroke;
3152 let keyboard_button = if stroke.key.eq("enter") {
3153 Some(KeyboardButton::Enter)
3154 } else if stroke.key.eq("space") {
3155 Some(KeyboardButton::Space)
3156 } else {
3157 None
3158 };
3159
3160 if let Some(button) = keyboard_button
3161 && !stroke.modifiers.modified()
3162 {
3163 let pending =
3164 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
3165 if pending != Some(window.focus_generation) {
3166 return;
3167 }
3168
3169 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
3170 button,
3171 bounds: hitbox.bounds,
3172 });
3173
3174 for listener in &click_listeners {
3175 listener(&click_event, window, cx);
3176 }
3177 } else {
3178 *pending_keyboard_down.borrow_mut() = None;
3182 }
3183 }
3184 }
3185 });
3186 }
3187
3188 window.on_mouse_event({
3189 let mut captured_mouse_down = None;
3190 let hitbox = hitbox.clone();
3191 move |event: &MouseUpEvent, phase, window, cx| match phase {
3192 DispatchPhase::Capture => {
3196 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3197 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
3198 captured_mouse_down = pending_mouse_down.take();
3199 window.refresh();
3200 } else if pending_mouse_down.is_some() {
3201 pending_mouse_down.take();
3207 window.refresh();
3208 }
3209 }
3210 DispatchPhase::Bubble => {
3212 if let Some(mouse_down) = captured_mouse_down.take() {
3213 let btn = mouse_down.button;
3214
3215 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
3216 down: mouse_down,
3217 up: event.clone(),
3218 });
3219
3220 match btn {
3221 MouseButton::Left => {
3222 for listener in &click_listeners {
3223 listener(&mouse_click, window, cx);
3224 }
3225 }
3226 _ => {
3227 for listener in &aux_click_listeners {
3228 listener(&mouse_click, window, cx);
3229 }
3230 }
3231 }
3232 }
3233 }
3234 }
3235 });
3236 }
3237
3238 if let Some(hover_listener) = self.hover_listener.take() {
3239 let was_hovered = element_state
3240 .hover_listener_state
3241 .get_or_insert_with(Default::default)
3242 .clone();
3243 let has_mouse_down = element_state
3244 .pending_mouse_down
3245 .get_or_insert_with(Default::default)
3246 .clone();
3247 let hover_listener = Rc::new(hover_listener);
3248 let hover_listener_state = was_hovered.clone();
3249 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3250 let mut was_hovered = hover_listener_state.borrow_mut();
3251 if is_hovered != *was_hovered {
3252 *was_hovered = is_hovered;
3253 drop(was_hovered);
3254 hover_listener(&is_hovered, window, cx);
3255 }
3256 };
3257 let hover_listener_mode = self.hover_listener_mode;
3258
3259 if has_mouse_down.borrow().is_none() {
3260 let is_hovered =
3261 !cx.has_active_drag() && hover_listener_mode.is_hovered(hitbox, window);
3262 if is_hovered != *was_hovered.borrow() {
3263 let update_hover = update_hover.clone();
3264 window.defer(cx, move |window, cx| {
3265 update_hover(is_hovered, window, cx);
3266 });
3267 }
3268 }
3269
3270 window.on_mouse_event({
3271 let update_hover = update_hover.clone();
3272 let hitbox = hitbox.clone();
3273 move |_: &MouseMoveEvent, phase, window, cx| {
3274 if phase == DispatchPhase::Bubble {
3275 let is_hovered = has_mouse_down.borrow().is_none()
3276 && !cx.has_active_drag()
3277 && hover_listener_mode.is_hovered(&hitbox, window);
3278 update_hover(is_hovered, window, cx);
3279 }
3280 }
3281 });
3282
3283 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3286 if phase == DispatchPhase::Bubble {
3287 update_hover(false, window, cx);
3288 }
3289 });
3290 }
3291
3292 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3293 let active_tooltip = element_state
3294 .active_tooltip
3295 .get_or_insert_with(Default::default)
3296 .clone();
3297 let pending_mouse_down = element_state
3298 .pending_mouse_down
3299 .get_or_insert_with(Default::default)
3300 .clone();
3301 let long_press_tooltip_active = element_state
3302 .long_press_tooltip_active
3303 .get_or_insert_with(Default::default)
3304 .clone();
3305
3306 let tooltip_is_hoverable = tooltip_builder.hoverable;
3307 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3308 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3309 });
3310 let check_is_hovered_during_prepaint = Rc::new({
3312 let pending_mouse_down = pending_mouse_down.clone();
3313 let source_bounds = hitbox.bounds;
3314 move |window: &Window| {
3315 !window.last_input_was_keyboard()
3316 && pending_mouse_down.borrow().is_none()
3317 && source_bounds.contains(&window.mouse_position())
3318 }
3319 });
3320 let check_is_hovered = Rc::new({
3321 let hitbox = hitbox.clone();
3322 move |window: &Window| {
3323 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3324 }
3325 });
3326 register_tooltip_mouse_handlers(
3327 &active_tooltip,
3328 self.tooltip_id,
3329 build_tooltip,
3330 check_is_hovered,
3331 check_is_hovered_during_prepaint,
3332 long_press_tooltip_active,
3333 self.tooltip_show_delay,
3334 window,
3335 );
3336 }
3337
3338 let active_state = element_state
3341 .clicked_state
3342 .get_or_insert_with(Default::default)
3343 .clone();
3344
3345 {
3346 let active_state = active_state.clone();
3347 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3348 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3349 *active_state.borrow_mut() = ElementClickedState::default();
3350 window.refresh();
3351 }
3352 });
3353 }
3354
3355 {
3356 let active_group_hitbox = self
3357 .group_active_style
3358 .as_ref()
3359 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3360 let hitbox = hitbox.clone();
3361 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3362 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3363 let group_hovered = active_group_hitbox
3364 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3365 let element_hovered = hitbox.is_hovered(window);
3366 if group_hovered || element_hovered {
3367 *active_state.borrow_mut() = ElementClickedState {
3368 group: group_hovered,
3369 element: element_hovered,
3370 };
3371 window.refresh();
3372 }
3373 }
3374 });
3375 }
3376 }
3377 }
3378
3379 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3380 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3381 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3382 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3383 let action_listeners = mem::take(&mut self.action_listeners);
3384 if let Some(context) = self.key_context.clone() {
3385 window.set_key_context(context);
3386 }
3387
3388 for listener in key_down_listeners {
3389 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3390 listener(event, phase, window, cx);
3391 })
3392 }
3393
3394 for listener in key_up_listeners {
3395 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3396 listener(event, phase, window, cx);
3397 })
3398 }
3399
3400 for listener in modifiers_changed_listeners {
3401 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3402 listener(event, window, cx);
3403 })
3404 }
3405
3406 for (action_type, listener) in action_listeners {
3407 window.on_action(action_type, listener)
3408 }
3409 }
3410
3411 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3412 let group_hitbox = self
3413 .group_hover_style
3414 .as_ref()
3415 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3416
3417 if let Some(group_hitbox) = group_hitbox {
3418 let was_hovered = group_hitbox.is_hovered(window);
3419 let current_view = window.current_view();
3420 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3421 let hovered = group_hitbox.is_hovered(window);
3422 if phase == DispatchPhase::Capture && hovered != was_hovered {
3423 cx.notify(current_view);
3424 }
3425 });
3426 }
3427 }
3428
3429 fn paint_scroll_listener(
3430 &self,
3431 hitbox: &Hitbox,
3432 style: &Style,
3433 window: &mut Window,
3434 _cx: &mut App,
3435 ) {
3436 if let Some(scroll_offset) = self.scroll_offset.clone() {
3437 let ongoing_scroll = self.ongoing_scroll.clone();
3438 let overflow = style.overflow;
3439 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3440 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3441 let line_height = window.line_height();
3442 let hitbox = hitbox.clone();
3443 let current_view = window.current_view();
3444 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
3445 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3446 let mut scroll_offset = scroll_offset.borrow_mut();
3447 let old_scroll_offset = *scroll_offset;
3448 let mut delta = event.delta.pixel_delta(line_height);
3449
3450 if restrict_scroll_to_axis
3451 && event.delta.precise()
3452 && let Some(ongoing_scroll) = &ongoing_scroll
3453 {
3454 ongoing_scroll
3455 .borrow_mut()
3456 .filter(&mut delta, event.touch_phase);
3457 }
3458
3459 let mut delta_x = match overflow.x {
3460 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3461 Overflow::Scroll
3462 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3463 {
3464 delta.y
3465 }
3466 _ => Pixels::ZERO,
3467 };
3468 let mut delta_y = match overflow.y {
3469 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3470 Overflow::Scroll
3471 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3472 {
3473 delta.x
3474 }
3475 _ => Pixels::ZERO,
3476 };
3477 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3478 if delta_x.abs() > delta_y.abs() {
3479 delta_y = Pixels::ZERO;
3480 } else {
3481 delta_x = Pixels::ZERO;
3482 }
3483 }
3484 scroll_offset.y += delta_y;
3485 scroll_offset.x += delta_x;
3486 if *scroll_offset != old_scroll_offset {
3487 cx.notify(current_view);
3488 }
3489 }
3490 });
3491 }
3492 }
3493
3494 pub fn compute_style(
3496 &self,
3497 global_id: Option<&GlobalElementId>,
3498 hitbox: Option<&Hitbox>,
3499 window: &mut Window,
3500 cx: &mut App,
3501 ) -> Style {
3502 window.with_optional_element_state(global_id, |element_state, window| {
3503 let mut element_state =
3504 element_state.map(|element_state| element_state.unwrap_or_default());
3505 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3506 (style, element_state)
3507 })
3508 }
3509
3510 fn compute_style_internal(
3512 &self,
3513 hitbox: Option<&Hitbox>,
3514 element_state: Option<&mut InteractiveElementState>,
3515 window: &mut Window,
3516 cx: &mut App,
3517 ) -> Style {
3518 let mut style = Style::default();
3519 style.refine(&self.base_style);
3520
3521 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3522 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3523 && focus_handle.within_focused(window, cx)
3524 {
3525 style.refine(in_focus_style);
3526 }
3527
3528 if let Some(focus_style) = self.focus_style.as_ref()
3529 && focus_handle.is_focused(window)
3530 {
3531 style.refine(focus_style);
3532 }
3533
3534 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3535 && focus_handle.is_focused(window)
3536 && window.last_input_was_keyboard()
3537 {
3538 style.refine(focus_visible_style);
3539 }
3540 }
3541
3542 if !cx.has_active_drag() {
3543 if let Some(group_hover) = self.group_hover_style.as_ref() {
3544 let is_group_hovered =
3545 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3546 !window.last_input_was_touch() && group_hitbox_id.is_hovered(window)
3547 } else if let Some(element_state) = element_state.as_ref() {
3548 !window.last_input_was_touch()
3549 && element_state
3550 .hover_state
3551 .as_ref()
3552 .map(|state| state.borrow().group)
3553 .unwrap_or(false)
3554 } else {
3555 false
3556 };
3557
3558 if is_group_hovered {
3559 style.refine(&group_hover.style);
3560 }
3561 }
3562
3563 if let Some(hover_style) = self.hover_style.as_ref() {
3564 let is_hovered = if let Some(hitbox) = hitbox {
3565 !window.last_input_was_touch() && hitbox.is_hovered(window)
3566 } else if let Some(element_state) = element_state.as_ref() {
3567 !window.last_input_was_touch()
3568 && element_state
3569 .hover_state
3570 .as_ref()
3571 .map(|state| state.borrow().element)
3572 .unwrap_or(false)
3573 } else {
3574 false
3575 };
3576
3577 if is_hovered {
3578 style.refine(hover_style);
3579 }
3580 }
3581 }
3582
3583 if let Some(hitbox) = hitbox {
3584 if let Some(drag) = cx.active_drag.take() {
3585 let mut can_drop = true;
3586 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3587 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3588 }
3589
3590 if can_drop {
3591 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3592 if let Some(group_hitbox_id) =
3593 GroupHitboxes::get(&group_drag_style.group, cx)
3594 && *state_type == drag.value.as_ref().type_id()
3595 && group_hitbox_id.is_hovered(window)
3596 {
3597 style.refine(&group_drag_style.style);
3598 }
3599 }
3600
3601 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3602 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3603 {
3604 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3605 }
3606 }
3607 }
3608
3609 style.mouse_cursor = drag.cursor_style;
3610 cx.active_drag = Some(drag);
3611 }
3612 }
3613
3614 if let Some(element_state) = element_state {
3615 let clicked_state = element_state
3616 .clicked_state
3617 .get_or_insert_with(Default::default)
3618 .borrow();
3619 if clicked_state.group
3620 && let Some(group) = self.group_active_style.as_ref()
3621 {
3622 style.refine(&group.style)
3623 }
3624
3625 if let Some(active_style) = self.active_style.as_ref()
3626 && clicked_state.element
3627 {
3628 style.refine(active_style)
3629 }
3630 }
3631
3632 style
3633 }
3634
3635 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3636 if let Some(id) = &self.aria.author_id {
3637 node.set_author_id(id.to_string());
3638 }
3639 if let Some(label) = &self.aria.label {
3640 node.set_label(label.to_string());
3641 }
3642 if let Some(description) = &self.aria.description {
3643 node.set_description(description.to_string());
3644 }
3645 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3646 node.set_keyboard_shortcut(keyshortcuts.to_string());
3647 }
3648 if let Some(selected) = self.aria.selected {
3649 node.set_selected(selected);
3650 }
3651 if let Some(expanded) = self.aria.expanded {
3652 node.set_expanded(expanded);
3653 }
3654 if let Some(toggled) = self.aria.toggled {
3655 node.set_toggled(toggled);
3656 }
3657 if let Some(value) = self.aria.numeric_value {
3658 node.set_numeric_value(value);
3659 }
3660 if let Some(value) = self.aria.min_numeric_value {
3661 node.set_min_numeric_value(value);
3662 }
3663 if let Some(value) = self.aria.max_numeric_value {
3664 node.set_max_numeric_value(value);
3665 }
3666 if let Some(step) = self.aria.numeric_value_step {
3667 node.set_numeric_value_step(step);
3668 }
3669 if let Some(value) = &self.aria.value {
3670 node.set_value(value.to_string());
3671 }
3672 if let Some(placeholder) = &self.aria.placeholder {
3673 node.set_placeholder(placeholder.to_string());
3674 }
3675 if let Some(orientation) = self.aria.orientation {
3676 node.set_orientation(orientation);
3677 }
3678 if let Some(level) = self.aria.level {
3679 node.set_level(level);
3680 }
3681 if let Some(position) = self.aria.position_in_set {
3682 node.set_position_in_set(position);
3683 }
3684 if let Some(size) = self.aria.size_of_set {
3685 node.set_size_of_set(size);
3686 }
3687 if let Some(index) = self.aria.row_index {
3688 node.set_row_index(index);
3689 }
3690 if let Some(index) = self.aria.column_index {
3691 node.set_column_index(index);
3692 }
3693 if let Some(count) = self.aria.row_count {
3694 node.set_row_count(count);
3695 }
3696 if let Some(count) = self.aria.column_count {
3697 node.set_column_count(count);
3698 }
3699 if !self.click_listeners.is_empty() {
3700 node.add_action(accesskit::Action::Click);
3701 }
3702 if self.tracked_focus_handle.is_some() || self.focusable {
3703 node.add_action(accesskit::Action::Focus);
3704 }
3705 for (action, _) in &self.a11y_action_listeners {
3706 node.add_action(*action);
3707 }
3708 }
3709}
3710
3711#[derive(Default)]
3714pub struct InteractiveElementState {
3715 pub(crate) focus_handle: Option<FocusHandle>,
3716 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3717 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3718 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3719 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3720 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3728 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3729 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3730 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3731 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3732}
3733
3734#[derive(Copy, Clone, Default, Eq, PartialEq)]
3736pub struct ElementClickedState {
3737 pub group: bool,
3739
3740 pub element: bool,
3742}
3743
3744impl ElementClickedState {
3745 fn is_clicked(&self) -> bool {
3746 self.group || self.element
3747 }
3748}
3749
3750#[derive(Copy, Clone, Default, Eq, PartialEq)]
3752pub struct ElementHoverState {
3753 pub group: bool,
3755
3756 pub element: bool,
3758}
3759
3760pub(crate) enum ActiveTooltip {
3761 WaitingForShow { _task: Task<()> },
3763 Visible {
3765 tooltip: AnyTooltip,
3766 is_hoverable: bool,
3767 },
3768 WaitingForHide {
3771 tooltip: AnyTooltip,
3772 _task: Task<()>,
3773 },
3774}
3775
3776pub(crate) fn clear_active_tooltip(
3777 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3778 window: &mut Window,
3779) {
3780 match active_tooltip.borrow_mut().take() {
3781 None => {}
3782 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3783 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3784 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3785 }
3786}
3787
3788pub(crate) fn clear_active_tooltip_if_not_hoverable(
3789 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3790 window: &mut Window,
3791) {
3792 let should_clear = match active_tooltip.borrow().as_ref() {
3793 None => false,
3794 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3795 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3796 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3797 };
3798 if should_clear {
3799 active_tooltip.borrow_mut().take();
3800 window.refresh();
3801 }
3802}
3803
3804pub(crate) fn set_tooltip_on_window(
3805 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3806 window: &mut Window,
3807) -> Option<TooltipId> {
3808 let tooltip = match active_tooltip.borrow().as_ref() {
3809 None => return None,
3810 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3811 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3812 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3813 };
3814 Some(window.set_tooltip(tooltip))
3815}
3816
3817pub(crate) fn register_tooltip_mouse_handlers(
3818 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3819 tooltip_id: Option<TooltipId>,
3820 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3821 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3822 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3823 long_press_tooltip_active: Rc<Cell<bool>>,
3824 show_delay: Option<Duration>,
3825 window: &mut Window,
3826) {
3827 let current_view = window.current_view();
3828 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3829
3830 window.on_mouse_event({
3831 let active_tooltip = active_tooltip.clone();
3832 let build_tooltip = build_tooltip.clone();
3833 let check_is_hovered = check_is_hovered.clone();
3834 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3835 move |_: &MouseMoveEvent, phase, window, cx| {
3836 handle_tooltip_mouse_move(
3837 &active_tooltip,
3838 &build_tooltip,
3839 &check_is_hovered,
3840 &check_is_hovered_during_prepaint,
3841 tooltip_id,
3842 current_view,
3843 phase,
3844 show_delay,
3845 window,
3846 cx,
3847 )
3848 }
3849 });
3850
3851 window.on_mouse_event({
3852 let active_tooltip = active_tooltip.clone();
3853 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3854 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3855 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3856 }
3857 }
3858 });
3859
3860 window.on_mouse_event({
3861 let active_tooltip = active_tooltip.clone();
3862 let build_tooltip = build_tooltip.clone();
3863 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3864 move |event: &LongPressEvent, phase, window, cx| {
3865 if !phase.bubble() {
3866 return;
3867 }
3868
3869 match event.phase {
3870 TouchPhase::Started if !window.default_prevented() && check_is_hovered(window) => {
3871 if show_tooltip(
3872 &active_tooltip,
3873 &build_tooltip,
3874 &check_is_hovered_during_prepaint,
3875 Some(long_press_tooltip_active.clone()),
3876 window,
3877 cx,
3878 ) {
3879 long_press_tooltip_active.set(true);
3880 window.prevent_default();
3881 cx.stop_propagation();
3882 }
3883 }
3884 TouchPhase::Ended | TouchPhase::Cancelled
3885 if long_press_tooltip_active.replace(false) =>
3886 {
3887 clear_active_tooltip(&active_tooltip, window);
3888 cx.stop_propagation();
3889 }
3890 TouchPhase::Started
3891 | TouchPhase::Moved
3892 | TouchPhase::Ended
3893 | TouchPhase::Cancelled => {}
3894 }
3895 }
3896 });
3897
3898 window.on_mouse_event({
3899 let active_tooltip = active_tooltip.clone();
3900 move |_: &ScrollEvent, _phase, window: &mut Window, _cx| {
3901 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3902 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3903 }
3904 }
3905 });
3906}
3907
3908fn handle_tooltip_mouse_move(
3920 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3921 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3922 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3923 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3924 tooltip_id: Option<TooltipId>,
3925 current_view: EntityId,
3926 phase: DispatchPhase,
3927 show_delay: Duration,
3928 window: &mut Window,
3929 cx: &mut App,
3930) {
3931 enum Action {
3934 None,
3935 CancelShow,
3936 ScheduleShow,
3937 CheckVisible,
3938 }
3939
3940 let action = match active_tooltip.borrow().as_ref() {
3941 None => {
3942 let is_hovered = check_is_hovered(window);
3943 if is_hovered && phase.bubble() {
3944 Action::ScheduleShow
3945 } else {
3946 Action::None
3947 }
3948 }
3949 Some(ActiveTooltip::WaitingForShow { .. }) => {
3950 let is_hovered = check_is_hovered(window);
3951 if is_hovered {
3952 Action::None
3953 } else {
3954 Action::CancelShow
3955 }
3956 }
3957 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3958 if phase.capture()
3959 && !check_is_hovered(window)
3960 && (!*is_hoverable
3961 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3962 {
3963 Action::CheckVisible
3964 } else {
3965 Action::None
3966 }
3967 }
3968 Some(ActiveTooltip::WaitingForHide { .. }) => {
3969 if phase.capture()
3970 && (check_is_hovered(window)
3971 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3972 {
3973 Action::CheckVisible
3974 } else {
3975 Action::None
3976 }
3977 }
3978 };
3979
3980 match action {
3981 Action::None => {}
3982 Action::CancelShow => {
3983 active_tooltip.borrow_mut().take();
3985 }
3986 Action::ScheduleShow => {
3987 let delayed_show_task = window.spawn(cx, {
3988 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3989 let build_tooltip = build_tooltip.clone();
3990 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3991 async move |cx| {
3992 cx.background_executor().timer(show_delay).await;
3993 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3994 return;
3995 };
3996 cx.update(|window, cx| {
3997 show_tooltip(
3998 &active_tooltip,
3999 &build_tooltip,
4000 &check_is_hovered_during_prepaint,
4001 None,
4002 window,
4003 cx,
4004 );
4005 })
4006 .ok();
4007 }
4008 });
4009 active_tooltip
4010 .borrow_mut()
4011 .replace(ActiveTooltip::WaitingForShow {
4012 _task: delayed_show_task,
4013 });
4014 }
4015 Action::CheckVisible => cx.notify(current_view),
4016 }
4017}
4018
4019fn show_tooltip(
4020 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4021 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4022 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
4023 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
4024 window: &mut Window,
4025 cx: &mut App,
4026) -> bool {
4027 let new_tooltip = build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
4028 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4029 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4030 ActiveTooltip::Visible {
4031 tooltip: AnyTooltip {
4032 view,
4033 mouse_position: window.mouse_position(),
4034 check_visible_and_update: Rc::new(move |tooltip_bounds, window, cx| {
4035 if long_press_tooltip_active
4036 .as_ref()
4037 .is_some_and(|active| active.get())
4038 {
4039 return true;
4040 }
4041 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4042 return false;
4043 };
4044 handle_tooltip_check_visible_and_update(
4045 &active_tooltip,
4046 tooltip_is_hoverable,
4047 &check_is_hovered_during_prepaint,
4048 tooltip_bounds,
4049 window,
4050 cx,
4051 )
4052 }),
4053 },
4054 is_hoverable: tooltip_is_hoverable,
4055 }
4056 });
4057 let did_show = new_tooltip.is_some();
4058 *active_tooltip.borrow_mut() = new_tooltip;
4059 window.refresh();
4060 did_show
4061}
4062
4063fn handle_tooltip_check_visible_and_update(
4067 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4068 tooltip_is_hoverable: bool,
4069 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
4070 tooltip_bounds: Bounds<Pixels>,
4071 window: &mut Window,
4072 cx: &mut App,
4073) -> bool {
4074 enum Action {
4077 None,
4078 Hide,
4079 ScheduleHide(AnyTooltip),
4080 CancelHide(AnyTooltip),
4081 }
4082
4083 let is_hovered = check_is_hovered(window)
4084 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
4085 let action = match active_tooltip.borrow().as_ref() {
4086 Some(ActiveTooltip::Visible { tooltip, .. }) => {
4087 if is_hovered {
4088 Action::None
4089 } else {
4090 if tooltip_is_hoverable {
4091 Action::ScheduleHide(tooltip.clone())
4092 } else {
4093 Action::Hide
4094 }
4095 }
4096 }
4097 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
4098 if is_hovered {
4099 Action::CancelHide(tooltip.clone())
4100 } else {
4101 Action::None
4102 }
4103 }
4104 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
4105 };
4106
4107 match action {
4108 Action::None => {}
4109 Action::Hide => clear_active_tooltip(active_tooltip, window),
4110 Action::ScheduleHide(tooltip) => {
4111 let delayed_hide_task = window.spawn(cx, {
4112 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4113 async move |cx| {
4114 cx.background_executor()
4115 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
4116 .await;
4117 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4118 return;
4119 };
4120 if active_tooltip.borrow_mut().take().is_some() {
4121 cx.update(|window, _cx| window.refresh()).ok();
4122 }
4123 }
4124 });
4125 active_tooltip
4126 .borrow_mut()
4127 .replace(ActiveTooltip::WaitingForHide {
4128 tooltip,
4129 _task: delayed_hide_task,
4130 });
4131 }
4132 Action::CancelHide(tooltip) => {
4133 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
4135 tooltip,
4136 is_hoverable: true,
4137 });
4138 }
4139 }
4140
4141 active_tooltip.borrow().is_some()
4142}
4143
4144#[derive(Default)]
4145pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
4146
4147impl Global for GroupHitboxes {}
4148
4149impl GroupHitboxes {
4150 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
4151 cx.default_global::<Self>()
4152 .0
4153 .get(name)
4154 .and_then(|bounds_stack| bounds_stack.last())
4155 .cloned()
4156 }
4157
4158 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
4159 cx.default_global::<Self>()
4160 .0
4161 .entry(name)
4162 .or_default()
4163 .push(hitbox_id);
4164 }
4165
4166 pub fn pop(name: &SharedString, cx: &mut App) {
4167 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
4168 }
4169}
4170
4171pub struct Stateful<E> {
4173 pub(crate) element: E,
4174}
4175
4176impl<E> Styled for Stateful<E>
4177where
4178 E: Styled,
4179{
4180 fn style(&mut self) -> &mut StyleRefinement {
4181 self.element.style()
4182 }
4183}
4184
4185impl<E> StatefulInteractiveElement for Stateful<E>
4186where
4187 E: Element,
4188 Self: InteractiveElement,
4189{
4190}
4191
4192impl<E> InteractiveElement for Stateful<E>
4193where
4194 E: InteractiveElement,
4195{
4196 fn interactivity(&mut self) -> &mut Interactivity {
4197 self.element.interactivity()
4198 }
4199}
4200
4201impl<E> Element for Stateful<E>
4202where
4203 E: Element,
4204{
4205 type RequestLayoutState = E::RequestLayoutState;
4206 type PrepaintState = E::PrepaintState;
4207
4208 fn id(&self) -> Option<ElementId> {
4209 self.element.id()
4210 }
4211
4212 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4213 self.element.source_location()
4214 }
4215
4216 fn a11y_role(&self) -> Option<accesskit::Role> {
4217 self.element.a11y_role()
4218 }
4219
4220 fn write_a11y_info(&self, node: &mut accesskit::Node) {
4221 self.element.write_a11y_info(node);
4222 }
4223
4224 fn a11y_synthetic_children(
4225 &mut self,
4226 prepaint: &mut Self::PrepaintState,
4227 builder: &mut crate::A11ySubtreeBuilder,
4228 ) {
4229 self.element.a11y_synthetic_children(prepaint, builder);
4230 }
4231
4232 fn request_layout(
4233 &mut self,
4234 id: Option<&GlobalElementId>,
4235 inspector_id: Option<&InspectorElementId>,
4236 window: &mut Window,
4237 cx: &mut App,
4238 ) -> (LayoutId, Self::RequestLayoutState) {
4239 self.element.request_layout(id, inspector_id, window, cx)
4240 }
4241
4242 fn prepaint(
4243 &mut self,
4244 id: Option<&GlobalElementId>,
4245 inspector_id: Option<&InspectorElementId>,
4246 bounds: Bounds<Pixels>,
4247 state: &mut Self::RequestLayoutState,
4248 window: &mut Window,
4249 cx: &mut App,
4250 ) -> E::PrepaintState {
4251 self.element
4252 .prepaint(id, inspector_id, bounds, state, window, cx)
4253 }
4254
4255 fn paint(
4256 &mut self,
4257 id: Option<&GlobalElementId>,
4258 inspector_id: Option<&InspectorElementId>,
4259 bounds: Bounds<Pixels>,
4260 request_layout: &mut Self::RequestLayoutState,
4261 prepaint: &mut Self::PrepaintState,
4262 window: &mut Window,
4263 cx: &mut App,
4264 ) {
4265 self.element.paint(
4266 id,
4267 inspector_id,
4268 bounds,
4269 request_layout,
4270 prepaint,
4271 window,
4272 cx,
4273 );
4274 }
4275}
4276
4277impl<E> ParentElement for Stateful<E>
4278where
4279 E: ParentElement,
4280{
4281 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4282 self.element.extend(elements)
4283 }
4284}
4285
4286#[derive(Clone)]
4289pub struct ScrollAnchor {
4290 handle: ScrollHandle,
4291 last_origin: Rc<RefCell<Point<Pixels>>>,
4292}
4293
4294impl ScrollAnchor {
4295 pub fn for_handle(handle: ScrollHandle) -> Self {
4297 Self {
4298 handle,
4299 last_origin: Default::default(),
4300 }
4301 }
4302 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4304 let this = self.clone();
4305
4306 window.on_next_frame(move |_, _| {
4307 let viewport_bounds = this.handle.bounds();
4308 let self_bounds = *this.last_origin.borrow();
4309 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4310 });
4311 }
4312}
4313
4314#[derive(Default, Debug)]
4315struct ScrollHandleState {
4316 offset: Rc<RefCell<Point<Pixels>>>,
4317 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4318 bounds: Bounds<Pixels>,
4319 max_offset: Point<Pixels>,
4320 child_bounds: Vec<Bounds<Pixels>>,
4321 scroll_to_bottom: bool,
4322 overflow: Point<Overflow>,
4323 active_item: Option<ScrollActiveItem>,
4324}
4325
4326#[derive(Default, Debug, Clone, Copy)]
4327struct ScrollActiveItem {
4328 index: usize,
4329 strategy: ScrollStrategy,
4330}
4331
4332#[derive(Default, Debug, Clone, Copy)]
4333enum ScrollStrategy {
4334 #[default]
4335 FirstVisible,
4336 Top,
4337}
4338
4339#[derive(Clone, Debug)]
4343pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4344
4345impl Default for ScrollHandle {
4346 fn default() -> Self {
4347 Self::new()
4348 }
4349}
4350
4351impl ScrollHandle {
4352 pub fn new() -> Self {
4354 Self(Rc::default())
4355 }
4356
4357 pub fn offset(&self) -> Point<Pixels> {
4359 *self.0.borrow().offset.borrow()
4360 }
4361
4362 pub fn max_offset(&self) -> Point<Pixels> {
4364 self.0.borrow().max_offset
4365 }
4366
4367 pub fn top_item(&self) -> usize {
4369 let state = self.0.borrow();
4370 let top = state.bounds.top() - state.offset.borrow().y;
4371
4372 match state.child_bounds.binary_search_by(|bounds| {
4373 if top < bounds.top() {
4374 Ordering::Greater
4375 } else if top > bounds.bottom() {
4376 Ordering::Less
4377 } else {
4378 Ordering::Equal
4379 }
4380 }) {
4381 Ok(ix) => ix,
4382 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4383 }
4384 }
4385
4386 pub fn bottom_item(&self) -> usize {
4388 let state = self.0.borrow();
4389 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4390
4391 match state.child_bounds.binary_search_by(|bounds| {
4392 if bottom < bounds.top() {
4393 Ordering::Greater
4394 } else if bottom > bounds.bottom() {
4395 Ordering::Less
4396 } else {
4397 Ordering::Equal
4398 }
4399 }) {
4400 Ok(ix) => ix,
4401 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4402 }
4403 }
4404
4405 pub fn bounds(&self) -> Bounds<Pixels> {
4407 self.0.borrow().bounds
4408 }
4409
4410 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4412 self.0.borrow().child_bounds.get(ix).cloned()
4413 }
4414
4415 pub fn scroll_to_item(&self, ix: usize) {
4417 let mut state = self.0.borrow_mut();
4418 state.active_item = Some(ScrollActiveItem {
4419 index: ix,
4420 strategy: ScrollStrategy::default(),
4421 });
4422 }
4423
4424 pub fn scroll_to_top_of_item(&self, ix: usize) {
4427 let mut state = self.0.borrow_mut();
4428 state.active_item = Some(ScrollActiveItem {
4429 index: ix,
4430 strategy: ScrollStrategy::Top,
4431 });
4432 }
4433
4434 fn scroll_to_active_item(&self) {
4438 let mut state = self.0.borrow_mut();
4439
4440 let Some(active_item) = state.active_item else {
4441 return;
4442 };
4443
4444 let active_item = match state.child_bounds.get(active_item.index) {
4445 Some(bounds) => {
4446 let mut scroll_offset = state.offset.borrow_mut();
4447
4448 match active_item.strategy {
4449 ScrollStrategy::FirstVisible => {
4450 if state.overflow.y == Overflow::Scroll {
4451 let child_height = bounds.size.height;
4452 let viewport_height = state.bounds.size.height;
4453 if child_height > viewport_height {
4454 scroll_offset.y = state.bounds.top() - bounds.top();
4455 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4456 scroll_offset.y = state.bounds.top() - bounds.top();
4457 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4458 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4459 }
4460 }
4461 }
4462 ScrollStrategy::Top => {
4463 scroll_offset.y = state.bounds.top() - bounds.top();
4464 }
4465 }
4466
4467 if state.overflow.x == Overflow::Scroll {
4468 let child_width = bounds.size.width;
4469 let viewport_width = state.bounds.size.width;
4470 if child_width > viewport_width {
4471 scroll_offset.x = state.bounds.left() - bounds.left();
4472 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4473 scroll_offset.x = state.bounds.left() - bounds.left();
4474 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4475 scroll_offset.x = state.bounds.right() - bounds.right();
4476 }
4477 }
4478 None
4479 }
4480 None => Some(active_item),
4481 };
4482 state.active_item = active_item;
4483 }
4484
4485 pub fn scroll_to_bottom(&self) {
4487 let mut state = self.0.borrow_mut();
4488 state.scroll_to_bottom = true;
4489 }
4490
4491 pub fn set_offset(&self, position: Point<Pixels>) {
4495 let state = self.0.borrow();
4496 *state.offset.borrow_mut() = position;
4497 }
4498
4499 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4501 let ix = self.top_item();
4502 let state = self.0.borrow();
4503
4504 if let Some(child_bounds) = state.child_bounds.get(ix) {
4505 (
4506 ix,
4507 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4508 )
4509 } else {
4510 (ix, px(0.))
4511 }
4512 }
4513
4514 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4516 let ix = self.bottom_item();
4517 let state = self.0.borrow();
4518
4519 if let Some(child_bounds) = state.child_bounds.get(ix) {
4520 (
4521 ix,
4522 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4523 )
4524 } else {
4525 (ix, px(0.))
4526 }
4527 }
4528
4529 pub fn children_count(&self) -> usize {
4531 self.0.borrow().child_bounds.len()
4532 }
4533}
4534
4535#[cfg(test)]
4536mod tests {
4537 use super::*;
4538 use crate::{
4539 AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, IntoElement,
4540 Keystroke, MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas,
4541 util::FluentBuilder as _,
4542 };
4543 use std::{cell::Cell, rc::Weak};
4544
4545 struct GroupHoverTestView {
4546 render_count: Rc<Cell<usize>>,
4547 anonymous_paint_count: Rc<Cell<usize>>,
4548 stateful_width: Rc<Cell<Pixels>>,
4549 }
4550
4551 impl Render for GroupHoverTestView {
4552 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4553 self.render_count.set(self.render_count.get() + 1);
4554 let anonymous_paint_count = self.anonymous_paint_count.clone();
4555 let stateful_width = self.stateful_width.clone();
4556 div().size_full().child(
4557 div()
4558 .ml(px(20.))
4559 .mt(px(20.))
4560 .size(px(50.))
4561 .relative()
4562 .group("hover-group")
4563 .child(
4564 div()
4565 .absolute()
4566 .size_full()
4567 .invisible()
4568 .group_hover("hover-group", |style| style.visible())
4569 .child(canvas(
4570 |_, _, _| {},
4571 move |_, _, _, _| {
4572 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4573 },
4574 )),
4575 )
4576 .child(
4577 div()
4578 .id("stateful-group-hover-target")
4579 .absolute()
4580 .top_0()
4581 .left_0()
4582 .size(px(10.))
4583 .group_hover("hover-group", |style| style.size(px(20.)))
4584 .child(canvas(
4585 move |bounds, _, _| stateful_width.set(bounds.size.width),
4586 |_, _, _, _| {},
4587 )),
4588 ),
4589 )
4590 }
4591 }
4592
4593 #[gpui::test]
4594 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4595 let render_count = Rc::new(Cell::new(0));
4596 let anonymous_paint_count = Rc::new(Cell::new(0));
4597 let stateful_width = Rc::new(Cell::new(px(0.)));
4598 let window = cx.add_window({
4599 let render_count = render_count.clone();
4600 let anonymous_paint_count = anonymous_paint_count.clone();
4601 let stateful_width = stateful_width.clone();
4602 move |_, _| GroupHoverTestView {
4603 render_count,
4604 anonymous_paint_count,
4605 stateful_width,
4606 }
4607 });
4608 let window = AnyWindowHandle::from(window);
4609
4610 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4611 .unwrap();
4612 assert_eq!(anonymous_paint_count.get(), 0);
4613 assert_eq!(stateful_width.get(), px(10.));
4614
4615 let move_mouse = |cx: &mut TestAppContext, position| {
4616 cx.update_window(window, |_, window, cx| {
4617 window.simulate_mouse_move(position, cx)
4618 })
4619 .unwrap();
4620 };
4621
4622 let initial_render_count = render_count.get();
4623 move_mouse(cx, point(px(25.), px(25.)));
4624 assert_eq!(render_count.get(), initial_render_count + 1);
4625 assert_eq!(anonymous_paint_count.get(), 1);
4626 assert_eq!(stateful_width.get(), px(20.));
4627
4628 move_mouse(cx, point(px(30.), px(30.)));
4629 assert_eq!(render_count.get(), initial_render_count + 1);
4630 assert_eq!(anonymous_paint_count.get(), 1);
4631 assert_eq!(stateful_width.get(), px(20.));
4632
4633 move_mouse(cx, point(px(5.), px(5.)));
4634 assert_eq!(render_count.get(), initial_render_count + 2);
4635 assert_eq!(anonymous_paint_count.get(), 1);
4636 assert_eq!(stateful_width.get(), px(10.));
4637
4638 move_mouse(cx, point(px(10.), px(10.)));
4639 assert_eq!(render_count.get(), initial_render_count + 2);
4640 assert_eq!(anonymous_paint_count.get(), 1);
4641 assert_eq!(stateful_width.get(), px(10.));
4642 }
4643
4644 struct HoverListenerLayoutTestView {
4645 target_left: Pixels,
4646 hover_transitions: Rc<RefCell<Vec<bool>>>,
4647 }
4648
4649 impl Render for HoverListenerLayoutTestView {
4650 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4651 let hover_transitions = self.hover_transitions.clone();
4652 div().relative().size_full().child(
4653 div()
4654 .id("hover-target")
4655 .absolute()
4656 .left(self.target_left)
4657 .top_0()
4658 .size(px(20.))
4659 .on_click(|_, _, _| {})
4660 .on_hover(move |is_hovered, _, _| {
4661 hover_transitions.borrow_mut().push(*is_hovered);
4662 }),
4663 )
4664 }
4665 }
4666
4667 #[gpui::test]
4668 fn default_hover_listener_updates_when_layout_changes_under_stationary_mouse(
4669 cx: &mut TestAppContext,
4670 ) {
4671 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4672 let window = cx.add_window({
4673 let hover_transitions = hover_transitions.clone();
4674 move |_, _| HoverListenerLayoutTestView {
4675 target_left: px(40.),
4676 hover_transitions,
4677 }
4678 });
4679 let any_window = AnyWindowHandle::from(window);
4680
4681 cx.update_window(any_window, |_, window, cx| {
4682 window.draw(cx).clear(cx);
4683 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4684 })
4685 .unwrap();
4686 assert!(hover_transitions.borrow().is_empty());
4687
4688 window
4689 .update(cx, |view, _, cx| {
4690 view.target_left = px(0.);
4691 cx.notify();
4692 })
4693 .unwrap();
4694 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4695 .unwrap();
4696 assert_eq!(*hover_transitions.borrow(), [true]);
4697
4698 window
4699 .update(cx, |view, _, cx| {
4700 view.target_left = px(40.);
4701 cx.notify();
4702 })
4703 .unwrap();
4704 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4705 .unwrap();
4706 assert_eq!(*hover_transitions.borrow(), [true, false]);
4707 }
4708
4709 #[gpui::test]
4710 fn default_hover_listener_ends_after_key_press(cx: &mut TestAppContext) {
4711 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4712 let window = cx.add_window({
4713 let hover_transitions = hover_transitions.clone();
4714 move |_, _| HoverListenerLayoutTestView {
4715 target_left: px(0.),
4716 hover_transitions,
4717 }
4718 });
4719 let any_window = AnyWindowHandle::from(window);
4720
4721 cx.update_window(any_window, |_, window, cx| {
4722 window.draw(cx).clear(cx);
4723 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4724 })
4725 .unwrap();
4726 assert_eq!(*hover_transitions.borrow(), [true]);
4727
4728 key_down(cx, any_window, "a");
4729 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4730 .unwrap();
4731 assert_eq!(*hover_transitions.borrow(), [true, false]);
4732 }
4733
4734 struct HoverListenerModeLayoutTestView {
4735 target_left: Pixels,
4736 hover_transitions: Rc<RefCell<Vec<bool>>>,
4737 }
4738
4739 impl Render for HoverListenerModeLayoutTestView {
4740 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4741 let hover_transitions = self.hover_transitions.clone();
4742 div().relative().size_full().child(
4743 div()
4744 .id("hover-target")
4745 .absolute()
4746 .left(self.target_left)
4747 .top_0()
4748 .size(px(20.))
4749 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
4750 .on_hover(move |is_hovered, _, _| {
4751 hover_transitions.borrow_mut().push(*is_hovered);
4752 }),
4753 )
4754 }
4755 }
4756
4757 #[gpui::test]
4758 fn input_modality_independent_hover_listener_updates_after_key_press(cx: &mut TestAppContext) {
4759 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4760 let window = cx.add_window({
4761 let hover_transitions = hover_transitions.clone();
4762 move |_, _| HoverListenerModeLayoutTestView {
4763 target_left: px(40.),
4764 hover_transitions,
4765 }
4766 });
4767 let any_window = AnyWindowHandle::from(window);
4768 let pointer_position = point(px(10.), px(10.));
4769
4770 cx.update_window(any_window, |_, window, cx| {
4771 window.draw(cx).clear(cx);
4772 window.simulate_mouse_move(pointer_position, cx);
4773 })
4774 .unwrap();
4775 assert!(hover_transitions.borrow().is_empty());
4776
4777 key_down(cx, any_window, "a");
4778 window
4779 .update(cx, |view, _, cx| {
4780 view.target_left = px(0.);
4781 cx.notify();
4782 })
4783 .unwrap();
4784 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4785 .unwrap();
4786 assert_eq!(*hover_transitions.borrow(), [true]);
4787
4788 key_down(cx, any_window, "b");
4789 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4790 .unwrap();
4791 assert_eq!(*hover_transitions.borrow(), [true]);
4792
4793 cx.update_window(any_window, |_, window, cx| {
4794 window.simulate_mouse_move(point(px(30.), px(10.)), cx);
4795 })
4796 .unwrap();
4797 assert_eq!(*hover_transitions.borrow(), [true, false]);
4798
4799 cx.update_window(any_window, |_, window, cx| {
4800 window.simulate_mouse_move(pointer_position, cx);
4801 window.dispatch_event(
4802 MouseExitEvent {
4803 position: pointer_position,
4804 ..Default::default()
4805 }
4806 .to_platform_input(),
4807 cx,
4808 );
4809 })
4810 .unwrap();
4811 assert_eq!(*hover_transitions.borrow(), [true, false, true, false]);
4812 }
4813
4814 #[gpui::test]
4815 fn default_hover_listener_remains_hovered_during_stationary_mouse_press(
4816 cx: &mut TestAppContext,
4817 ) {
4818 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4819 let window = cx.add_window({
4820 let hover_transitions = hover_transitions.clone();
4821 move |_, _| HoverListenerLayoutTestView {
4822 target_left: px(0.),
4823 hover_transitions,
4824 }
4825 });
4826 let any_window = AnyWindowHandle::from(window);
4827 let mouse_position = point(px(10.), px(10.));
4828
4829 cx.update_window(any_window, |_, window, cx| {
4830 window.draw(cx).clear(cx);
4831 window.simulate_mouse_move(mouse_position, cx);
4832 })
4833 .unwrap();
4834 assert_eq!(*hover_transitions.borrow(), [true]);
4835
4836 cx.update_window(any_window, |_, window, cx| {
4837 window.dispatch_event(
4838 MouseDownEvent {
4839 position: mouse_position,
4840 button: MouseButton::Left,
4841 modifiers: Default::default(),
4842 click_count: 1,
4843 first_mouse: false,
4844 }
4845 .to_platform_input(),
4846 cx,
4847 );
4848 window.draw(cx).clear(cx);
4849 })
4850 .unwrap();
4851 assert_eq!(*hover_transitions.borrow(), [true]);
4852
4853 cx.update_window(any_window, |_, window, cx| {
4854 window.dispatch_event(
4855 MouseUpEvent {
4856 position: mouse_position,
4857 button: MouseButton::Left,
4858 modifiers: Default::default(),
4859 click_count: 1,
4860 }
4861 .to_platform_input(),
4862 cx,
4863 );
4864 window.draw(cx).clear(cx);
4865 })
4866 .unwrap();
4867 assert_eq!(*hover_transitions.borrow(), [true]);
4868 }
4869
4870 struct TestTooltipView;
4871
4872 impl Render for TestTooltipView {
4873 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4874 div().w(px(20.)).h(px(20.)).child("tooltip")
4875 }
4876 }
4877
4878 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4879
4880 struct TooltipCaptureElement {
4881 child: AnyElement,
4882 captured_active_tooltip: CapturedActiveTooltip,
4883 }
4884
4885 impl Element for TooltipCaptureElement {
4886 type RequestLayoutState = ();
4887 type PrepaintState = ();
4888
4889 fn id(&self) -> Option<ElementId> {
4890 None
4891 }
4892
4893 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4894 None
4895 }
4896
4897 fn request_layout(
4898 &mut self,
4899 _id: Option<&GlobalElementId>,
4900 _inspector_id: Option<&InspectorElementId>,
4901 window: &mut Window,
4902 cx: &mut App,
4903 ) -> (LayoutId, Self::RequestLayoutState) {
4904 (self.child.request_layout(window, cx), ())
4905 }
4906
4907 fn prepaint(
4908 &mut self,
4909 _id: Option<&GlobalElementId>,
4910 _inspector_id: Option<&InspectorElementId>,
4911 _bounds: Bounds<Pixels>,
4912 _request_layout: &mut Self::RequestLayoutState,
4913 window: &mut Window,
4914 cx: &mut App,
4915 ) -> Self::PrepaintState {
4916 self.child.prepaint(window, cx);
4917 }
4918
4919 fn paint(
4920 &mut self,
4921 _id: Option<&GlobalElementId>,
4922 _inspector_id: Option<&InspectorElementId>,
4923 _bounds: Bounds<Pixels>,
4924 _request_layout: &mut Self::RequestLayoutState,
4925 _prepaint: &mut Self::PrepaintState,
4926 window: &mut Window,
4927 cx: &mut App,
4928 ) {
4929 self.child.paint(window, cx);
4930 window.with_global_id("target".into(), |global_id, window| {
4931 window.with_element_state::<InteractiveElementState, _>(
4932 global_id,
4933 |state, _window| {
4934 let state = state.unwrap();
4935 *self.captured_active_tooltip.borrow_mut() =
4936 state.active_tooltip.as_ref().map(Rc::downgrade);
4937 ((), state)
4938 },
4939 )
4940 });
4941 }
4942 }
4943
4944 struct TooltipOwner {
4945 captured_active_tooltip: CapturedActiveTooltip,
4946 show_delay_override: Option<Duration>,
4947 }
4948
4949 impl Render for TooltipOwner {
4950 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4951 TooltipCaptureElement {
4952 child: div()
4953 .size_full()
4954 .child(
4955 div()
4956 .id("target")
4957 .w(px(50.))
4958 .h(px(50.))
4959 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4960 .when_some(self.show_delay_override, |this, delay| {
4961 this.tooltip_show_delay(delay)
4962 }),
4963 )
4964 .into_any_element(),
4965 captured_active_tooltip: self.captured_active_tooltip.clone(),
4966 }
4967 }
4968 }
4969
4970 #[test]
4971 fn scroll_handle_aligns_wide_children_to_left_edge() {
4972 let handle = ScrollHandle::new();
4973 {
4974 let mut state = handle.0.borrow_mut();
4975 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4976 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4977 state.overflow.x = Overflow::Scroll;
4978 state.active_item = Some(ScrollActiveItem {
4979 index: 0,
4980 strategy: ScrollStrategy::default(),
4981 });
4982 }
4983
4984 handle.scroll_to_active_item();
4985
4986 assert_eq!(handle.offset().x, px(-25.));
4987 }
4988
4989 #[test]
4990 fn scroll_handle_aligns_tall_children_to_top_edge() {
4991 let handle = ScrollHandle::new();
4992 {
4993 let mut state = handle.0.borrow_mut();
4994 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4995 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4996 state.overflow.y = Overflow::Scroll;
4997 state.active_item = Some(ScrollActiveItem {
4998 index: 0,
4999 strategy: ScrollStrategy::default(),
5000 });
5001 }
5002
5003 handle.scroll_to_active_item();
5004
5005 assert_eq!(handle.offset().y, px(-25.));
5006 }
5007
5008 #[test]
5009 fn long_press_shows_tooltip_until_touch_ends() {
5010 let (mut test_app, any_window, captured_active_tooltip) = create_tooltip_owner_test(None);
5011 let active_tooltip = captured_active_tooltip
5012 .borrow()
5013 .clone()
5014 .unwrap()
5015 .upgrade()
5016 .unwrap();
5017 let touch_id = TouchId(1);
5018 let touch_position = point(px(49.), px(10.));
5019
5020 test_app
5021 .update_window(any_window, |_, window, cx| {
5022 window.dispatch_event(
5023 TouchEvent {
5024 id: touch_id,
5025 phase: TouchPhase::Started,
5026 position: touch_position,
5027 predicted_position: None,
5028 force: None,
5029 }
5030 .to_platform_input(),
5031 cx,
5032 );
5033 })
5034 .unwrap();
5035 test_app
5036 .dispatcher
5037 .advance_clock(GestureTuning::default().long_press_duration + Duration::from_millis(1));
5038 test_app.run_until_parked();
5039
5040 assert!(matches!(
5041 active_tooltip.borrow().as_ref(),
5042 Some(ActiveTooltip::Visible { .. })
5043 ));
5044
5045 let moved_position = point(px(55.), px(10.));
5046 test_app
5047 .update_window(any_window, |_, window, cx| {
5048 window.dispatch_event(
5049 TouchEvent {
5050 id: touch_id,
5051 phase: TouchPhase::Moved,
5052 position: moved_position,
5053 predicted_position: None,
5054 force: None,
5055 }
5056 .to_platform_input(),
5057 cx,
5058 );
5059 window.draw(cx).clear(cx);
5060 })
5061 .unwrap();
5062 assert!(matches!(
5063 active_tooltip.borrow().as_ref(),
5064 Some(ActiveTooltip::Visible { .. })
5065 ));
5066
5067 test_app
5068 .update_window(any_window, |_, window, cx| {
5069 window.dispatch_event(
5070 TouchEvent {
5071 id: touch_id,
5072 phase: TouchPhase::Ended,
5073 position: moved_position,
5074 predicted_position: None,
5075 force: None,
5076 }
5077 .to_platform_input(),
5078 cx,
5079 );
5080 })
5081 .unwrap();
5082
5083 assert!(active_tooltip.borrow().is_none());
5084 }
5085
5086 fn setup_tooltip_owner_test(
5087 show_delay_override: Option<Duration>,
5088 ) -> (
5089 TestAppContext,
5090 crate::AnyWindowHandle,
5091 CapturedActiveTooltip,
5092 ) {
5093 let (mut test_app, any_window, captured_active_tooltip) =
5094 create_tooltip_owner_test(show_delay_override);
5095
5096 test_app
5097 .update_window(any_window, |_, window, cx| {
5098 window.dispatch_event(
5099 MouseMoveEvent {
5100 position: point(px(10.), px(10.)),
5101 modifiers: Default::default(),
5102 pressed_button: None,
5103 }
5104 .to_platform_input(),
5105 cx,
5106 );
5107 })
5108 .unwrap();
5109
5110 test_app
5111 .update_window(any_window, |_, window, cx| {
5112 window.draw(cx).clear(cx);
5113 })
5114 .unwrap();
5115
5116 (test_app, any_window, captured_active_tooltip)
5117 }
5118
5119 fn create_tooltip_owner_test(
5120 show_delay_override: Option<Duration>,
5121 ) -> (
5122 TestAppContext,
5123 crate::AnyWindowHandle,
5124 CapturedActiveTooltip,
5125 ) {
5126 let mut test_app = TestAppContext::single();
5127 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
5128 let window = test_app.add_window({
5129 let captured_active_tooltip = captured_active_tooltip.clone();
5130 move |_, _| TooltipOwner {
5131 captured_active_tooltip,
5132 show_delay_override,
5133 }
5134 });
5135 let any_window = window.into();
5136
5137 test_app
5138 .update_window(any_window, |_, window, cx| {
5139 window.draw(cx).clear(cx);
5140 })
5141 .unwrap();
5142
5143 (test_app, any_window, captured_active_tooltip)
5144 }
5145
5146 #[test]
5147 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
5148 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5149
5150 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5151 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5152 assert!(matches!(
5153 active_tooltip.borrow().as_ref(),
5154 Some(ActiveTooltip::WaitingForShow { .. })
5155 ));
5156
5157 test_app
5158 .update_window(any_window, |_, window, _| {
5159 window.remove_window();
5160 })
5161 .unwrap();
5162 test_app.run_until_parked();
5163 drop(active_tooltip);
5164
5165 assert!(weak_active_tooltip.upgrade().is_none());
5166 }
5167
5168 #[test]
5169 fn tooltip_respects_custom_show_delay() {
5170 let extra_delay = Duration::from_secs(1);
5171 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
5172 let (test_app, _any_window, captured_active_tooltip) =
5173 setup_tooltip_owner_test(Some(show_delay_override));
5174
5175 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5176 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5177
5178 test_app
5179 .dispatcher
5180 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5181 test_app.run_until_parked();
5182
5183 assert!(matches!(
5184 active_tooltip.borrow().as_ref(),
5185 Some(ActiveTooltip::WaitingForShow { .. })
5186 ));
5187
5188 test_app.dispatcher.advance_clock(extra_delay);
5189 test_app.run_until_parked();
5190
5191 assert!(matches!(
5192 active_tooltip.borrow().as_ref(),
5193 Some(ActiveTooltip::Visible { .. })
5194 ));
5195 }
5196
5197 #[test]
5198 fn tooltip_is_released_when_its_owner_disappears() {
5199 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5200
5201 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5202 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5203
5204 test_app
5205 .dispatcher
5206 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5207 test_app.run_until_parked();
5208
5209 assert!(matches!(
5210 active_tooltip.borrow().as_ref(),
5211 Some(ActiveTooltip::Visible { .. })
5212 ));
5213
5214 test_app
5215 .update_window(any_window, |_, window, _| {
5216 window.remove_window();
5217 })
5218 .unwrap();
5219 test_app.run_until_parked();
5220 drop(active_tooltip);
5221
5222 assert!(weak_active_tooltip.upgrade().is_none());
5223 }
5224
5225 #[test]
5226 fn tooltip_hides_after_mouse_leaves_origin() {
5227 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5228
5229 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5230 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5231
5232 test_app
5233 .dispatcher
5234 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5235 test_app.run_until_parked();
5236
5237 assert!(matches!(
5238 active_tooltip.borrow().as_ref(),
5239 Some(ActiveTooltip::Visible { .. })
5240 ));
5241
5242 test_app
5243 .update_window(any_window, |_, window, cx| {
5244 window.dispatch_event(
5245 MouseMoveEvent {
5246 position: point(px(75.), px(75.)),
5247 modifiers: Default::default(),
5248 pressed_button: None,
5249 }
5250 .to_platform_input(),
5251 cx,
5252 );
5253 })
5254 .unwrap();
5255
5256 assert!(active_tooltip.borrow().is_none());
5257 }
5258
5259 struct MouseDownOutOwner {
5260 mouse_down_out_count: Rc<RefCell<usize>>,
5261 }
5262
5263 impl Render for MouseDownOutOwner {
5264 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5265 let mouse_down_out_count = self.mouse_down_out_count.clone();
5266 div()
5267 .size_full()
5268 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
5269 move |_, _, _| {
5270 *mouse_down_out_count.borrow_mut() += 1;
5271 },
5272 ))
5273 }
5274 }
5275
5276 #[test]
5277 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
5278 let mut test_app = TestAppContext::single();
5279 let mouse_down_out_count = Rc::new(RefCell::new(0));
5280 let window = test_app.add_window({
5281 let mouse_down_out_count = mouse_down_out_count.clone();
5282 move |_, _| MouseDownOutOwner {
5283 mouse_down_out_count,
5284 }
5285 });
5286 let any_window: AnyWindowHandle = window.into();
5287
5288 fn dispatch_mouse_down_outside_target(
5289 test_app: &mut TestAppContext,
5290 any_window: AnyWindowHandle,
5291 ) {
5292 test_app
5293 .update_window(any_window, |_, window, cx| {
5294 window.dispatch_event(
5295 MouseDownEvent {
5296 position: point(px(75.), px(75.)),
5297 button: MouseButton::Left,
5298 modifiers: Default::default(),
5299 click_count: 1,
5300 first_mouse: false,
5301 }
5302 .to_platform_input(),
5303 cx,
5304 );
5305 })
5306 .unwrap();
5307 }
5308
5309 test_app
5310 .update_window(any_window, |_, window, cx| {
5311 window.draw(cx).clear(cx);
5312 })
5313 .unwrap();
5314
5315 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5316 assert_eq!(
5317 *mouse_down_out_count.borrow(),
5318 1,
5319 "mouse down outside the element should fire mouse-down-out listeners"
5320 );
5321
5322 test_app
5323 .update_window(any_window, |_, window, cx| {
5324 cx.set_prompt_builder(crate::fallback_prompt_renderer);
5325 let _receiver =
5326 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
5327 assert!(window.has_active_prompt());
5328 window.draw(cx).clear(cx);
5329 })
5330 .unwrap();
5331
5332 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5333 assert_eq!(
5334 *mouse_down_out_count.borrow(),
5335 1,
5336 "mouse down over an active prompt should not fire mouse-down-out listeners"
5337 );
5338 }
5339
5340 #[test]
5341 fn touch_tap_out_fires_once_after_release() {
5342 let mut test_app = TestAppContext::single();
5343 let mouse_down_out_count = Rc::new(RefCell::new(0));
5344 let window = test_app.add_window({
5345 let mouse_down_out_count = mouse_down_out_count.clone();
5346 move |_, _| MouseDownOutOwner {
5347 mouse_down_out_count,
5348 }
5349 });
5350 let any_window: AnyWindowHandle = window.into();
5351
5352 test_app
5353 .update_window(any_window, |_, window, cx| {
5354 window.draw(cx).clear(cx);
5355 let started = TouchEvent {
5356 id: TouchId(1),
5357 phase: TouchPhase::Started,
5358 position: point(px(75.), px(75.)),
5359 force: None,
5360 predicted_position: None,
5361 };
5362 window.dispatch_event(started.clone().to_platform_input(), cx);
5363 assert_eq!(*mouse_down_out_count.borrow(), 0);
5364 window.dispatch_event(
5365 TouchEvent {
5366 phase: TouchPhase::Ended,
5367 ..started
5368 }
5369 .to_platform_input(),
5370 cx,
5371 );
5372 })
5373 .unwrap();
5374
5375 assert_eq!(
5376 *mouse_down_out_count.borrow(),
5377 1,
5378 "a touch tap outside the element should use mouse-down-out listeners"
5379 );
5380 }
5381
5382 #[crate::test]
5383 fn touch_pan_and_cancel_do_not_fire_mouse_down_out(cx: &mut TestAppContext) {
5384 let mouse_down_out_count = Rc::new(RefCell::new(0));
5385 let window = cx.add_window({
5386 let mouse_down_out_count = mouse_down_out_count.clone();
5387 move |_, _| MouseDownOutOwner {
5388 mouse_down_out_count,
5389 }
5390 });
5391 cx.update_window(window.into(), |_, window, cx| {
5392 window.draw(cx).clear(cx);
5393 for (id, samples) in [
5394 (
5395 TouchId(1),
5396 [
5397 (TouchPhase::Started, 100.),
5398 (TouchPhase::Moved, 75.),
5399 (TouchPhase::Ended, 75.),
5400 ],
5401 ),
5402 (
5403 TouchId(2),
5404 [
5405 (TouchPhase::Started, 100.),
5406 (TouchPhase::Moved, 100.),
5407 (TouchPhase::Cancelled, 100.),
5408 ],
5409 ),
5410 ] {
5411 for (phase, vertical_position) in samples {
5412 window.dispatch_event(
5413 TouchEvent {
5414 id,
5415 phase,
5416 position: point(px(75.), px(vertical_position)),
5417 predicted_position: None,
5418 force: None,
5419 }
5420 .to_platform_input(),
5421 cx,
5422 );
5423 }
5424 }
5425 })
5426 .unwrap();
5427 assert_eq!(*mouse_down_out_count.borrow(), 0);
5428 }
5429
5430 #[test]
5431 fn test_accessibility_id_builder_writes_author_id() {
5432 let mut element = div()
5433 .id("buffer-font-size")
5434 .accessibility_id("settings.buffer-font-size");
5435 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5436
5437 element.interactivity().write_a11y_info(&mut node);
5438
5439 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5440 }
5441
5442 #[test]
5443 fn test_write_a11y_info_string_and_numeric_properties() {
5444 let mut interactivity = Interactivity::default();
5445 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
5446 interactivity.aria.label = Some("Buffer Font Size".into());
5447 interactivity.aria.value = Some("15".into());
5448 interactivity.aria.placeholder = Some("Search".into());
5449 interactivity.aria.numeric_value = Some(15.0);
5450 interactivity.aria.min_numeric_value = Some(6.0);
5451 interactivity.aria.max_numeric_value = Some(72.0);
5452 interactivity.aria.numeric_value_step = Some(1.0);
5453
5454 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5455 interactivity.write_a11y_info(&mut node);
5456
5457 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5458 assert_eq!(node.label(), Some("Buffer Font Size"));
5459 assert_eq!(node.value(), Some("15"));
5460 assert_eq!(node.placeholder(), Some("Search"));
5461 assert_eq!(node.numeric_value(), Some(15.0));
5462 assert_eq!(node.min_numeric_value(), Some(6.0));
5463 assert_eq!(node.max_numeric_value(), Some(72.0));
5464 assert_eq!(node.numeric_value_step(), Some(1.0));
5465 }
5466
5467 struct KeyboardActivationTest {
5470 focus_a: FocusHandle,
5471 focus_b: FocusHandle,
5472 clicks: Rc<RefCell<Vec<&'static str>>>,
5473 }
5474
5475 impl Render for KeyboardActivationTest {
5476 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5477 let clicks_a = self.clicks.clone();
5478 let clicks_b = self.clicks.clone();
5479 div()
5480 .size_full()
5481 .child(
5482 div()
5483 .id("a")
5484 .w(px(50.))
5485 .h(px(50.))
5486 .track_focus(&self.focus_a)
5487 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
5488 )
5489 .child(
5490 div()
5491 .id("b")
5492 .w(px(50.))
5493 .h(px(50.))
5494 .track_focus(&self.focus_b)
5495 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
5496 )
5497 }
5498 }
5499
5500 fn setup_keyboard_activation_test() -> (
5501 TestAppContext,
5502 AnyWindowHandle,
5503 Rc<RefCell<Vec<&'static str>>>,
5504 FocusHandle,
5505 FocusHandle,
5506 ) {
5507 let mut cx = TestAppContext::single();
5508 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
5509 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
5510 let window = cx.add_window({
5511 let focus_a = focus_a.clone();
5512 let focus_b = focus_b.clone();
5513 let clicks = clicks.clone();
5514 move |_, _| KeyboardActivationTest {
5515 focus_a,
5516 focus_b,
5517 clicks,
5518 }
5519 });
5520 (cx, window.into(), clicks, focus_a, focus_b)
5521 }
5522
5523 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
5526 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
5527 .unwrap();
5528 cx.run_until_parked();
5529 cx.update_window(window, |_, window, cx| {
5530 window.draw(cx).clear(cx);
5531 })
5532 .unwrap();
5533 }
5534
5535 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5536 let os = cx.read(|cx| cx.platform_info().os);
5537 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5538 cx.update_window(window, |_, window, cx| {
5539 window.dispatch_event(
5540 KeyDownEvent {
5541 keystroke,
5542 is_held: false,
5543 prefer_character_input: false,
5544 }
5545 .to_platform_input(),
5546 cx,
5547 );
5548 })
5549 .unwrap();
5550 }
5551
5552 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5553 let os = cx.read(|cx| cx.platform_info().os);
5554 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5555 cx.update_window(window, |_, window, cx| {
5556 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
5557 })
5558 .unwrap();
5559 }
5560
5561 #[test]
5563 fn keyboard_activation_fires_click_on_same_element() {
5564 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5565
5566 focus_and_draw(&mut cx, window, &focus_a);
5567 key_down(&mut cx, window, "enter");
5568 key_up(&mut cx, window, "enter");
5569
5570 assert_eq!(*clicks.borrow(), vec!["a"]);
5571 }
5572
5573 #[test]
5578 fn keyboard_activation_does_not_leak_across_focus_change() {
5579 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5580
5581 focus_and_draw(&mut cx, window, &focus_a);
5583 key_down(&mut cx, window, "enter");
5584
5585 focus_and_draw(&mut cx, window, &focus_b);
5587 key_up(&mut cx, window, "enter");
5588
5589 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5592 }
5593
5594 #[test]
5599 fn keyboard_activation_does_not_leak_when_focus_returns() {
5600 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5601
5602 focus_and_draw(&mut cx, window, &focus_a);
5604 key_down(&mut cx, window, "enter");
5605
5606 focus_and_draw(&mut cx, window, &focus_b);
5609 focus_and_draw(&mut cx, window, &focus_a);
5610 key_up(&mut cx, window, "enter");
5611
5612 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5614 }
5615
5616 #[test]
5621 fn keyboard_activation_cleared_by_intervening_key_release() {
5622 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5623
5624 focus_and_draw(&mut cx, window, &focus_a);
5625 key_down(&mut cx, window, "escape");
5626 key_down(&mut cx, window, "space");
5627 key_up(&mut cx, window, "escape");
5628 key_up(&mut cx, window, "space");
5629
5630 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5631 }
5632
5633 #[test]
5637 fn keyboard_activation_does_not_distinguish_space_and_enter() {
5638 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5639
5640 focus_and_draw(&mut cx, window, &focus_a);
5641 key_down(&mut cx, window, "space");
5642 key_up(&mut cx, window, "enter");
5643
5644 assert_eq!(*clicks.borrow(), vec!["a"]);
5645 }
5646
5647 #[test]
5650 fn keyboard_activation_cleared_by_intervening_keydown() {
5651 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5652
5653 focus_and_draw(&mut cx, window, &focus_a);
5654 key_down(&mut cx, window, "enter");
5655 key_down(&mut cx, window, "a");
5656 key_up(&mut cx, window, "enter");
5657
5658 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5659 }
5660
5661 #[test]
5664 fn keyboard_activation_ignores_modified_keys() {
5665 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5666
5667 focus_and_draw(&mut cx, window, &focus_a);
5668 key_down(&mut cx, window, "cmd-enter");
5669 key_up(&mut cx, window, "cmd-enter");
5670
5671 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5672 }
5673
5674 struct TabGroupFocus {
5678 group_a: FocusHandle,
5679 item_a: FocusHandle,
5680 group_b: FocusHandle,
5681 item_b: FocusHandle,
5682 }
5683
5684 impl Render for TabGroupFocus {
5685 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5686 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
5687 div()
5688 .track_focus(container)
5689 .tab_group()
5690 .child(div().track_focus(item))
5691 }
5692 div()
5693 .child(group(&self.group_a, &self.item_a))
5694 .child(group(&self.group_b, &self.item_b))
5695 }
5696 }
5697
5698 #[test]
5702 fn focus_next_from_tab_group_container_enters_that_group() {
5703 let mut cx = TestAppContext::single();
5704 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
5705 (
5706 cx.focus_handle(),
5707 cx.focus_handle().tab_stop(true),
5708 cx.focus_handle(),
5709 cx.focus_handle().tab_stop(true),
5710 )
5711 });
5712 let window: AnyWindowHandle = cx
5713 .add_window({
5714 let (group_a, item_a, group_b, item_b) =
5715 (group_a, item_a, group_b.clone(), item_b.clone());
5716 move |_, _| TabGroupFocus {
5717 group_a,
5718 item_a,
5719 group_b,
5720 item_b,
5721 }
5722 })
5723 .into();
5724 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5725 .unwrap();
5726
5727 let focused = cx
5729 .update_window(window, |_, window, cx| {
5730 window.focus(&group_b, cx);
5731 window.focus_next(cx);
5732 window.focused(cx).map(|handle| handle.id)
5733 })
5734 .unwrap();
5735
5736 assert_eq!(focused, Some(item_b.id));
5737 }
5738
5739 #[gpui::test]
5740 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5741 cx: &mut TestAppContext,
5742 ) {
5743 struct PaddedContainer {
5744 scroll_handle: ScrollHandle,
5745 }
5746
5747 impl Render for PaddedContainer {
5748 fn render(
5749 &mut self,
5750 _window: &mut Window,
5751 _cx: &mut Context<Self>,
5752 ) -> impl IntoElement {
5753 div().size_full().child(
5756 div()
5757 .id("container")
5758 .h(px(50.))
5759 .w(px(100.))
5760 .py(px(4.25))
5761 .overflow_y_scroll()
5762 .track_scroll(&self.scroll_handle)
5763 .child(div().w_full().h(px(42.))),
5764 )
5765 }
5766 }
5767
5768 let scroll_handle = ScrollHandle::new();
5769 let window: AnyWindowHandle = cx
5770 .add_window({
5771 let scroll_handle = scroll_handle.clone();
5772 move |_, _| PaddedContainer { scroll_handle }
5773 })
5774 .into();
5775 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5776 .unwrap();
5777
5778 assert_eq!(scroll_handle.max_offset().y, px(0.));
5779 }
5780
5781 struct ContentSizedGrid;
5782
5783 impl Render for ContentSizedGrid {
5784 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5785 let widths = [px(100.), px(200.), px(50.)];
5786 div().size_full().child(
5787 div()
5788 .w_full()
5789 .grid()
5790 .grid_cols_max_content(widths.len() as u16)
5791 .children(widths.into_iter().enumerate().map(|(index, width)| {
5792 div()
5793 .debug_selector(move || format!("cell-{index}"))
5794 .w(width)
5795 .h(px(10.))
5796 })),
5797 )
5798 }
5799 }
5800
5801 #[gpui::test]
5802 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
5803 let window = cx.add_window(|_, _| ContentSizedGrid);
5804 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
5805 .unwrap();
5806
5807 let mut bounds = |selector: &'static str| {
5808 cx.update_window(window.into(), |_, window, _| {
5809 window.rendered_frame.debug_bounds.get(selector).copied()
5810 })
5811 .unwrap()
5812 .unwrap_or_else(|| panic!("{selector} was not rendered"))
5813 };
5814
5815 assert_eq!(bounds("cell-0").origin.x, px(0.));
5816 assert_eq!(bounds("cell-1").origin.x, px(100.));
5817 assert_eq!(bounds("cell-2").origin.x, px(300.));
5818 }
5819}