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