1use crate::{
19 Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, BackGestureEvent, Bounds, ClickEvent,
20 DispatchPhase, Display, Element, ElementId, Entity, EntityId, ExternalDragPayload,
21 ExternalDragPayloadSource, FileDropEvent, FocusHandle, Global, GlobalElementId, Hitbox,
22 HitboxBehavior, HitboxId, InspectorElementId, IsZero, KeyContext, KeyDownEvent, KeyUpEvent,
23 KeyboardButton, KeyboardClickEvent, LayoutId, LongPressEvent, ModifiersChangedEvent,
24 MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent, MouseMoveEvent,
25 MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels,
26 Point, Render, ScrollEvent, SharedString, Size, Style, StyleRefinement, Styled, Task,
27 TooltipId, TouchPhase, Visibility, Window, WindowControlArea, point, px, size,
28};
29use collections::HashMap;
30use gpui_util::ResultExt;
31use refineable::Refineable;
32use smallvec::SmallVec;
33use std::{
34 any::{Any, TypeId},
35 cell::{Cell, RefCell},
36 cmp::Ordering,
37 fmt::Debug,
38 marker::PhantomData,
39 mem,
40 rc::Rc,
41 sync::Arc,
42 time::Duration,
43};
44
45use super::ImageCacheProvider;
46
47#[cfg(feature = "stacker")]
48type StackSafe<T> = stacksafe::StackSafe<T>;
49#[cfg(not(feature = "stacker"))]
50type StackSafe<T> = T;
51
52const DRAG_THRESHOLD: f64 = 2.;
53const DEFAULT_TOOLTIP_SHOW_DELAY: Duration = Duration::from_millis(500);
54const HOVERABLE_TOOLTIP_HIDE_DELAY: Duration = Duration::from_millis(500);
55
56pub struct GroupStyle {
58 pub group: SharedString,
60
61 pub style: Box<StyleRefinement>,
64}
65
66pub struct DragMoveEvent<T> {
68 pub event: MouseMoveEvent,
70
71 pub bounds: Bounds<Pixels>,
73 drag: PhantomData<T>,
74 dragged_item: Arc<dyn Any>,
75}
76
77impl<T: 'static> DragMoveEvent<T> {
78 pub fn drag<'b>(&self, cx: &'b App) -> &'b T {
80 cx.active_drag
81 .as_ref()
82 .and_then(|drag| drag.value.downcast_ref::<T>())
83 .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
84 }
85
86 pub fn dragged_item(&self) -> &dyn Any {
88 self.dragged_item.as_ref()
89 }
90}
91
92impl Interactivity {
93 #[cfg(any(feature = "inspector", debug_assertions))]
95 #[track_caller]
96 pub fn new() -> Interactivity {
97 Interactivity {
98 source_location: Some(core::panic::Location::caller()),
99 ..Default::default()
100 }
101 }
102
103 #[cfg(not(any(feature = "inspector", debug_assertions)))]
105 pub fn new() -> Interactivity {
106 Interactivity::default()
107 }
108
109 pub fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
111 #[cfg(any(feature = "inspector", debug_assertions))]
112 {
113 self.source_location
114 }
115
116 #[cfg(not(any(feature = "inspector", debug_assertions)))]
117 {
118 None
119 }
120 }
121
122 pub fn on_mouse_down(
127 &mut self,
128 button: MouseButton,
129 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
130 ) {
131 self.mouse_down_listeners
132 .push(Box::new(move |event, phase, hitbox, window, cx| {
133 if phase == DispatchPhase::Bubble
134 && event.button == button
135 && hitbox.is_hovered(window)
136 {
137 (listener)(event, window, cx)
138 }
139 }));
140 }
141
142 pub fn capture_any_mouse_down(
147 &mut self,
148 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
149 ) {
150 self.mouse_down_listeners
151 .push(Box::new(move |event, phase, hitbox, window, cx| {
152 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
153 (listener)(event, window, cx)
154 }
155 }));
156 }
157
158 pub fn on_any_mouse_down(
163 &mut self,
164 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
165 ) {
166 self.mouse_down_listeners
167 .push(Box::new(move |event, phase, hitbox, window, cx| {
168 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
169 (listener)(event, window, cx)
170 }
171 }));
172 }
173
174 pub fn on_mouse_pressure(
179 &mut self,
180 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
181 ) {
182 self.mouse_pressure_listeners
183 .push(Box::new(move |event, phase, hitbox, window, cx| {
184 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
185 (listener)(event, window, cx)
186 }
187 }));
188 }
189
190 pub fn capture_mouse_pressure(
195 &mut self,
196 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
197 ) {
198 self.mouse_pressure_listeners
199 .push(Box::new(move |event, phase, hitbox, window, cx| {
200 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
201 (listener)(event, window, cx)
202 }
203 }));
204 }
205
206 pub fn on_mouse_up(
211 &mut self,
212 button: MouseButton,
213 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
214 ) {
215 self.mouse_up_listeners
216 .push(Box::new(move |event, phase, hitbox, window, cx| {
217 if phase == DispatchPhase::Bubble
218 && event.button == button
219 && hitbox.is_hovered(window)
220 {
221 (listener)(event, window, cx)
222 }
223 }));
224 }
225
226 pub fn capture_any_mouse_up(
231 &mut self,
232 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
233 ) {
234 self.mouse_up_listeners
235 .push(Box::new(move |event, phase, hitbox, window, cx| {
236 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
237 (listener)(event, window, cx)
238 }
239 }));
240 }
241
242 pub fn on_any_mouse_up(
247 &mut self,
248 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
249 ) {
250 self.mouse_up_listeners
251 .push(Box::new(move |event, phase, hitbox, window, cx| {
252 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
253 (listener)(event, window, cx)
254 }
255 }));
256 }
257
258 pub fn on_mouse_down_out(
264 &mut self,
265 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
266 ) {
267 self.mouse_down_listeners
268 .push(Box::new(move |event, phase, hitbox, window, cx| {
269 if phase == DispatchPhase::Capture
270 && !window.has_active_prompt()
271 && !hitbox.contains(&window.mouse_position())
272 {
273 (listener)(event, window, cx)
274 }
275 }));
276 }
277
278 pub fn on_mouse_up_out(
284 &mut self,
285 button: MouseButton,
286 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
287 ) {
288 self.mouse_up_listeners
289 .push(Box::new(move |event, phase, hitbox, window, cx| {
290 if phase == DispatchPhase::Capture
291 && event.button == button
292 && !hitbox.is_hovered(window)
293 {
294 (listener)(event, window, cx);
295 }
296 }));
297 }
298
299 pub fn on_mouse_move(
304 &mut self,
305 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
306 ) {
307 self.mouse_move_listeners
308 .push(Box::new(move |event, phase, hitbox, window, cx| {
309 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
310 (listener)(event, window, cx);
311 }
312 }));
313 }
314
315 pub fn on_mouse_exit(
320 &mut self,
321 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
322 ) {
323 self.mouse_exit_listeners
324 .push(Box::new(move |event, phase, hitbox, window, cx| {
325 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
326 (listener)(event, window, cx);
327 }
328 }));
329 }
330
331 pub fn on_file_drop_exit(
339 &mut self,
340 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
341 ) {
342 self.file_drop_exit_listeners
343 .push(Box::new(move |event, phase, hitbox, window, cx| {
344 if phase == DispatchPhase::Bubble
345 && matches!(event, FileDropEvent::Exited)
346 && hitbox.id.is_hovered_ignoring_last_input(window)
347 {
348 (listener)(event, window, cx);
349 }
350 }));
351 }
352
353 pub fn on_drag_move<T>(
361 &mut self,
362 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
363 ) where
364 T: 'static,
365 {
366 self.mouse_move_listeners
367 .push(Box::new(move |event, phase, hitbox, window, cx| {
368 if phase == DispatchPhase::Capture
369 && let Some(drag) = &cx.active_drag
370 && drag.value.as_ref().type_id() == TypeId::of::<T>()
371 {
372 (listener)(
373 &DragMoveEvent {
374 event: event.clone(),
375 bounds: hitbox.bounds,
376 drag: PhantomData,
377 dragged_item: Arc::clone(&drag.value),
378 },
379 window,
380 cx,
381 );
382 }
383 }));
384 }
385
386 pub fn on_scroll(&mut self, listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static) {
391 self.scroll_listeners
392 .push(Box::new(move |event, phase, hitbox, window, cx| {
393 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
394 (listener)(event, window, cx);
395 }
396 }));
397 }
398
399 #[deprecated(note = "renamed to `on_scroll`")]
401 pub fn on_scroll_wheel(
402 &mut self,
403 listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static,
404 ) {
405 self.on_scroll(listener);
406 }
407
408 pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
412 self.pinch_listeners
413 .push(Box::new(move |event, phase, hitbox, window, cx| {
414 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
415 (listener)(event, window, cx);
416 }
417 }));
418 }
419
420 pub fn on_back_gesture(
425 &mut self,
426 listener: impl Fn(&BackGestureEvent, &mut Window, &mut App) + 'static,
427 ) {
428 self.back_gesture_listeners
429 .push(Box::new(move |event, phase, hitbox, window, cx| {
430 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
431 (listener)(event, window, cx);
432 window.prevent_default();
433 cx.stop_propagation();
434 }
435 }));
436 }
437
438 pub fn capture_pinch(
442 &mut self,
443 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
444 ) {
445 self.pinch_listeners
446 .push(Box::new(move |event, phase, _hitbox, window, cx| {
447 if phase == DispatchPhase::Capture {
448 (listener)(event, window, cx);
449 } else {
450 cx.propagate();
451 }
452 }));
453 }
454
455 pub fn capture_action<A: Action>(
460 &mut self,
461 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
462 ) {
463 self.action_listeners.push((
464 TypeId::of::<A>(),
465 Box::new(move |action, phase, window, cx| {
466 let action = action.downcast_ref().unwrap();
467 if phase == DispatchPhase::Capture {
468 (listener)(action, window, cx)
469 } else {
470 cx.propagate();
471 }
472 }),
473 ));
474 }
475
476 #[track_caller]
481 #[inline(always)]
482 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
483 self.action_listeners.push((
484 TypeId::of::<A>(),
485 Box::new(move |action, phase, window, cx| {
486 let action = action.downcast_ref().unwrap();
487 if phase == DispatchPhase::Bubble {
488 (listener)(action, window, cx)
489 }
490 }),
491 ));
492 }
493
494 pub fn on_boxed_action(
501 &mut self,
502 action: &dyn Action,
503 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
504 ) {
505 let action = action.boxed_clone();
506 self.action_listeners.push((
507 (*action).type_id(),
508 Box::new(move |_, phase, window, cx| {
509 if phase == DispatchPhase::Bubble {
510 (listener)(&*action, window, cx)
511 }
512 }),
513 ));
514 }
515
516 pub fn on_key_down(
521 &mut self,
522 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
523 ) {
524 self.key_down_listeners
525 .push(Box::new(move |event, phase, window, cx| {
526 if phase == DispatchPhase::Bubble {
527 (listener)(event, window, cx)
528 }
529 }));
530 }
531
532 pub fn capture_key_down(
537 &mut self,
538 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
539 ) {
540 self.key_down_listeners
541 .push(Box::new(move |event, phase, window, cx| {
542 if phase == DispatchPhase::Capture {
543 listener(event, window, cx)
544 }
545 }));
546 }
547
548 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
553 self.key_up_listeners
554 .push(Box::new(move |event, phase, window, cx| {
555 if phase == DispatchPhase::Bubble {
556 listener(event, window, cx)
557 }
558 }));
559 }
560
561 pub fn capture_key_up(
566 &mut self,
567 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
568 ) {
569 self.key_up_listeners
570 .push(Box::new(move |event, phase, window, cx| {
571 if phase == DispatchPhase::Capture {
572 listener(event, window, cx)
573 }
574 }));
575 }
576
577 pub fn on_modifiers_changed(
582 &mut self,
583 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
584 ) {
585 self.modifiers_changed_listeners.push(Box::new(listener));
586 }
587
588 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
593 self.drop_listeners.push((
594 TypeId::of::<T>(),
595 Box::new(move |dragged_value, window, cx| {
596 listener(dragged_value.downcast_ref().unwrap(), window, cx);
597 }),
598 ));
599 }
600
601 pub fn can_drop(
604 &mut self,
605 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
606 ) {
607 self.can_drop_predicate = Some(Box::new(predicate));
608 }
609
610 #[inline(always)]
615 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
616 where
617 Self: Sized,
618 {
619 self.click_listeners.push(Rc::new(listener));
620 }
621
622 pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
627 where
628 Self: Sized,
629 {
630 self.aux_click_listeners.push(Rc::new(listener));
631 }
632
633 pub fn on_drag<T, W>(
640 &mut self,
641 value: T,
642 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
643 ) where
644 Self: Sized,
645 T: 'static,
646 W: 'static + Render,
647 {
648 debug_assert!(
649 self.drag_listener.is_none(),
650 "calling on_drag more than once on the same element is not supported"
651 );
652 self.drag_listener = Some(DragListener {
653 value: Arc::new(value),
654 render: Box::new(move |value, offset, window, cx| {
655 constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
656 }),
657 external_payload: None,
658 });
659 }
660
661 pub fn external_drag_payload<T>(
666 &mut self,
667 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
668 ) where
669 Self: Sized,
670 T: 'static,
671 {
672 let Some(drag_listener) = self.drag_listener.as_mut() else {
673 debug_assert!(false, "external_drag_payload must be called after on_drag");
674 return;
675 };
676 debug_assert!(
677 drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
678 "external_drag_payload must use the same dragged value type as on_drag"
679 );
680 debug_assert!(
681 drag_listener.external_payload.is_none(),
682 "calling external_drag_payload more than once on the same element is not supported"
683 );
684 drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
685 resolver(value.downcast_ref::<T>()?, window, cx)
686 }));
687 }
688
689 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
700 where
701 Self: Sized,
702 {
703 debug_assert!(
704 self.hover_listener.is_none(),
705 "calling on_hover more than once on the same element is not supported"
706 );
707 self.hover_listener = Some(Box::new(listener));
708 }
709
710 pub fn hover_listener_mode(&mut self, mode: HoverListenerMode)
714 where
715 Self: Sized,
716 {
717 self.hover_listener_mode = mode;
718 }
719
720 pub fn hover_style_mode(&mut self, mode: HoverListenerMode)
725 where
726 Self: Sized,
727 {
728 self.hover_style_mode = mode;
729 }
730
731 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
734 where
735 Self: Sized,
736 {
737 debug_assert!(
738 self.tooltip_builder.is_none(),
739 "calling tooltip more than once on the same element is not supported"
740 );
741 self.tooltip_builder = Some(TooltipBuilder {
742 build: Rc::new(build_tooltip),
743 hoverable: false,
744 });
745 }
746
747 pub fn hoverable_tooltip(
751 &mut self,
752 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
753 ) where
754 Self: Sized,
755 {
756 debug_assert!(
757 self.tooltip_builder.is_none(),
758 "calling tooltip more than once on the same element is not supported"
759 );
760 self.tooltip_builder = Some(TooltipBuilder {
761 build: Rc::new(build_tooltip),
762 hoverable: true,
763 });
764 }
765
766 pub fn tooltip_show_delay(&mut self, delay: Duration) {
771 self.tooltip_show_delay = Some(delay);
772 }
773
774 pub fn occlude_mouse(&mut self) {
779 self.hitbox_behavior = HitboxBehavior::BlockMouse;
780 }
781
782 pub fn window_control_area(&mut self, area: WindowControlArea) {
785 self.window_control = Some(area);
786 }
787
788 pub fn block_mouse_except_scroll(&mut self) {
793 self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
794 }
795
796 fn has_pinch_listeners(&self) -> bool {
797 !self.pinch_listeners.is_empty()
798 }
799}
800
801pub trait InteractiveElement: Sized {
804 fn interactivity(&mut self) -> &mut Interactivity;
806
807 fn group(mut self, group: impl Into<SharedString>) -> Self {
809 self.interactivity().group = Some(group.into());
810 self
811 }
812
813 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
815 self.interactivity().element_id = Some(id.into());
816
817 Stateful { element: self }
818 }
819
820 fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
824 self.interactivity().focusable = true;
825 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
826 self
827 }
828
829 fn tab_stop(mut self, tab_stop: bool) -> Self {
836 self.interactivity().tab_stop = tab_stop;
837 self
838 }
839
840 fn tab_index(mut self, index: isize) -> Self {
845 self.interactivity().focusable = true;
846 self.interactivity().tab_index = Some(index);
847 self.interactivity().tab_stop = true;
848 self
849 }
850
851 fn tab_group(mut self) -> Self {
856 self.interactivity().tab_group = true;
857 if self.interactivity().tab_index.is_none() {
858 self.interactivity().tab_index = Some(0);
859 }
860 self
861 }
862
863 fn key_context<C, E>(mut self, key_context: C) -> Self
866 where
867 C: TryInto<KeyContext, Error = E>,
868 E: std::fmt::Display,
869 {
870 if let Some(key_context) = key_context.try_into().log_err() {
871 self.interactivity().key_context = Some(key_context);
872 }
873 self
874 }
875
876 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
878 debug_assert!(
879 self.interactivity().hover_style.is_none(),
880 "hover style already set"
881 );
882 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
883 self
884 }
885
886 fn group_hover(
888 mut self,
889 group_name: impl Into<SharedString>,
890 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
891 ) -> Self {
892 self.interactivity().group_hover_style = Some(GroupStyle {
893 group: group_name.into(),
894 style: Box::new(f(StyleRefinement::default())),
895 });
896 self
897 }
898
899 #[inline(always)]
904 fn on_mouse_down(
905 mut self,
906 button: MouseButton,
907 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
908 ) -> Self {
909 self.interactivity().on_mouse_down(button, listener);
910 self
911 }
912
913 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
920 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
921 self.interactivity().debug_selector = Some(f());
922 self
923 }
924
925 #[cfg(not(any(test, all(debug_assertions, feature = "test-support"))))]
932 #[inline]
933 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
934 self
935 }
936
937 fn capture_any_mouse_down(
942 mut self,
943 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
944 ) -> Self {
945 self.interactivity().capture_any_mouse_down(listener);
946 self
947 }
948
949 fn on_any_mouse_down(
954 mut self,
955 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
956 ) -> Self {
957 self.interactivity().on_any_mouse_down(listener);
958 self
959 }
960
961 fn on_mouse_up(
966 mut self,
967 button: MouseButton,
968 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
969 ) -> Self {
970 self.interactivity().on_mouse_up(button, listener);
971 self
972 }
973
974 fn capture_any_mouse_up(
979 mut self,
980 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
981 ) -> Self {
982 self.interactivity().capture_any_mouse_up(listener);
983 self
984 }
985
986 fn on_mouse_pressure(
991 mut self,
992 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
993 ) -> Self {
994 self.interactivity().on_mouse_pressure(listener);
995 self
996 }
997
998 fn capture_mouse_pressure(
1003 mut self,
1004 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
1005 ) -> Self {
1006 self.interactivity().capture_mouse_pressure(listener);
1007 self
1008 }
1009
1010 fn on_mouse_down_out(
1016 mut self,
1017 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
1018 ) -> Self {
1019 self.interactivity().on_mouse_down_out(listener);
1020 self
1021 }
1022
1023 fn on_mouse_up_out(
1029 mut self,
1030 button: MouseButton,
1031 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
1032 ) -> Self {
1033 self.interactivity().on_mouse_up_out(button, listener);
1034 self
1035 }
1036
1037 fn on_mouse_move(
1042 mut self,
1043 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
1044 ) -> Self {
1045 self.interactivity().on_mouse_move(listener);
1046 self
1047 }
1048
1049 fn on_mouse_exit(
1054 mut self,
1055 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
1056 ) -> Self {
1057 self.interactivity().on_mouse_exit(listener);
1058 self
1059 }
1060
1061 fn on_file_drop_exit(
1069 mut self,
1070 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
1071 ) -> Self {
1072 self.interactivity().on_file_drop_exit(listener);
1073 self
1074 }
1075
1076 fn on_drag_move<T: 'static>(
1084 mut self,
1085 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
1086 ) -> Self {
1087 self.interactivity().on_drag_move(listener);
1088 self
1089 }
1090
1091 fn on_scroll(
1096 mut self,
1097 listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static,
1098 ) -> Self {
1099 self.interactivity().on_scroll(listener);
1100 self
1101 }
1102
1103 #[deprecated(note = "renamed to `on_scroll`")]
1105 fn on_scroll_wheel(
1106 self,
1107 listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static,
1108 ) -> Self {
1109 self.on_scroll(listener)
1110 }
1111
1112 fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
1117 self.interactivity().on_pinch(listener);
1118 self
1119 }
1120
1121 fn on_back_gesture(
1128 mut self,
1129 listener: impl Fn(&BackGestureEvent, &mut Window, &mut App) + 'static,
1130 ) -> Self {
1131 self.interactivity().on_back_gesture(listener);
1132 self
1133 }
1134
1135 fn capture_pinch(
1140 mut self,
1141 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
1142 ) -> Self {
1143 self.interactivity().capture_pinch(listener);
1144 self
1145 }
1146 fn capture_action<A: Action>(
1151 mut self,
1152 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1153 ) -> Self {
1154 self.interactivity().capture_action(listener);
1155 self
1156 }
1157
1158 #[track_caller]
1163 #[inline(always)]
1164 fn on_action<A: Action>(
1165 mut self,
1166 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1167 ) -> Self {
1168 self.interactivity().on_action(listener);
1169 self
1170 }
1171
1172 fn on_boxed_action(
1179 mut self,
1180 action: &dyn Action,
1181 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1182 ) -> Self {
1183 self.interactivity().on_boxed_action(action, listener);
1184 self
1185 }
1186
1187 fn on_key_down(
1192 mut self,
1193 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1194 ) -> Self {
1195 self.interactivity().on_key_down(listener);
1196 self
1197 }
1198
1199 fn capture_key_down(
1204 mut self,
1205 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1206 ) -> Self {
1207 self.interactivity().capture_key_down(listener);
1208 self
1209 }
1210
1211 fn on_key_up(
1216 mut self,
1217 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1218 ) -> Self {
1219 self.interactivity().on_key_up(listener);
1220 self
1221 }
1222
1223 fn capture_key_up(
1228 mut self,
1229 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1230 ) -> Self {
1231 self.interactivity().capture_key_up(listener);
1232 self
1233 }
1234
1235 #[inline(always)]
1240 fn on_modifiers_changed(
1241 mut self,
1242 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1243 ) -> Self {
1244 self.interactivity().on_modifiers_changed(listener);
1245 self
1246 }
1247
1248 fn drag_over<S: 'static>(
1250 mut self,
1251 f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1252 ) -> Self {
1253 self.interactivity().drag_over_styles.push((
1254 TypeId::of::<S>(),
1255 Box::new(move |currently_dragged: &dyn Any, window, cx| {
1256 f(
1257 StyleRefinement::default(),
1258 currently_dragged.downcast_ref::<S>().unwrap(),
1259 window,
1260 cx,
1261 )
1262 }),
1263 ));
1264 self
1265 }
1266
1267 fn group_drag_over<S: 'static>(
1269 mut self,
1270 group_name: impl Into<SharedString>,
1271 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1272 ) -> Self {
1273 self.interactivity().group_drag_over_styles.push((
1274 TypeId::of::<S>(),
1275 GroupStyle {
1276 group: group_name.into(),
1277 style: Box::new(f(StyleRefinement::default())),
1278 },
1279 ));
1280 self
1281 }
1282
1283 fn on_drop<T: 'static>(
1288 mut self,
1289 listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1290 ) -> Self {
1291 self.interactivity().on_drop(listener);
1292 self
1293 }
1294
1295 fn can_drop(
1298 mut self,
1299 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1300 ) -> Self {
1301 self.interactivity().can_drop(predicate);
1302 self
1303 }
1304
1305 fn occlude(mut self) -> Self {
1309 self.interactivity().occlude_mouse();
1310 self
1311 }
1312
1313 fn window_control_area(mut self, area: WindowControlArea) -> Self {
1316 self.interactivity().window_control_area(area);
1317 self
1318 }
1319
1320 fn block_mouse_except_scroll(mut self) -> Self {
1325 self.interactivity().block_mouse_except_scroll();
1326 self
1327 }
1328
1329 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1332 where
1333 Self: Sized,
1334 {
1335 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1336 self
1337 }
1338
1339 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1342 where
1343 Self: Sized,
1344 {
1345 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1346 self
1347 }
1348
1349 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1354 where
1355 Self: Sized,
1356 {
1357 self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1358 self
1359 }
1360}
1361
1362pub trait StatefulInteractiveElement: InteractiveElement {
1365 fn role(mut self, role: accesskit::Role) -> Self {
1369 debug_assert!(
1370 role != accesskit::Role::GenericContainer,
1371 "GenericContainer is filtered out of the a11y tree and has no effect"
1372 );
1373 self.interactivity().override_role = Some(role);
1374 self
1375 }
1376
1377 fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self {
1385 self.interactivity().aria.author_id = Some(id.into());
1386 self
1387 }
1388
1389 fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1391 self.interactivity().aria.label = Some(label.into());
1392 self
1393 }
1394
1395 fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
1400 self.interactivity().aria.description = Some(description.into());
1401 self
1402 }
1403
1404 fn aria_keyshortcuts(mut self, keyshortcuts: impl Into<SharedString>) -> Self {
1410 self.interactivity().aria.keyshortcuts = Some(keyshortcuts.into());
1411 self
1412 }
1413
1414 fn aria_active_descendant(mut self) -> Self {
1430 self.interactivity().report_active_descendant_focus = true;
1431 self
1432 }
1433
1434 fn a11y_synthetic_children(
1444 mut self,
1445 f: impl FnOnce(&mut crate::A11ySubtreeBuilder) + 'static,
1446 ) -> Self {
1447 self.interactivity().a11y_synthetic_children = Some(Box::new(f));
1448 self
1449 }
1450
1451 fn aria_selected(mut self, selected: bool) -> Self {
1453 self.interactivity().aria.selected = Some(selected);
1454 self
1455 }
1456
1457 fn aria_expanded(mut self, expanded: bool) -> Self {
1459 self.interactivity().aria.expanded = Some(expanded);
1460 self
1461 }
1462
1463 fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1465 self.interactivity().aria.toggled = Some(toggled);
1466 self
1467 }
1468
1469 fn aria_numeric_value(mut self, value: f64) -> Self {
1471 self.interactivity().aria.numeric_value = Some(value);
1472 self
1473 }
1474
1475 fn aria_numeric_value_step(mut self, step: f64) -> Self {
1478 self.interactivity().aria.numeric_value_step = Some(step);
1479 self
1480 }
1481
1482 fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
1485 self.interactivity().aria.value = Some(value.into());
1486 self
1487 }
1488
1489 fn aria_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1492 self.interactivity().aria.placeholder = Some(placeholder.into());
1493 self
1494 }
1495
1496 fn aria_min_numeric_value(mut self, value: f64) -> Self {
1498 self.interactivity().aria.min_numeric_value = Some(value);
1499 self
1500 }
1501
1502 fn aria_max_numeric_value(mut self, value: f64) -> Self {
1504 self.interactivity().aria.max_numeric_value = Some(value);
1505 self
1506 }
1507
1508 fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1510 self.interactivity().aria.orientation = Some(orientation);
1511 self
1512 }
1513
1514 fn aria_level(mut self, level: usize) -> Self {
1516 self.interactivity().aria.level = Some(level);
1517 self
1518 }
1519
1520 fn aria_position_in_set(mut self, position: usize) -> Self {
1522 self.interactivity().aria.position_in_set = Some(position);
1523 self
1524 }
1525
1526 fn aria_size_of_set(mut self, size: usize) -> Self {
1528 self.interactivity().aria.size_of_set = Some(size);
1529 self
1530 }
1531
1532 fn aria_row_index(mut self, index: usize) -> Self {
1534 self.interactivity().aria.row_index = Some(index);
1535 self
1536 }
1537
1538 fn aria_column_index(mut self, index: usize) -> Self {
1540 self.interactivity().aria.column_index = Some(index);
1541 self
1542 }
1543
1544 fn aria_row_count(mut self, count: usize) -> Self {
1546 self.interactivity().aria.row_count = Some(count);
1547 self
1548 }
1549
1550 fn aria_column_count(mut self, count: usize) -> Self {
1552 self.interactivity().aria.column_count = Some(count);
1553 self
1554 }
1555
1556 fn aria_disabled(mut self, disabled: bool) -> Self {
1560 self.interactivity().aria.disabled = Some(disabled);
1561 self
1562 }
1563
1564 fn aria_read_only(mut self, read_only: bool) -> Self {
1567 self.interactivity().aria.read_only = Some(read_only);
1568 self
1569 }
1570
1571 fn aria_required(mut self, required: bool) -> Self {
1574 self.interactivity().aria.required = Some(required);
1575 self
1576 }
1577
1578 fn aria_modal(mut self, modal: bool) -> Self {
1581 self.interactivity().aria.modal = Some(modal);
1582 self
1583 }
1584
1585 fn aria_hidden(mut self, hidden: bool) -> Self {
1590 self.interactivity().aria.hidden = Some(hidden);
1591 self
1592 }
1593
1594 #[inline(always)]
1599 fn on_a11y_action(
1600 mut self,
1601 action: accesskit::Action,
1602 listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1603 + 'static,
1604 ) -> Self {
1605 self.interactivity()
1606 .a11y_action_listeners
1607 .push((action, Box::new(listener)));
1608 self
1609 }
1610
1611 fn focusable(mut self) -> Self {
1613 self.interactivity().focusable = true;
1614 self
1615 }
1616
1617 fn overflow_scroll(mut self) -> Self {
1619 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1620 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1621 self
1622 }
1623
1624 fn overflow_x_scroll(mut self) -> Self {
1626 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1627 self
1628 }
1629
1630 fn overflow_y_scroll(mut self) -> Self {
1632 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1633 self
1634 }
1635
1636 fn restrict_scroll_to_axis(mut self) -> Self {
1640 self.interactivity().base_style.restrict_scroll_to_axis = Some(true);
1641 self
1642 }
1643
1644 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1646 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1647 self
1648 }
1649
1650 fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1652 self.interactivity().scroll_anchor = scroll_anchor;
1653 self
1654 }
1655
1656 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1658 where
1659 Self: Sized,
1660 {
1661 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1662 self
1663 }
1664
1665 fn group_active(
1667 mut self,
1668 group_name: impl Into<SharedString>,
1669 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1670 ) -> Self
1671 where
1672 Self: Sized,
1673 {
1674 self.interactivity().group_active_style = Some(GroupStyle {
1675 group: group_name.into(),
1676 style: Box::new(f(StyleRefinement::default())),
1677 });
1678 self
1679 }
1680
1681 #[inline(always)]
1686 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1687 where
1688 Self: Sized,
1689 {
1690 self.interactivity().on_click(listener);
1691 self
1692 }
1693
1694 fn on_aux_click(
1699 mut self,
1700 listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1701 ) -> Self
1702 where
1703 Self: Sized,
1704 {
1705 self.interactivity().on_aux_click(listener);
1706 self
1707 }
1708
1709 fn on_drag<T, W>(
1717 mut self,
1718 value: T,
1719 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1720 ) -> Self
1721 where
1722 Self: Sized,
1723 T: 'static,
1724 W: 'static + Render,
1725 {
1726 self.interactivity().on_drag(value, constructor);
1727 self
1728 }
1729
1730 fn external_drag_payload<T>(
1736 mut self,
1737 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
1738 ) -> Self
1739 where
1740 Self: Sized,
1741 T: 'static,
1742 {
1743 self.interactivity().external_drag_payload(resolver);
1744 self
1745 }
1746
1747 fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1758 where
1759 Self: Sized,
1760 {
1761 self.interactivity().on_hover(listener);
1762 self
1763 }
1764
1765 fn hover_listener_mode(mut self, mode: HoverListenerMode) -> Self
1769 where
1770 Self: Sized,
1771 {
1772 self.interactivity().hover_listener_mode(mode);
1773 self
1774 }
1775
1776 fn hover_style_mode(mut self, mode: HoverListenerMode) -> Self
1778 where
1779 Self: Sized,
1780 {
1781 self.interactivity().hover_style_mode(mode);
1782 self
1783 }
1784
1785 fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1788 where
1789 Self: Sized,
1790 {
1791 self.interactivity().tooltip(build_tooltip);
1792 self
1793 }
1794
1795 fn hoverable_tooltip(
1799 mut self,
1800 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1801 ) -> Self
1802 where
1803 Self: Sized,
1804 {
1805 self.interactivity().hoverable_tooltip(build_tooltip);
1806 self
1807 }
1808
1809 fn tooltip_show_delay(mut self, delay: Duration) -> Self
1814 where
1815 Self: Sized,
1816 {
1817 self.interactivity().tooltip_show_delay(delay);
1818 self
1819 }
1820}
1821
1822pub(crate) type MouseDownListener =
1823 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1824pub(crate) type MouseUpListener =
1825 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1826pub(crate) type MousePressureListener =
1827 Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1828pub(crate) type MouseMoveListener =
1829 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1830pub(crate) type MouseExitListener =
1831 Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1832
1833pub(crate) type FileDropExitListener =
1834 Box<dyn Fn(&FileDropEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1835
1836pub(crate) type ScrollListener =
1837 Box<dyn Fn(&ScrollEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1838
1839pub(crate) type PinchListener =
1840 Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1841
1842pub(crate) type BackGestureListener =
1843 Box<dyn Fn(&BackGestureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1844
1845pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1846
1847#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1850pub enum HoverListenerMode {
1851 #[default]
1854 InputModalityAware,
1855 InputModalityIndependent,
1859}
1860
1861impl HoverListenerMode {
1862 fn is_hovered(self, hitbox: &Hitbox, window: &Window) -> bool {
1863 self.is_hovered_id(hitbox.id, window)
1864 }
1865
1866 fn is_hovered_id(self, id: HitboxId, window: &Window) -> bool {
1869 match self {
1870 Self::InputModalityAware => id.is_hovered(window),
1871 Self::InputModalityIndependent => id.is_hovered_ignoring_last_input(window),
1872 }
1873 }
1874}
1875
1876pub(crate) struct DragListener {
1877 value: Arc<dyn Any>,
1878 render: Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>,
1879 external_payload: Option<ExternalDragPayloadResolver>,
1880}
1881
1882type ExternalDragPayloadResolver =
1883 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
1884
1885type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1886
1887type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1888
1889pub(crate) struct TooltipBuilder {
1890 build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1891 hoverable: bool,
1892}
1893
1894pub(crate) type KeyDownListener =
1895 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1896
1897pub(crate) type KeyUpListener =
1898 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1899
1900pub(crate) type ModifiersChangedListener =
1901 Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1902
1903pub(crate) type ActionListener =
1904 Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1905
1906#[track_caller]
1908pub fn div() -> Div {
1909 #[allow(unused_mut)]
1910 let mut interactivity = InteractivityBox::new();
1911 #[cfg(any(feature = "inspector", debug_assertions))]
1912 {
1913 interactivity.source_location = Some(core::panic::Location::caller());
1914 }
1915 Div {
1916 interactivity,
1917 children: SmallVec::default(),
1918 prepaint_listener: None,
1919 image_cache: None,
1920 prepaint_order_fn: None,
1921 }
1922}
1923
1924enum InteractivityBox {
1928 Arena(crate::ArenaBox<Interactivity>),
1929 Heap(Box<Interactivity>),
1930}
1931
1932impl InteractivityBox {
1933 #[inline]
1935 fn new() -> Self {
1936 if crate::window::draw_in_progress() {
1937 Self::Arena(crate::window::with_element_arena(|arena| {
1938 arena.alloc(Interactivity::default)
1939 }))
1940 } else {
1941 Self::Heap(Box::default())
1942 }
1943 }
1944}
1945
1946impl std::ops::Deref for InteractivityBox {
1947 type Target = Interactivity;
1948
1949 #[inline]
1950 fn deref(&self) -> &Interactivity {
1951 match self {
1952 Self::Arena(interactivity) => interactivity,
1953 Self::Heap(interactivity) => interactivity,
1954 }
1955 }
1956}
1957
1958impl std::ops::DerefMut for InteractivityBox {
1959 #[inline]
1960 fn deref_mut(&mut self) -> &mut Interactivity {
1961 match self {
1962 Self::Arena(interactivity) => interactivity,
1963 Self::Heap(interactivity) => interactivity,
1964 }
1965 }
1966}
1967
1968pub struct Div {
1970 interactivity: InteractivityBox,
1973 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1974 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1975 image_cache: Option<Box<dyn ImageCacheProvider>>,
1976 prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1977}
1978
1979impl Div {
1980 pub fn on_children_prepainted(
1983 mut self,
1984 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1985 ) -> Self {
1986 self.prepaint_listener = Some(Box::new(listener));
1987 self
1988 }
1989
1990 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1992 self.image_cache = Some(Box::new(cache));
1993 self
1994 }
1995
1996 pub fn with_dynamic_prepaint_order(
2005 mut self,
2006 order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
2007 ) -> Self {
2008 self.prepaint_order_fn = Some(Box::new(order_fn));
2009 self
2010 }
2011}
2012
2013pub struct DivFrameState {
2020 child_layout_ids: SmallVec<[LayoutId; 2]>,
2021 children_prepainted: bool,
2032}
2033
2034#[derive(Clone)]
2036pub struct DivInspectorState {
2037 #[cfg(any(feature = "inspector", debug_assertions))]
2041 pub base_style: Box<StyleRefinement>,
2042 pub bounds: Bounds<Pixels>,
2044 pub content_size: Size<Pixels>,
2046}
2047
2048impl Styled for Div {
2049 fn style(&mut self) -> &mut StyleRefinement {
2050 &mut self.interactivity.base_style
2051 }
2052}
2053
2054impl InteractiveElement for Div {
2055 fn interactivity(&mut self) -> &mut Interactivity {
2056 &mut self.interactivity
2057 }
2058}
2059
2060impl ParentElement for Div {
2061 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
2062 #[cfg(feature = "stacker")]
2063 self.children
2064 .extend(elements.into_iter().map(StackSafe::new));
2065 #[cfg(not(feature = "stacker"))]
2066 self.children.extend(elements);
2067 }
2068}
2069
2070impl Element for Div {
2071 type RequestLayoutState = DivFrameState;
2072 type PrepaintState = Option<Hitbox>;
2073
2074 fn id(&self) -> Option<ElementId> {
2075 self.interactivity.element_id.clone()
2076 }
2077
2078 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
2079 self.interactivity.source_location()
2080 }
2081
2082 fn a11y_role(&self) -> Option<accesskit::Role> {
2083 self.interactivity
2086 .override_role
2087 .filter(|role| *role != accesskit::Role::GenericContainer)
2088 }
2089
2090 fn write_a11y_info(&self, node: &mut accesskit::Node) {
2091 self.interactivity.write_a11y_info(node);
2092 }
2093
2094 fn a11y_synthetic_children(
2095 &mut self,
2096 _prepaint: &mut Self::PrepaintState,
2097 builder: &mut crate::A11ySubtreeBuilder,
2098 ) {
2099 if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
2100 f(builder);
2101 }
2102 }
2103
2104 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2105 fn request_layout(
2106 &mut self,
2107 global_id: Option<&GlobalElementId>,
2108 inspector_id: Option<&InspectorElementId>,
2109 window: &mut Window,
2110 cx: &mut App,
2111 ) -> (LayoutId, Self::RequestLayoutState) {
2112 let mut child_layout_ids = SmallVec::new();
2113 let image_cache = self
2114 .image_cache
2115 .as_mut()
2116 .map(|provider| provider.provide(window, cx));
2117
2118 let layout_id = window.with_image_cache(image_cache, |window| {
2119 self.interactivity.request_layout(
2120 global_id,
2121 inspector_id,
2122 window,
2123 cx,
2124 |style, window, cx| {
2125 window.with_text_style(style.text_style().cloned(), |window| {
2126 child_layout_ids = self
2127 .children
2128 .iter_mut()
2129 .map(|child| child.request_layout(window, cx))
2130 .collect::<SmallVec<_>>();
2131 window.request_layout(style, child_layout_ids.iter().copied(), cx)
2132 })
2133 },
2134 )
2135 });
2136
2137 (
2138 layout_id,
2139 DivFrameState {
2140 child_layout_ids,
2141 children_prepainted: false,
2142 },
2143 )
2144 }
2145
2146 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2147 fn prepaint(
2148 &mut self,
2149 global_id: Option<&GlobalElementId>,
2150 inspector_id: Option<&InspectorElementId>,
2151 bounds: Bounds<Pixels>,
2152 request_layout: &mut Self::RequestLayoutState,
2153 window: &mut Window,
2154 cx: &mut App,
2155 ) -> Option<Hitbox> {
2156 let image_cache = self
2157 .image_cache
2158 .as_mut()
2159 .map(|provider| provider.provide(window, cx));
2160
2161 let has_prepaint_listener = self.prepaint_listener.is_some();
2162 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
2163 request_layout.child_layout_ids.len()
2164 } else {
2165 0
2166 });
2167
2168 let mut child_min = point(Pixels::MAX, Pixels::MAX);
2169 let mut child_max = point(Pixels::MIN, Pixels::MIN);
2172 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
2173 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
2174 }
2175 let mut out_of_flow_extent = Size::<Pixels>::default();
2182 let mut in_flow = 0usize;
2183 let mut measure = |child_bounds: Bounds<Pixels>, absolute: bool| {
2184 if absolute {
2185 let far = child_bounds.bottom_right() - bounds.origin;
2186 out_of_flow_extent.width = out_of_flow_extent.width.max(far.x);
2187 out_of_flow_extent.height = out_of_flow_extent.height.max(far.y);
2188 } else {
2189 in_flow += 1;
2190 child_min = child_min.min(&child_bounds.origin);
2191 child_max = child_max.max(&child_bounds.bottom_right());
2192 }
2193 };
2194 let content_size = if request_layout.child_layout_ids.is_empty() {
2195 bounds.size
2196 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2197 let mut state = scroll_handle.0.borrow_mut();
2198 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
2199 for child_layout_id in &request_layout.child_layout_ids {
2200 let child_bounds = window.layout_bounds(*child_layout_id);
2201 measure(child_bounds, window.layout_is_absolute(*child_layout_id));
2202 state.child_bounds.push(child_bounds);
2203 }
2204 if in_flow == 0 { Size::default() } else { (child_max - child_min).into() }
2205 } else {
2206 for child_layout_id in &request_layout.child_layout_ids {
2207 let child_bounds = window.layout_bounds(*child_layout_id);
2208 measure(child_bounds, window.layout_is_absolute(*child_layout_id));
2209
2210 if has_prepaint_listener {
2211 children_bounds.push(child_bounds);
2212 }
2213 }
2214 if in_flow == 0 { Size::default() } else { (child_max - child_min).into() }
2215 };
2216 self.interactivity.out_of_flow_extent = out_of_flow_extent;
2217
2218 if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2219 scroll_handle.scroll_to_active_item();
2220 }
2221
2222 self.interactivity.prepaint(
2223 global_id,
2224 inspector_id,
2225 bounds,
2226 content_size,
2227 window,
2228 cx,
2229 |style, scroll_offset, hitbox, window, cx| {
2230 if style.display == Display::None {
2232 return hitbox;
2233 }
2234 request_layout.children_prepainted = true;
2235
2236 window.with_image_cache(image_cache, |window| {
2237 window.with_element_offset(scroll_offset, |window| {
2238 if let Some(order_fn) = &self.prepaint_order_fn {
2239 let order = order_fn(window, cx);
2240 for idx in order {
2241 if let Some(child) = self.children.get_mut(idx) {
2242 child.prepaint(window, cx);
2243 }
2244 }
2245 } else {
2246 for child in &mut self.children {
2247 child.prepaint(window, cx);
2248 }
2249 }
2250 });
2251
2252 if let Some(listener) = self.prepaint_listener.as_ref() {
2253 listener(children_bounds, window, cx);
2254 }
2255 });
2256
2257 hitbox
2258 },
2259 )
2260 }
2261
2262 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2263 fn paint(
2264 &mut self,
2265 global_id: Option<&GlobalElementId>,
2266 inspector_id: Option<&InspectorElementId>,
2267 bounds: Bounds<Pixels>,
2268 request_layout: &mut Self::RequestLayoutState,
2269 hitbox: &mut Option<Hitbox>,
2270 window: &mut Window,
2271 cx: &mut App,
2272 ) {
2273 let image_cache = self
2274 .image_cache
2275 .as_mut()
2276 .map(|provider| provider.provide(window, cx));
2277 let children_prepainted = request_layout.children_prepainted;
2278
2279 window.with_image_cache(image_cache, |window| {
2280 self.interactivity.paint(
2281 global_id,
2282 inspector_id,
2283 bounds,
2284 hitbox.as_ref(),
2285 window,
2286 cx,
2287 |style, window, cx| {
2288 if style.display == Display::None || !children_prepainted {
2292 return;
2293 }
2294
2295 for child in &mut self.children {
2296 child.paint(window, cx);
2297 }
2298 },
2299 )
2300 });
2301 }
2302}
2303
2304#[derive(Default)]
2305pub(crate) struct AriaProperties {
2306 pub(crate) author_id: Option<SharedString>,
2307 pub(crate) label: Option<SharedString>,
2308 pub(crate) description: Option<SharedString>,
2309 pub(crate) keyshortcuts: Option<SharedString>,
2310 pub(crate) selected: Option<bool>,
2311 pub(crate) expanded: Option<bool>,
2312 pub(crate) toggled: Option<accesskit::Toggled>,
2313 pub(crate) numeric_value: Option<f64>,
2314 pub(crate) min_numeric_value: Option<f64>,
2315 pub(crate) max_numeric_value: Option<f64>,
2316 pub(crate) numeric_value_step: Option<f64>,
2317 pub(crate) value: Option<SharedString>,
2318 pub(crate) placeholder: Option<SharedString>,
2319 pub(crate) orientation: Option<accesskit::Orientation>,
2320 pub(crate) level: Option<usize>,
2321 pub(crate) position_in_set: Option<usize>,
2322 pub(crate) size_of_set: Option<usize>,
2323 pub(crate) row_index: Option<usize>,
2324 pub(crate) column_index: Option<usize>,
2325 pub(crate) row_count: Option<usize>,
2326 pub(crate) column_count: Option<usize>,
2327 pub(crate) disabled: Option<bool>,
2328 pub(crate) read_only: Option<bool>,
2329 pub(crate) required: Option<bool>,
2330 pub(crate) modal: Option<bool>,
2331 pub(crate) hidden: Option<bool>,
2332}
2333
2334#[derive(Default)]
2337pub struct Interactivity {
2338 pub element_id: Option<ElementId>,
2340 pub active: Option<bool>,
2342 pub hovered: Option<bool>,
2345 pub(crate) tooltip_id: Option<TooltipId>,
2346 pub(crate) content_size: Size<Pixels>,
2347 pub(crate) out_of_flow_extent: Size<Pixels>,
2350 pub(crate) key_context: Option<KeyContext>,
2351 pub(crate) focusable: bool,
2352 pub(crate) tracked_focus_handle: Option<FocusHandle>,
2353 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2354 pub(crate) scroll_anchor: Option<ScrollAnchor>,
2355 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2356 pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2357 pub(crate) group: Option<SharedString>,
2358 pub base_style: Box<StyleRefinement>,
2361 pub(crate) focus_style: Option<Box<StyleRefinement>>,
2362 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2363 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2364 pub(crate) hover_style: Option<Box<StyleRefinement>>,
2365 pub(crate) group_hover_style: Option<GroupStyle>,
2366 pub(crate) active_style: Option<Box<StyleRefinement>>,
2367 pub(crate) group_active_style: Option<GroupStyle>,
2368 pub(crate) drag_over_styles: Vec<(
2369 TypeId,
2370 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2371 )>,
2372 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
2373 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
2374 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
2375 pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
2376 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
2377 pub(crate) mouse_exit_listeners: Vec<MouseExitListener>,
2378 pub(crate) file_drop_exit_listeners: Vec<FileDropExitListener>,
2379 pub(crate) scroll_listeners: Vec<ScrollListener>,
2380 pub(crate) pinch_listeners: Vec<PinchListener>,
2381 pub(crate) back_gesture_listeners: Vec<BackGestureListener>,
2382 pub(crate) key_down_listeners: Vec<KeyDownListener>,
2383 pub(crate) key_up_listeners: Vec<KeyUpListener>,
2384 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
2385 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
2386 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
2387 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
2388 pub(crate) click_listeners: Vec<ClickListener>,
2389 pub(crate) aux_click_listeners: Vec<ClickListener>,
2390 pub(crate) drag_listener: Option<DragListener>,
2391 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2392 pub(crate) hover_listener_mode: HoverListenerMode,
2393 pub(crate) hover_style_mode: HoverListenerMode,
2404 pub(crate) tooltip_builder: Option<TooltipBuilder>,
2405 pub(crate) tooltip_show_delay: Option<Duration>,
2406 pub(crate) window_control: Option<WindowControlArea>,
2407 pub(crate) hitbox_behavior: HitboxBehavior,
2408 pub(crate) tab_index: Option<isize>,
2409 pub(crate) tab_group: bool,
2410 pub(crate) tab_stop: bool,
2411
2412 pub(crate) a11y_action_listeners:
2413 Vec<(accesskit::Action, crate::window::a11y::A11yActionListener)>,
2414 pub(crate) a11y_synthetic_children: Option<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2415 pub(crate) report_active_descendant_focus: bool,
2416 pub(crate) override_role: Option<accesskit::Role>,
2417 pub(crate) aria: AriaProperties,
2418
2419 #[cfg(any(feature = "inspector", debug_assertions))]
2420 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2421
2422 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2423 pub(crate) debug_selector: Option<String>,
2424}
2425
2426impl Interactivity {
2427 pub fn request_layout(
2429 &mut self,
2430 global_id: Option<&GlobalElementId>,
2431 _inspector_id: Option<&InspectorElementId>,
2432 window: &mut Window,
2433 cx: &mut App,
2434 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2435 ) -> LayoutId {
2436 #[cfg(any(feature = "inspector", debug_assertions))]
2437 window.with_inspector_state(
2438 _inspector_id,
2439 cx,
2440 |inspector_state: &mut Option<DivInspectorState>, _window| {
2441 if let Some(inspector_state) = inspector_state {
2442 self.base_style = inspector_state.base_style.clone();
2443 } else {
2444 *inspector_state = Some(DivInspectorState {
2445 base_style: self.base_style.clone(),
2446 bounds: Default::default(),
2447 content_size: Default::default(),
2448 })
2449 }
2450 },
2451 );
2452
2453 window.with_optional_element_state::<InteractiveElementState, _>(
2454 global_id,
2455 |element_state, window| {
2456 let mut element_state =
2457 element_state.map(|element_state| element_state.unwrap_or_default());
2458
2459 if let Some(element_state) = element_state.as_ref()
2460 && cx.has_active_drag()
2461 {
2462 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2463 *pending_mouse_down.borrow_mut() = None;
2464 }
2465 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2466 *clicked_state.borrow_mut() = ElementClickedState::default();
2467 }
2468 }
2469
2470 if self.focusable
2475 && self.tracked_focus_handle.is_none()
2476 && let Some(element_state) = element_state.as_mut()
2477 {
2478 let mut handle = element_state
2479 .focus_handle
2480 .get_or_insert_with(|| cx.focus_handle())
2481 .clone()
2482 .tab_stop(self.tab_stop);
2483
2484 if let Some(index) = self.tab_index {
2485 handle = handle.tab_index(index);
2486 }
2487
2488 self.tracked_focus_handle = Some(handle);
2489 }
2490
2491 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2492 let scroll_handle_state = scroll_handle.0.borrow();
2493 self.scroll_offset = Some(scroll_handle_state.offset.clone());
2494 self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2495 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2496 || self.base_style.overflow.y == Some(Overflow::Scroll))
2497 && let Some(element_state) = element_state.as_mut()
2498 {
2499 self.scroll_offset = Some(
2500 element_state
2501 .scroll_offset
2502 .get_or_insert_with(Rc::default)
2503 .clone(),
2504 );
2505 self.ongoing_scroll = Some(
2506 element_state
2507 .ongoing_scroll
2508 .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2509 .clone(),
2510 );
2511 }
2512
2513 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2514 let layout_id = f(style, window, cx);
2515 (layout_id, element_state)
2516 },
2517 )
2518 }
2519
2520 pub fn prepaint<R>(
2522 &mut self,
2523 global_id: Option<&GlobalElementId>,
2524 _inspector_id: Option<&InspectorElementId>,
2525 bounds: Bounds<Pixels>,
2526 content_size: Size<Pixels>,
2527 window: &mut Window,
2528 cx: &mut App,
2529 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2530 ) -> R {
2531 self.content_size = content_size;
2532
2533 #[cfg(any(feature = "inspector", debug_assertions))]
2534 window.with_inspector_state(
2535 _inspector_id,
2536 cx,
2537 |inspector_state: &mut Option<DivInspectorState>, _window| {
2538 if let Some(inspector_state) = inspector_state {
2539 inspector_state.bounds = bounds;
2540 inspector_state.content_size = content_size;
2541 }
2542 },
2543 );
2544
2545 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2546 window.set_focus_handle(focus_handle, cx);
2547
2548 if window.a11y.is_active() {
2549 if let Some(global_id) = global_id {
2550 let node_id = global_id.accesskit_node_id();
2551 window.a11y.set_focusable(node_id, focus_handle.id);
2552 if focus_handle.is_focused(window) {
2553 window.a11y.set_focus(node_id);
2554 }
2555 } else if focus_handle.is_focused(window) {
2556 window
2560 .a11y
2561 .note_focus_without_node(focus_handle.id, "it has no element id");
2562 }
2563 }
2564 }
2565
2566 if self.report_active_descendant_focus && window.a11y.is_active() {
2567 if let Some(global_id) = global_id {
2568 window
2569 .a11y
2570 .set_active_descendant(global_id.accesskit_node_id());
2571 }
2572 }
2573 window.with_optional_element_state::<InteractiveElementState, _>(
2574 global_id,
2575 |element_state, window| {
2576 let mut element_state =
2577 element_state.map(|element_state| element_state.unwrap_or_default());
2578 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2579
2580 if let Some(element_state) = element_state.as_mut() {
2581 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2582 let clicked_state = clicked_state.borrow();
2583 self.active = Some(clicked_state.element);
2584 }
2585 if self.hover_style.is_some() || self.group_hover_style.is_some() {
2586 element_state
2587 .hover_state
2588 .get_or_insert_with(Default::default);
2589 }
2590 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2591 if self.tooltip_builder.is_some() {
2592 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2593 } else {
2594 if let Some(long_press_tooltip_active) =
2596 element_state.long_press_tooltip_active.as_ref()
2597 {
2598 long_press_tooltip_active.set(false);
2599 }
2600 element_state.active_tooltip.take();
2601 }
2602 }
2603 }
2604
2605 let own_transform = style.transform_matrix(bounds, window.scale_factor());
2611 let transformation = if style.vn_capture.is_some() {
2612 crate::TransformationMatrix::unit()
2613 } else {
2614 own_transform
2615 };
2616 window.vn_with_capture(style.vn_capture, bounds, own_transform, |window| {
2617 window.with_element_transform(transformation, |window| {
2618 window.note_tagged_transform(transformation.is_unit());
2619 window.with_element_opacity(style.opacity, |window| {
2623 window.with_text_style(style.text_style_for_bounds(bounds, window), |window| {
2624 let clip = style.vn_clip_mask(bounds, window.rem_size());
2628 let outline = style.vn_clip_outline(bounds, window.rem_size());
2629 window.with_content_mask(clip, |window| {
2630 window.vn_with_clip_shape(outline.as_ref(), |window| {
2631 window.vn_with_mask(style.vn_mask.as_ref(), bounds, cx, |window, cx| {
2632 window.vn_with_color_matrix(style.vn_color_matrix, |window| {
2633 window.with_content_mask(
2634 style.overflow_mask(bounds, window.rem_size()),
2635 |window| {
2636 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2637 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2638 } else {
2639 if window.vn_picks_every_box() {
2643 window.vn_insert_pick(bounds);
2644 }
2645 None
2646 };
2647
2648 let scroll_offset =
2649 self.clamp_scroll_position(bounds, &style, window, cx);
2650 let scope = if style.vn_reads_content() {
2651 crate::window::vn_element_key(global_id)
2652 } else {
2653 0
2654 };
2655 let result = window.vn_with_defer_scope(scope, |window| {
2656 f(&style, scroll_offset, hitbox, window, cx)
2657 });
2658 (result, element_state)
2659 },
2660 )
2661 })
2662 })
2663 })
2664 })
2665 })
2666 })
2667 })
2668 })
2669 },
2670 )
2671 }
2672
2673 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2674 self.hitbox_behavior != HitboxBehavior::Normal
2675 || self.window_control.is_some()
2676 || style.mouse_cursor.is_some()
2677 || self.group.is_some()
2678 || self.scroll_offset.is_some()
2679 || self.tracked_focus_handle.is_some()
2680 || self.hover_style.is_some()
2681 || self.group_hover_style.is_some()
2682 || self.hover_listener.is_some()
2683 || !self.mouse_up_listeners.is_empty()
2684 || !self.mouse_pressure_listeners.is_empty()
2685 || !self.mouse_down_listeners.is_empty()
2686 || !self.mouse_move_listeners.is_empty()
2687 || !self.mouse_exit_listeners.is_empty()
2688 || !self.file_drop_exit_listeners.is_empty()
2689 || !self.click_listeners.is_empty()
2690 || !self.aux_click_listeners.is_empty()
2691 || !self.scroll_listeners.is_empty()
2692 || self.has_pinch_listeners()
2693 || !self.back_gesture_listeners.is_empty()
2694 || self.drag_listener.is_some()
2695 || !self.drop_listeners.is_empty()
2696 || !self.drag_over_styles.is_empty()
2697 || self.tooltip_builder.is_some()
2698 || window.tags_every_hitbox()
2701 || window.is_inspector_picking(cx)
2702 }
2703
2704 fn max_scroll_offset(
2705 &self,
2706 bounds: Bounds<Pixels>,
2707 style: &Style,
2708 window: &Window,
2709 ) -> Point<Pixels> {
2710 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2711 const ROUNDING_FACTOR: f32 = 100.0;
2712 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2713 }
2714
2715 let rem_size = window.rem_size();
2716 let padding = style
2721 .padding
2722 .to_pixels(bounds.size.into(), rem_size)
2723 .map(|edge| window.pixel_snap(*edge));
2724 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2725 let padded_content_size = self.content_size + padding_size;
2732 let padded_content_size = size(
2733 padded_content_size.width.max(self.out_of_flow_extent.width),
2734 padded_content_size.height.max(self.out_of_flow_extent.height),
2735 );
2736 Point::from(padded_content_size - bounds.size)
2737 .map(round_to_two_decimals)
2738 .max(&Default::default())
2739 }
2740
2741 fn clamp_scroll_position(
2742 &self,
2743 bounds: Bounds<Pixels>,
2744 style: &Style,
2745 window: &mut Window,
2746 _cx: &mut App,
2747 ) -> Point<Pixels> {
2748 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2749 let mut scroll_to_bottom = false;
2750 let mut tracked_scroll_handle = self
2751 .tracked_scroll_handle
2752 .as_ref()
2753 .map(|handle| handle.0.borrow_mut());
2754 if let Some(scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2755 scroll_handle_state.overflow = style.overflow;
2756 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2757 }
2758
2759 let scroll_max = self.max_scroll_offset(bounds, style, window);
2760 let mut scroll_offset = scroll_offset.borrow_mut();
2763
2764 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2765 if scroll_to_bottom {
2766 scroll_offset.y = -scroll_max.y;
2767 } else {
2768 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2769 }
2770
2771 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2772 scroll_handle_state.max_offset = scroll_max;
2773 scroll_handle_state.bounds = bounds;
2774 }
2775
2776 *scroll_offset
2777 } else {
2778 Point::default()
2779 }
2780 }
2781
2782 pub fn paint(
2791 &mut self,
2792 global_id: Option<&GlobalElementId>,
2793 _inspector_id: Option<&InspectorElementId>,
2794 bounds: Bounds<Pixels>,
2795 hitbox: Option<&Hitbox>,
2796 window: &mut Window,
2797 cx: &mut App,
2798 f: impl FnOnce(&Style, &mut Window, &mut App),
2799 ) {
2800 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2801 window.with_optional_element_state::<InteractiveElementState, _>(
2802 global_id,
2803 |element_state, window| {
2804 let mut element_state =
2805 element_state.map(|element_state| element_state.unwrap_or_default());
2806
2807 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2808
2809 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2810 if let Some(debug_selector) = &self.debug_selector {
2811 window
2812 .next_frame
2813 .record_debug_bounds(debug_selector.clone(), bounds);
2814 }
2815
2816 self.paint_hover_group_handler(window, cx);
2817
2818 if style.visibility == Visibility::Hidden {
2819 return ((), element_state);
2820 }
2821
2822 let mut tab_group = None;
2823 if self.tab_group {
2824 tab_group = self.tab_index;
2825 }
2826
2827 let own_transform = style.transform_matrix(bounds, window.scale_factor());
2828 window.vn_with_capture(style.vn_capture, bounds, own_transform, |window| {
2829 window.vn_set_effect_element(global_id);
2830 window.with_element_opacity(style.opacity, |window| {
2831 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2832 window.with_text_style(style.text_style_for_bounds(bounds, window), |window| {
2833 window.with_content_mask(
2834 style.overflow_mask(bounds, window.rem_size()),
2835 |window| {
2836 window.with_tab_group(tab_group, |window| {
2837 if let Some(focus_handle) = &self.tracked_focus_handle {
2846 window.next_frame.tab_stops.insert(focus_handle);
2847 }
2848 if let Some(hitbox) = hitbox {
2849 #[cfg(debug_assertions)]
2850 self.paint_debug_info(
2851 global_id, hitbox, &style, window, cx,
2852 );
2853
2854 if let Some(drag) = cx.active_drag.as_ref() {
2855 if let Some(mouse_cursor) = drag.cursor_style {
2856 window.set_window_cursor_style(mouse_cursor);
2857 }
2858 } else {
2859 if let Some(mouse_cursor) = style.mouse_cursor {
2860 window.set_cursor_style(mouse_cursor, hitbox);
2861 }
2862 }
2863
2864 if let Some(group) = self.group.clone() {
2865 GroupHitboxes::push(group, hitbox.id, cx);
2866 }
2867
2868 if let Some(area) = self.window_control {
2869 window.insert_window_control_hitbox(
2870 area,
2871 hitbox.clone(),
2872 );
2873 }
2874
2875 self.paint_mouse_listeners(
2876 hitbox,
2877 element_state.as_mut(),
2878 window,
2879 cx,
2880 );
2881 self.paint_scroll_listener(hitbox, &style, window, cx);
2882 }
2883
2884 self.paint_keyboard_listeners(window, cx);
2885
2886 if window.a11y.is_active() {
2887 if let Some(global_id) = global_id {
2888 if !self.a11y_action_listeners.is_empty() {
2889 let node_id = global_id.accesskit_node_id();
2890 for (action, listener) in
2891 self.a11y_action_listeners.drain(..)
2892 {
2893 window.on_a11y_action(
2894 node_id, action, listener,
2895 );
2896 }
2897 }
2898 }
2899 }
2900
2901 f(&style, window, cx);
2902
2903 if let Some(_hitbox) = hitbox {
2904 #[cfg(any(feature = "inspector", debug_assertions))]
2905 window.insert_inspector_hitbox(
2906 _hitbox.id,
2907 _inspector_id,
2908 cx,
2909 );
2910
2911 if let Some(group) = self.group.as_ref() {
2912 GroupHitboxes::pop(group, cx);
2913 }
2914 }
2915 })
2916 },
2917 );
2918 });
2919 });
2920 });
2921 });
2922
2923 ((), element_state)
2924 },
2925 );
2926 }
2927
2928 #[cfg(debug_assertions)]
2929 fn paint_debug_info(
2930 &self,
2931 global_id: Option<&GlobalElementId>,
2932 hitbox: &Hitbox,
2933 style: &Style,
2934 window: &mut Window,
2935 cx: &mut App,
2936 ) {
2937 use crate::{BorderStyle, TextAlign};
2938
2939 if let Some(global_id) = global_id
2940 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2941 && hitbox.is_hovered(window)
2942 {
2943 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2944 let element_id = format!("{global_id:?}");
2945 let str_len = element_id.len();
2946
2947 let render_debug_text = |window: &mut Window| {
2948 if let Some(text) = window
2949 .text_system()
2950 .shape_text(
2951 element_id.into(),
2952 FONT_SIZE,
2953 &[window.text_style().to_run(str_len)],
2954 None,
2955 None,
2956 )
2957 .ok()
2958 .and_then(|mut text| text.pop())
2959 {
2960 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2961 .ok();
2962
2963 let text_bounds = crate::Bounds {
2964 origin: hitbox.origin,
2965 size: text.size(FONT_SIZE),
2966 };
2967 if let Some(source_location) = self.source_location
2968 && text_bounds.contains(&window.mouse_position())
2969 && window.modifiers().secondary(cx)
2970 {
2971 let secondary_held = window.modifiers().secondary(cx);
2972 window.on_key_event({
2973 move |e: &crate::ModifiersChangedEvent, _phase, window, cx| {
2974 if e.modifiers.secondary(cx) != secondary_held
2975 && text_bounds.contains(&window.mouse_position())
2976 {
2977 window.refresh();
2978 }
2979 }
2980 });
2981
2982 let was_hovered = hitbox.is_hovered(window);
2983 let current_view = window.current_view();
2984 window.on_mouse_event({
2985 let hitbox = hitbox.clone();
2986 move |_: &MouseMoveEvent, phase, window, cx| {
2987 if phase == DispatchPhase::Capture {
2988 let hovered = hitbox.is_hovered(window);
2989 if hovered != was_hovered {
2990 cx.notify(current_view)
2991 }
2992 }
2993 }
2994 });
2995
2996 window.on_mouse_event({
2997 let hitbox = hitbox.clone();
2998 move |e: &crate::MouseDownEvent, phase, window, cx| {
2999 if text_bounds.contains(&e.position)
3000 && phase.capture()
3001 && hitbox.is_hovered(window)
3002 {
3003 cx.stop_propagation();
3004 let Ok(dir) = std::env::current_dir() else {
3005 return;
3006 };
3007
3008 eprintln!(
3009 "This element was created at:\n{}:{}:{}",
3010 dir.join(source_location.file()).to_string_lossy(),
3011 source_location.line(),
3012 source_location.column()
3013 );
3014 }
3015 }
3016 });
3017 window.paint_quad(crate::outline(
3018 crate::Bounds {
3019 origin: hitbox.origin
3020 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
3021 size: crate::Size {
3022 width: text_bounds.size.width,
3023 height: crate::px(1.),
3024 },
3025 },
3026 crate::red(),
3027 BorderStyle::default(),
3028 ))
3029 }
3030 }
3031 };
3032
3033 window.with_text_style(
3034 Some(crate::TextStyleRefinement {
3035 color: Some(crate::red()),
3036 line_height: Some(FONT_SIZE.into()),
3037 background_color: Some(crate::white()),
3038 ..Default::default()
3039 }),
3040 render_debug_text,
3041 )
3042 }
3043 }
3044
3045 fn paint_mouse_listeners(
3046 &mut self,
3047 hitbox: &Hitbox,
3048 element_state: Option<&mut InteractiveElementState>,
3049 window: &mut Window,
3050 cx: &mut App,
3051 ) {
3052 let is_focused = self
3053 .tracked_focus_handle
3054 .as_ref()
3055 .map(|handle| handle.is_focused(window))
3056 .unwrap_or(false);
3057
3058 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
3062 let hitbox = hitbox.clone();
3063 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
3064 if phase == DispatchPhase::Bubble
3065 && hitbox.is_hovered(window)
3066 && !window.default_prevented()
3067 {
3068 window.focus(&focus_handle, cx);
3069 window.prevent_default();
3072 }
3073 });
3074 }
3075
3076 for listener in self.mouse_down_listeners.drain(..) {
3077 let hitbox = hitbox.clone();
3078 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
3079 listener(event, phase, &hitbox, window, cx);
3080 })
3081 }
3082
3083 for listener in self.mouse_up_listeners.drain(..) {
3084 let hitbox = hitbox.clone();
3085 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
3086 listener(event, phase, &hitbox, window, cx);
3087 })
3088 }
3089
3090 for listener in self.mouse_pressure_listeners.drain(..) {
3091 let hitbox = hitbox.clone();
3092 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
3093 listener(event, phase, &hitbox, window, cx);
3094 })
3095 }
3096
3097 for listener in self.mouse_move_listeners.drain(..) {
3098 let hitbox = hitbox.clone();
3099 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
3100 listener(event, phase, &hitbox, window, cx);
3101 })
3102 }
3103
3104 for listener in self.mouse_exit_listeners.drain(..) {
3105 let hitbox = hitbox.clone();
3106 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
3107 listener(event, phase, &hitbox, window, cx);
3108 })
3109 }
3110
3111 for listener in self.file_drop_exit_listeners.drain(..) {
3112 let hitbox = hitbox.clone();
3113 window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
3114 listener(event, phase, &hitbox, window, cx);
3115 })
3116 }
3117
3118 for listener in self.scroll_listeners.drain(..) {
3119 let hitbox = hitbox.clone();
3120 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
3121 listener(event, phase, &hitbox, window, cx);
3122 })
3123 }
3124
3125 for listener in self.pinch_listeners.drain(..) {
3126 let hitbox = hitbox.clone();
3127 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
3128 listener(event, phase, &hitbox, window, cx);
3129 })
3130 }
3131
3132 for listener in self.back_gesture_listeners.drain(..) {
3133 let hitbox = hitbox.clone();
3134 window.on_mouse_event(move |event: &BackGestureEvent, phase, window, cx| {
3135 listener(event, phase, &hitbox, window, cx);
3136 })
3137 }
3138
3139 if self.hover_style.is_some()
3140 || self.base_style.mouse_cursor.is_some()
3141 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
3142 {
3143 let hitbox = hitbox.clone();
3144 let hover_state = self.hover_style.as_ref().and_then(|_| {
3145 element_state
3146 .as_ref()
3147 .and_then(|state| state.hover_state.as_ref())
3148 .cloned()
3149 });
3150 let current_view = window.current_view();
3151
3152 let hover_style_mode = self.hover_style_mode;
3153 if let Some(hover_state) = &hover_state {
3154 let hovered = hover_style_mode.is_hovered(&hitbox, window);
3155 catch_up_stored_hover(hover_state, |s| &mut s.element, hovered, window, cx);
3156 }
3157 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3158 let hovered = hover_style_mode.is_hovered(&hitbox, window);
3160 let was_hovered = hover_state
3161 .as_ref()
3162 .is_some_and(|state| state.borrow().element);
3163 if phase == DispatchPhase::Capture && hovered != was_hovered {
3164 if let Some(hover_state) = &hover_state {
3165 hover_state.borrow_mut().element = hovered;
3166 cx.notify(current_view);
3167 }
3168 }
3169 });
3170 }
3171
3172 if let Some(group_hover) = self.group_hover_style.as_ref() {
3173 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3174 let hover_state = element_state
3175 .as_ref()
3176 .and_then(|element| element.hover_state.as_ref())
3177 .cloned();
3178 let current_view = window.current_view();
3179
3180 let hover_style_mode = self.hover_style_mode;
3181 if let Some(hover_state) = &hover_state {
3182 let group_hovered = hover_style_mode.is_hovered_id(group_hitbox_id, window);
3183 catch_up_stored_hover(hover_state, |s| &mut s.group, group_hovered, window, cx);
3184 }
3185 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3186 let group_hovered = hover_style_mode.is_hovered_id(group_hitbox_id, window);
3188 let was_group_hovered = hover_state
3189 .as_ref()
3190 .is_some_and(|state| state.borrow().group);
3191 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
3192 if let Some(hover_state) = &hover_state {
3193 hover_state.borrow_mut().group = group_hovered;
3194 cx.notify(current_view);
3195 }
3196 }
3197 });
3198 }
3199 }
3200
3201 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
3202
3203 let mut drag_listener = mem::take(&mut self.drag_listener);
3204 let drop_listeners = mem::take(&mut self.drop_listeners);
3205 let click_listeners = mem::take(&mut self.click_listeners);
3206 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
3207 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
3208
3209 if !drop_listeners.is_empty() {
3210 let hitbox = hitbox.clone();
3211 window.on_mouse_event({
3212 move |_: &MouseUpEvent, phase, window, cx| {
3213 if let Some(drag) = &cx.active_drag
3214 && phase == DispatchPhase::Bubble
3215 && hitbox.is_hovered(window)
3216 {
3217 let drag_state_type = drag.value.as_ref().type_id();
3218 for (drop_state_type, listener) in &drop_listeners {
3219 if *drop_state_type == drag_state_type {
3220 let drag = cx
3221 .active_drag
3222 .take()
3223 .expect("checked for type drag state type above");
3224
3225 let mut can_drop = true;
3226 if let Some(predicate) = &can_drop_predicate {
3227 can_drop = predicate(drag.value.as_ref(), window, cx);
3228 }
3229
3230 if can_drop {
3231 listener(drag.value.as_ref(), window, cx);
3232 window.refresh();
3233 cx.stop_propagation();
3234 }
3235 }
3236 }
3237 }
3238 }
3239 });
3240 }
3241
3242 if let Some(element_state) = element_state {
3243 if !click_listeners.is_empty()
3244 || !aux_click_listeners.is_empty()
3245 || drag_listener.is_some()
3246 {
3247 let pending_mouse_down = element_state
3248 .pending_mouse_down
3249 .get_or_insert_with(Default::default)
3250 .clone();
3251
3252 let pending_keyboard_down = element_state
3253 .pending_keyboard_down
3254 .get_or_insert_with(Default::default)
3255 .clone();
3256
3257 let clicked_state = element_state
3258 .clicked_state
3259 .get_or_insert_with(Default::default)
3260 .clone();
3261
3262 window.on_mouse_event({
3263 let pending_mouse_down = pending_mouse_down.clone();
3264 let hitbox = hitbox.clone();
3265 let has_aux_click_listeners = !aux_click_listeners.is_empty();
3266 move |event: &MouseDownEvent, phase, window, _cx| {
3267 if phase == DispatchPhase::Bubble
3268 && (event.button == MouseButton::Left || has_aux_click_listeners)
3269 && hitbox.is_hovered(window)
3270 {
3271 *pending_mouse_down.borrow_mut() = Some(event.clone());
3272 window.refresh();
3273 }
3274 }
3275 });
3276
3277 window.on_mouse_event({
3278 let pending_mouse_down = pending_mouse_down.clone();
3279 let hitbox = hitbox.clone();
3280 move |event: &MouseMoveEvent, phase, window, cx| {
3281 if phase == DispatchPhase::Capture {
3282 return;
3283 }
3284
3285 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3286 if let Some(mouse_down) = pending_mouse_down.clone()
3287 && !cx.has_active_drag()
3288 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
3289 && let Some(listener) = drag_listener.take()
3290 && mouse_down.button == MouseButton::Left
3291 {
3292 *clicked_state.borrow_mut() = ElementClickedState::default();
3293 let cursor_offset = event.position - hitbox.origin;
3294 let drag = (listener.render)(
3295 listener.value.as_ref(),
3296 cursor_offset,
3297 window,
3298 cx,
3299 );
3300 let external_payload_source =
3301 listener.external_payload.map(|external_payload| {
3302 let value = listener.value.clone();
3303 Box::new(move |window: &mut Window, cx: &mut App| {
3304 external_payload(value.as_ref(), window, cx)
3305 })
3306 as ExternalDragPayloadSource
3307 });
3308 cx.active_drag = Some(AnyDrag {
3309 view: drag,
3310 value: listener.value,
3311 cursor_offset,
3312 cursor_style: drag_cursor_style,
3313 external_payload_source,
3314 });
3315 pending_mouse_down.take();
3316 window.refresh();
3317 cx.stop_propagation();
3318 }
3319 }
3320 });
3321
3322 if is_focused {
3323 window.on_key_event({
3333 let pending_keyboard_down = pending_keyboard_down.clone();
3334 move |event: &KeyDownEvent, phase, window, _cx| {
3335 if phase.bubble() && !window.default_prevented() {
3336 let stroke = &event.keystroke;
3337 let is_activation_key = (stroke.key.eq("enter")
3338 || stroke.key.eq("space"))
3339 && !stroke.modifiers.modified();
3340 *pending_keyboard_down.borrow_mut() =
3341 is_activation_key.then_some(window.focus_generation);
3342 }
3343 }
3344 });
3345
3346 window.on_key_event({
3348 let click_listeners = click_listeners.clone();
3349 let hitbox = hitbox.clone();
3350 move |event: &KeyUpEvent, phase, window, cx| {
3351 if phase.bubble() && !window.default_prevented() {
3352 let stroke = &event.keystroke;
3353 let keyboard_button = if stroke.key.eq("enter") {
3354 Some(KeyboardButton::Enter)
3355 } else if stroke.key.eq("space") {
3356 Some(KeyboardButton::Space)
3357 } else {
3358 None
3359 };
3360
3361 if let Some(button) = keyboard_button
3362 && !stroke.modifiers.modified()
3363 {
3364 let pending =
3365 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
3366 if pending != Some(window.focus_generation) {
3367 return;
3368 }
3369
3370 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
3371 button,
3372 bounds: hitbox.bounds,
3373 });
3374
3375 for listener in &click_listeners {
3376 listener(&click_event, window, cx);
3377 }
3378 } else {
3379 *pending_keyboard_down.borrow_mut() = None;
3383 }
3384 }
3385 }
3386 });
3387 }
3388
3389 window.on_mouse_event({
3390 let mut captured_mouse_down = None;
3391 let hitbox = hitbox.clone();
3392 move |event: &MouseUpEvent, phase, window, cx| match phase {
3393 DispatchPhase::Capture => {
3397 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3398 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
3399 captured_mouse_down = pending_mouse_down.take();
3400 window.refresh();
3401 } else if pending_mouse_down.is_some() {
3402 pending_mouse_down.take();
3408 window.refresh();
3409 }
3410 }
3411 DispatchPhase::Bubble => {
3413 if let Some(mouse_down) = captured_mouse_down.take() {
3414 let btn = mouse_down.button;
3415
3416 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
3417 down: mouse_down,
3418 up: event.clone(),
3419 });
3420
3421 match btn {
3422 MouseButton::Left => {
3423 for listener in &click_listeners {
3424 listener(&mouse_click, window, cx);
3425 }
3426 }
3427 _ => {
3428 for listener in &aux_click_listeners {
3429 listener(&mouse_click, window, cx);
3430 }
3431 }
3432 }
3433 }
3434 }
3435 }
3436 });
3437 }
3438
3439 if let Some(hover_listener) = self.hover_listener.take() {
3440 let was_hovered = element_state
3441 .hover_listener_state
3442 .get_or_insert_with(Default::default)
3443 .clone();
3444 let has_mouse_down = element_state
3445 .pending_mouse_down
3446 .get_or_insert_with(Default::default)
3447 .clone();
3448 let hover_listener = Rc::new(hover_listener);
3449 let hover_listener_state = was_hovered.clone();
3450 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3451 let mut was_hovered = hover_listener_state.borrow_mut();
3452 if is_hovered != *was_hovered {
3453 *was_hovered = is_hovered;
3454 drop(was_hovered);
3455 hover_listener(&is_hovered, window, cx);
3456 }
3457 };
3458 let hover_listener_mode = self.hover_listener_mode;
3459
3460 if has_mouse_down.borrow().is_none() {
3461 let is_hovered =
3462 !cx.has_active_drag() && hover_listener_mode.is_hovered(hitbox, window);
3463 if is_hovered != *was_hovered.borrow() {
3464 let update_hover = update_hover.clone();
3465 window.defer(cx, move |window, cx| {
3466 update_hover(is_hovered, window, cx);
3467 });
3468 }
3469 }
3470
3471 window.on_mouse_event({
3472 let update_hover = update_hover.clone();
3473 let hitbox = hitbox.clone();
3474 move |_: &MouseMoveEvent, phase, window, cx| {
3475 if phase == DispatchPhase::Bubble {
3476 let is_hovered = has_mouse_down.borrow().is_none()
3477 && !cx.has_active_drag()
3478 && hover_listener_mode.is_hovered(&hitbox, window);
3479 update_hover(is_hovered, window, cx);
3480 }
3481 }
3482 });
3483
3484 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3487 if phase == DispatchPhase::Bubble {
3488 update_hover(false, window, cx);
3489 }
3490 });
3491 }
3492
3493 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3494 let active_tooltip = element_state
3495 .active_tooltip
3496 .get_or_insert_with(Default::default)
3497 .clone();
3498 let pending_mouse_down = element_state
3499 .pending_mouse_down
3500 .get_or_insert_with(Default::default)
3501 .clone();
3502 let long_press_tooltip_active = element_state
3503 .long_press_tooltip_active
3504 .get_or_insert_with(Default::default)
3505 .clone();
3506
3507 let tooltip_is_hoverable = tooltip_builder.hoverable;
3508 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3509 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3510 });
3511 let check_is_hovered_during_prepaint = Rc::new({
3513 let pending_mouse_down = pending_mouse_down.clone();
3514 let source_bounds = hitbox.bounds;
3515 move |window: &Window| {
3516 !window.last_input_was_keyboard()
3517 && pending_mouse_down.borrow().is_none()
3518 && source_bounds.contains(&window.mouse_position())
3519 }
3520 });
3521 let check_is_hovered = Rc::new({
3522 let hitbox = hitbox.clone();
3523 move |window: &Window| {
3524 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3525 }
3526 });
3527 register_tooltip_mouse_handlers(
3528 &active_tooltip,
3529 self.tooltip_id,
3530 build_tooltip,
3531 check_is_hovered,
3532 check_is_hovered_during_prepaint,
3533 long_press_tooltip_active,
3534 self.tooltip_show_delay,
3535 window,
3536 );
3537 }
3538
3539 let active_state = element_state
3542 .clicked_state
3543 .get_or_insert_with(Default::default)
3544 .clone();
3545
3546 {
3547 let active_state = active_state.clone();
3548 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3549 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3550 *active_state.borrow_mut() = ElementClickedState::default();
3551 window.refresh();
3552 }
3553 });
3554 }
3555
3556 {
3557 let active_group_hitbox = self
3558 .group_active_style
3559 .as_ref()
3560 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3561 let hitbox = hitbox.clone();
3562 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3563 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3564 let group_hovered = active_group_hitbox
3565 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3566 let element_hovered = hitbox.is_hovered(window);
3567 if group_hovered || element_hovered {
3568 *active_state.borrow_mut() = ElementClickedState {
3569 group: group_hovered,
3570 element: element_hovered,
3571 };
3572 window.refresh();
3573 }
3574 }
3575 });
3576 }
3577 }
3578 }
3579
3580 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3581 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3582 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3583 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3584 let action_listeners = mem::take(&mut self.action_listeners);
3585 if let Some(context) = self.key_context.clone() {
3586 window.set_key_context(context);
3587 }
3588
3589 for listener in key_down_listeners {
3590 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3591 listener(event, phase, window, cx);
3592 })
3593 }
3594
3595 for listener in key_up_listeners {
3596 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3597 listener(event, phase, window, cx);
3598 })
3599 }
3600
3601 for listener in modifiers_changed_listeners {
3602 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3603 listener(event, window, cx);
3604 })
3605 }
3606
3607 for (action_type, listener) in action_listeners {
3608 window.on_action(action_type, listener)
3609 }
3610 }
3611
3612 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3613 let group_hitbox = self
3614 .group_hover_style
3615 .as_ref()
3616 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3617
3618 if let Some(group_hitbox) = group_hitbox {
3619 let was_hovered = group_hitbox.is_hovered(window);
3620 let current_view = window.current_view();
3621 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3622 let hovered = group_hitbox.is_hovered(window);
3623 if phase == DispatchPhase::Capture && hovered != was_hovered {
3624 cx.notify(current_view);
3625 }
3626 });
3627 }
3628 }
3629
3630 fn paint_scroll_listener(
3631 &self,
3632 hitbox: &Hitbox,
3633 style: &Style,
3634 window: &mut Window,
3635 _cx: &mut App,
3636 ) {
3637 if let Some(scroll_offset) = self.scroll_offset.clone() {
3638 let scroll_max = self.max_scroll_offset(hitbox.bounds, style, window);
3639 let ongoing_scroll = self.ongoing_scroll.clone();
3640 let overflow = style.overflow;
3641 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3642 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3643 let line_height = window.line_height();
3644 let hitbox = hitbox.clone();
3645 let current_view = window.current_view();
3646 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
3647 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3648 let mut scroll_offset = scroll_offset.borrow_mut();
3649 let old_scroll_offset = *scroll_offset;
3650 let mut delta = event.delta.pixel_delta(line_height);
3651
3652 if restrict_scroll_to_axis
3653 && event.delta.precise()
3654 && let Some(ongoing_scroll) = &ongoing_scroll
3655 {
3656 ongoing_scroll
3657 .borrow_mut()
3658 .filter(&mut delta, event.touch_phase);
3659 }
3660
3661 let mut delta_x = match overflow.x {
3662 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3663 Overflow::Scroll
3664 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3665 {
3666 delta.y
3667 }
3668 _ => Pixels::ZERO,
3669 };
3670 let mut delta_y = match overflow.y {
3671 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3672 Overflow::Scroll
3673 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3674 {
3675 delta.x
3676 }
3677 _ => Pixels::ZERO,
3678 };
3679 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3680 if delta_x.abs() > delta_y.abs() {
3681 delta_y = Pixels::ZERO;
3682 } else {
3683 delta_x = Pixels::ZERO;
3684 }
3685 }
3686 scroll_offset.y = (scroll_offset.y + delta_y).clamp(-scroll_max.y, px(0.));
3689 scroll_offset.x = (scroll_offset.x + delta_x).clamp(-scroll_max.x, px(0.));
3690 if *scroll_offset != old_scroll_offset {
3691 cx.notify(current_view);
3692 }
3693 }
3694 });
3695 }
3696 }
3697
3698 pub fn compute_style(
3700 &self,
3701 global_id: Option<&GlobalElementId>,
3702 hitbox: Option<&Hitbox>,
3703 window: &mut Window,
3704 cx: &mut App,
3705 ) -> Style {
3706 window.with_optional_element_state(global_id, |element_state, window| {
3707 let mut element_state =
3708 element_state.map(|element_state| element_state.unwrap_or_default());
3709 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3710 (style, element_state)
3711 })
3712 }
3713
3714 fn compute_style_internal(
3716 &self,
3717 hitbox: Option<&Hitbox>,
3718 element_state: Option<&mut InteractiveElementState>,
3719 window: &mut Window,
3720 cx: &mut App,
3721 ) -> Style {
3722 let mut style = Style::default();
3723 style.refine(&self.base_style);
3724
3725 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3726 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3727 && focus_handle.within_focused(window, cx)
3728 {
3729 style.refine(in_focus_style);
3730 }
3731
3732 if let Some(focus_style) = self.focus_style.as_ref()
3733 && focus_handle.is_focused(window)
3734 {
3735 style.refine(focus_style);
3736 }
3737
3738 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3739 && focus_handle.is_focused(window)
3740 && window.last_input_was_keyboard()
3741 {
3742 style.refine(focus_visible_style);
3743 }
3744 }
3745
3746 if !cx.has_active_drag() {
3747 if let Some(group_hover) = self.group_hover_style.as_ref() {
3748 let is_group_hovered =
3749 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3750 !window.last_input_was_touch()
3752 && self.hover_style_mode.is_hovered_id(group_hitbox_id, window)
3753 } else if let Some(element_state) = element_state.as_ref() {
3754 !window.last_input_was_touch()
3755 && element_state
3756 .hover_state
3757 .as_ref()
3758 .map(|state| state.borrow().group)
3759 .unwrap_or(false)
3760 } else {
3761 false
3762 };
3763
3764 if is_group_hovered {
3765 style.refine(&group_hover.style);
3766 }
3767 }
3768
3769 if let Some(hover_style) = self.hover_style.as_ref() {
3770 let is_hovered = if let Some(hitbox) = hitbox {
3771 !window.last_input_was_touch()
3773 && self.hover_style_mode.is_hovered(hitbox, window)
3774 } else if let Some(element_state) = element_state.as_ref() {
3775 !window.last_input_was_touch()
3776 && element_state
3777 .hover_state
3778 .as_ref()
3779 .map(|state| state.borrow().element)
3780 .unwrap_or(false)
3781 } else {
3782 false
3783 };
3784
3785 if is_hovered {
3786 style.refine(hover_style);
3787 }
3788 }
3789 }
3790
3791 if let Some(hitbox) = hitbox {
3792 if let Some(drag) = cx.active_drag.take() {
3793 let mut can_drop = true;
3794 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3795 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3796 }
3797
3798 if can_drop {
3799 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3800 if let Some(group_hitbox_id) =
3801 GroupHitboxes::get(&group_drag_style.group, cx)
3802 && *state_type == drag.value.as_ref().type_id()
3803 && group_hitbox_id.is_hovered(window)
3804 {
3805 style.refine(&group_drag_style.style);
3806 }
3807 }
3808
3809 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3810 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3811 {
3812 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3813 }
3814 }
3815 }
3816
3817 style.mouse_cursor = drag.cursor_style;
3818 cx.active_drag = Some(drag);
3819 }
3820 }
3821
3822 if let Some(element_state) = element_state {
3823 let clicked_state = element_state
3824 .clicked_state
3825 .get_or_insert_with(Default::default)
3826 .borrow();
3827 if clicked_state.group
3828 && let Some(group) = self.group_active_style.as_ref()
3829 {
3830 style.refine(&group.style)
3831 }
3832
3833 if let Some(active_style) = self.active_style.as_ref()
3834 && clicked_state.element
3835 {
3836 style.refine(active_style)
3837 }
3838 }
3839
3840 style
3841 }
3842
3843 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3844 if let Some(id) = &self.aria.author_id {
3845 node.set_author_id(id.to_string());
3846 }
3847 if let Some(label) = &self.aria.label {
3848 node.set_label(label.to_string());
3849 }
3850 if let Some(description) = &self.aria.description {
3851 node.set_description(description.to_string());
3852 }
3853 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3854 node.set_keyboard_shortcut(keyshortcuts.to_string());
3855 }
3856 if let Some(selected) = self.aria.selected {
3857 node.set_selected(selected);
3858 }
3859 if let Some(expanded) = self.aria.expanded {
3860 node.set_expanded(expanded);
3861 }
3862 if let Some(toggled) = self.aria.toggled {
3863 node.set_toggled(toggled);
3864 }
3865 if let Some(value) = self.aria.numeric_value {
3866 node.set_numeric_value(value);
3867 }
3868 if let Some(value) = self.aria.min_numeric_value {
3869 node.set_min_numeric_value(value);
3870 }
3871 if let Some(value) = self.aria.max_numeric_value {
3872 node.set_max_numeric_value(value);
3873 }
3874 if let Some(step) = self.aria.numeric_value_step {
3875 node.set_numeric_value_step(step);
3876 }
3877 if let Some(value) = &self.aria.value {
3878 node.set_value(value.to_string());
3879 }
3880 if let Some(placeholder) = &self.aria.placeholder {
3881 node.set_placeholder(placeholder.to_string());
3882 }
3883 if let Some(orientation) = self.aria.orientation {
3884 node.set_orientation(orientation);
3885 }
3886 if let Some(level) = self.aria.level {
3887 node.set_level(level);
3888 }
3889 if let Some(position) = self.aria.position_in_set {
3890 node.set_position_in_set(position);
3891 }
3892 if let Some(size) = self.aria.size_of_set {
3893 node.set_size_of_set(size);
3894 }
3895 if let Some(index) = self.aria.row_index {
3896 node.set_row_index(index);
3897 }
3898 if let Some(index) = self.aria.column_index {
3899 node.set_column_index(index);
3900 }
3901 if let Some(count) = self.aria.row_count {
3902 node.set_row_count(count);
3903 }
3904 if let Some(count) = self.aria.column_count {
3905 node.set_column_count(count);
3906 }
3907 match self.aria.disabled {
3910 Some(true) => node.set_disabled(),
3911 Some(false) => node.clear_disabled(),
3912 None => {}
3913 }
3914 match self.aria.read_only {
3915 Some(true) => node.set_read_only(),
3916 Some(false) => node.clear_read_only(),
3917 None => {}
3918 }
3919 match self.aria.required {
3920 Some(true) => node.set_required(),
3921 Some(false) => node.clear_required(),
3922 None => {}
3923 }
3924 match self.aria.modal {
3925 Some(true) => node.set_modal(),
3926 Some(false) => node.clear_modal(),
3927 None => {}
3928 }
3929 match self.aria.hidden {
3930 Some(true) => node.set_hidden(),
3931 Some(false) => node.clear_hidden(),
3932 None => {}
3933 }
3934 if !self.click_listeners.is_empty() {
3935 node.add_action(accesskit::Action::Click);
3936 }
3937 if self.tracked_focus_handle.is_some() || self.focusable {
3938 node.add_action(accesskit::Action::Focus);
3939 }
3940 for (action, _) in &self.a11y_action_listeners {
3941 node.add_action(*action);
3942 }
3943 }
3944}
3945
3946#[derive(Default)]
3949pub struct InteractiveElementState {
3950 pub(crate) focus_handle: Option<FocusHandle>,
3951 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3952 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3953 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3954 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3955 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3963 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3964 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3965 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3966 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3967}
3968
3969#[derive(Copy, Clone, Default, Eq, PartialEq)]
3971pub struct ElementClickedState {
3972 pub group: bool,
3974
3975 pub element: bool,
3977}
3978
3979impl ElementClickedState {
3980 fn is_clicked(&self) -> bool {
3981 self.group || self.element
3982 }
3983}
3984
3985#[derive(Copy, Clone, Default, Eq, PartialEq)]
3987pub struct ElementHoverState {
3988 pub group: bool,
3990
3991 pub element: bool,
3993}
3994
3995fn catch_up_stored_hover(
4009 state: &Rc<RefCell<ElementHoverState>>,
4010 field: impl FnOnce(&mut ElementHoverState) -> &mut bool,
4011 hovered: bool,
4012 window: &mut Window,
4013 cx: &mut App,
4014) {
4015 let mut state = state.borrow_mut();
4016 let stored = field(&mut state);
4017 if *stored != hovered {
4018 *stored = hovered;
4019 let current_view = window.current_view();
4020 window.defer(cx, move |_, cx| cx.notify(current_view));
4021 }
4022}
4023
4024pub(crate) enum ActiveTooltip {
4025 WaitingForShow { _task: Task<()> },
4027 Visible {
4029 tooltip: AnyTooltip,
4030 is_hoverable: bool,
4031 },
4032 WaitingForHide {
4035 tooltip: AnyTooltip,
4036 _task: Task<()>,
4037 },
4038}
4039
4040pub(crate) fn clear_active_tooltip(
4041 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4042 window: &mut Window,
4043) {
4044 match active_tooltip.borrow_mut().take() {
4045 None => {}
4046 Some(ActiveTooltip::WaitingForShow { .. }) => {}
4047 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
4048 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
4049 }
4050}
4051
4052pub(crate) fn clear_active_tooltip_if_not_hoverable(
4053 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4054 window: &mut Window,
4055) {
4056 let should_clear = match active_tooltip.borrow().as_ref() {
4057 None => false,
4058 Some(ActiveTooltip::WaitingForShow { .. }) => false,
4059 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
4060 Some(ActiveTooltip::WaitingForHide { .. }) => false,
4061 };
4062 if should_clear {
4063 active_tooltip.borrow_mut().take();
4064 window.refresh();
4065 }
4066}
4067
4068pub(crate) fn set_tooltip_on_window(
4069 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4070 window: &mut Window,
4071) -> Option<TooltipId> {
4072 let tooltip = match active_tooltip.borrow().as_ref() {
4073 None => return None,
4074 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
4075 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
4076 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
4077 };
4078 Some(window.set_tooltip(tooltip))
4079}
4080
4081pub(crate) fn register_tooltip_mouse_handlers(
4082 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4083 tooltip_id: Option<TooltipId>,
4084 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4085 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
4086 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
4087 long_press_tooltip_active: Rc<Cell<bool>>,
4088 show_delay: Option<Duration>,
4089 window: &mut Window,
4090) {
4091 let current_view = window.current_view();
4092 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
4093
4094 window.on_mouse_event({
4095 let active_tooltip = active_tooltip.clone();
4096 let build_tooltip = build_tooltip.clone();
4097 let check_is_hovered = check_is_hovered.clone();
4098 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4099 move |_: &MouseMoveEvent, phase, window, cx| {
4100 handle_tooltip_mouse_move(
4101 &active_tooltip,
4102 &build_tooltip,
4103 &check_is_hovered,
4104 &check_is_hovered_during_prepaint,
4105 tooltip_id,
4106 current_view,
4107 phase,
4108 show_delay,
4109 window,
4110 cx,
4111 )
4112 }
4113 });
4114
4115 window.on_mouse_event({
4116 let active_tooltip = active_tooltip.clone();
4117 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
4118 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
4119 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
4120 }
4121 }
4122 });
4123
4124 window.on_mouse_event({
4125 let active_tooltip = active_tooltip.clone();
4126 let build_tooltip = build_tooltip.clone();
4127 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4128 move |event: &LongPressEvent, phase, window, cx| {
4129 if !phase.bubble() {
4130 return;
4131 }
4132
4133 match event.phase {
4134 TouchPhase::Started if !window.default_prevented() && check_is_hovered(window) => {
4135 if show_tooltip(
4136 &active_tooltip,
4137 &build_tooltip,
4138 &check_is_hovered_during_prepaint,
4139 Some(long_press_tooltip_active.clone()),
4140 window,
4141 cx,
4142 ) {
4143 long_press_tooltip_active.set(true);
4144 window.prevent_default();
4145 cx.stop_propagation();
4146 }
4147 }
4148 TouchPhase::Ended | TouchPhase::Cancelled
4149 if long_press_tooltip_active.replace(false) =>
4150 {
4151 clear_active_tooltip(&active_tooltip, window);
4152 cx.stop_propagation();
4153 }
4154 TouchPhase::Started
4155 | TouchPhase::Moved
4156 | TouchPhase::Ended
4157 | TouchPhase::Cancelled => {}
4158 }
4159 }
4160 });
4161
4162 window.on_mouse_event({
4163 let active_tooltip = active_tooltip.clone();
4164 move |_: &ScrollEvent, _phase, window: &mut Window, _cx| {
4165 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
4166 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
4167 }
4168 }
4169 });
4170}
4171
4172fn handle_tooltip_mouse_move(
4184 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4185 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4186 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
4187 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
4188 tooltip_id: Option<TooltipId>,
4189 current_view: EntityId,
4190 phase: DispatchPhase,
4191 show_delay: Duration,
4192 window: &mut Window,
4193 cx: &mut App,
4194) {
4195 enum Action {
4198 None,
4199 CancelShow,
4200 ScheduleShow,
4201 CheckVisible,
4202 }
4203
4204 let action = match active_tooltip.borrow().as_ref() {
4205 None => {
4206 let is_hovered = check_is_hovered(window);
4207 if is_hovered && phase.bubble() {
4208 Action::ScheduleShow
4209 } else {
4210 Action::None
4211 }
4212 }
4213 Some(ActiveTooltip::WaitingForShow { .. }) => {
4214 let is_hovered = check_is_hovered(window);
4215 if is_hovered {
4216 Action::None
4217 } else {
4218 Action::CancelShow
4219 }
4220 }
4221 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
4222 if phase.capture()
4223 && !check_is_hovered(window)
4224 && (!*is_hoverable
4225 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
4226 {
4227 Action::CheckVisible
4228 } else {
4229 Action::None
4230 }
4231 }
4232 Some(ActiveTooltip::WaitingForHide { .. }) => {
4233 if phase.capture()
4234 && (check_is_hovered(window)
4235 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
4236 {
4237 Action::CheckVisible
4238 } else {
4239 Action::None
4240 }
4241 }
4242 };
4243
4244 match action {
4245 Action::None => {}
4246 Action::CancelShow => {
4247 active_tooltip.borrow_mut().take();
4249 }
4250 Action::ScheduleShow => {
4251 let delayed_show_task = window.spawn(cx, {
4252 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4253 let build_tooltip = build_tooltip.clone();
4254 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4255 async move |cx| {
4256 cx.background_executor().timer(show_delay).await;
4257 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4258 return;
4259 };
4260 cx.update(|window, cx| {
4261 show_tooltip(
4262 &active_tooltip,
4263 &build_tooltip,
4264 &check_is_hovered_during_prepaint,
4265 None,
4266 window,
4267 cx,
4268 );
4269 })
4270 .ok();
4271 }
4272 });
4273 active_tooltip
4274 .borrow_mut()
4275 .replace(ActiveTooltip::WaitingForShow {
4276 _task: delayed_show_task,
4277 });
4278 }
4279 Action::CheckVisible => cx.notify(current_view),
4280 }
4281}
4282
4283fn show_tooltip(
4284 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4285 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4286 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
4287 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
4288 window: &mut Window,
4289 cx: &mut App,
4290) -> bool {
4291 let new_tooltip = build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
4292 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4293 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4294 ActiveTooltip::Visible {
4295 tooltip: AnyTooltip {
4296 view,
4297 mouse_position: window.mouse_position(),
4298 check_visible_and_update: Rc::new(move |tooltip_bounds, window, cx| {
4299 if long_press_tooltip_active
4300 .as_ref()
4301 .is_some_and(|active| active.get())
4302 {
4303 return true;
4304 }
4305 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4306 return false;
4307 };
4308 handle_tooltip_check_visible_and_update(
4309 &active_tooltip,
4310 tooltip_is_hoverable,
4311 &check_is_hovered_during_prepaint,
4312 tooltip_bounds,
4313 window,
4314 cx,
4315 )
4316 }),
4317 },
4318 is_hoverable: tooltip_is_hoverable,
4319 }
4320 });
4321 let did_show = new_tooltip.is_some();
4322 *active_tooltip.borrow_mut() = new_tooltip;
4323 window.refresh();
4324 did_show
4325}
4326
4327fn handle_tooltip_check_visible_and_update(
4331 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4332 tooltip_is_hoverable: bool,
4333 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
4334 tooltip_bounds: Bounds<Pixels>,
4335 window: &mut Window,
4336 cx: &mut App,
4337) -> bool {
4338 enum Action {
4341 None,
4342 Hide,
4343 ScheduleHide(AnyTooltip),
4344 CancelHide(AnyTooltip),
4345 }
4346
4347 let is_hovered = check_is_hovered(window)
4348 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
4349 let action = match active_tooltip.borrow().as_ref() {
4350 Some(ActiveTooltip::Visible { tooltip, .. }) => {
4351 if is_hovered {
4352 Action::None
4353 } else {
4354 if tooltip_is_hoverable {
4355 Action::ScheduleHide(tooltip.clone())
4356 } else {
4357 Action::Hide
4358 }
4359 }
4360 }
4361 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
4362 if is_hovered {
4363 Action::CancelHide(tooltip.clone())
4364 } else {
4365 Action::None
4366 }
4367 }
4368 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
4369 };
4370
4371 match action {
4372 Action::None => {}
4373 Action::Hide => clear_active_tooltip(active_tooltip, window),
4374 Action::ScheduleHide(tooltip) => {
4375 let delayed_hide_task = window.spawn(cx, {
4376 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4377 async move |cx| {
4378 cx.background_executor()
4379 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
4380 .await;
4381 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4382 return;
4383 };
4384 if active_tooltip.borrow_mut().take().is_some() {
4385 cx.update(|window, _cx| window.refresh()).ok();
4386 }
4387 }
4388 });
4389 active_tooltip
4390 .borrow_mut()
4391 .replace(ActiveTooltip::WaitingForHide {
4392 tooltip,
4393 _task: delayed_hide_task,
4394 });
4395 }
4396 Action::CancelHide(tooltip) => {
4397 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
4399 tooltip,
4400 is_hoverable: true,
4401 });
4402 }
4403 }
4404
4405 active_tooltip.borrow().is_some()
4406}
4407
4408#[derive(Default)]
4409pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
4410
4411impl Global for GroupHitboxes {}
4412
4413impl GroupHitboxes {
4414 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
4415 cx.default_global::<Self>()
4416 .0
4417 .get(name)
4418 .and_then(|bounds_stack| bounds_stack.last())
4419 .cloned()
4420 }
4421
4422 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
4423 cx.default_global::<Self>()
4424 .0
4425 .entry(name)
4426 .or_default()
4427 .push(hitbox_id);
4428 }
4429
4430 pub fn pop(name: &SharedString, cx: &mut App) {
4431 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
4432 }
4433}
4434
4435pub struct Stateful<E> {
4437 pub(crate) element: E,
4438}
4439
4440impl<E> Styled for Stateful<E>
4441where
4442 E: Styled,
4443{
4444 fn style(&mut self) -> &mut StyleRefinement {
4445 self.element.style()
4446 }
4447}
4448
4449impl<E> StatefulInteractiveElement for Stateful<E>
4450where
4451 E: Element,
4452 Self: InteractiveElement,
4453{
4454}
4455
4456impl<E> InteractiveElement for Stateful<E>
4457where
4458 E: InteractiveElement,
4459{
4460 fn interactivity(&mut self) -> &mut Interactivity {
4461 self.element.interactivity()
4462 }
4463}
4464
4465impl<E> Element for Stateful<E>
4466where
4467 E: Element,
4468{
4469 type RequestLayoutState = E::RequestLayoutState;
4470 type PrepaintState = E::PrepaintState;
4471
4472 fn id(&self) -> Option<ElementId> {
4473 self.element.id()
4474 }
4475
4476 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4477 self.element.source_location()
4478 }
4479
4480 fn a11y_role(&self) -> Option<accesskit::Role> {
4481 self.element.a11y_role()
4482 }
4483
4484 fn write_a11y_info(&self, node: &mut accesskit::Node) {
4485 self.element.write_a11y_info(node);
4486 }
4487
4488 fn a11y_synthetic_children(
4489 &mut self,
4490 prepaint: &mut Self::PrepaintState,
4491 builder: &mut crate::A11ySubtreeBuilder,
4492 ) {
4493 self.element.a11y_synthetic_children(prepaint, builder);
4494 }
4495
4496 fn request_layout(
4497 &mut self,
4498 id: Option<&GlobalElementId>,
4499 inspector_id: Option<&InspectorElementId>,
4500 window: &mut Window,
4501 cx: &mut App,
4502 ) -> (LayoutId, Self::RequestLayoutState) {
4503 self.element.request_layout(id, inspector_id, window, cx)
4504 }
4505
4506 fn prepaint(
4507 &mut self,
4508 id: Option<&GlobalElementId>,
4509 inspector_id: Option<&InspectorElementId>,
4510 bounds: Bounds<Pixels>,
4511 state: &mut Self::RequestLayoutState,
4512 window: &mut Window,
4513 cx: &mut App,
4514 ) -> E::PrepaintState {
4515 self.element
4516 .prepaint(id, inspector_id, bounds, state, window, cx)
4517 }
4518
4519 fn paint(
4520 &mut self,
4521 id: Option<&GlobalElementId>,
4522 inspector_id: Option<&InspectorElementId>,
4523 bounds: Bounds<Pixels>,
4524 request_layout: &mut Self::RequestLayoutState,
4525 prepaint: &mut Self::PrepaintState,
4526 window: &mut Window,
4527 cx: &mut App,
4528 ) {
4529 self.element.paint(
4530 id,
4531 inspector_id,
4532 bounds,
4533 request_layout,
4534 prepaint,
4535 window,
4536 cx,
4537 );
4538 }
4539}
4540
4541impl<E> ParentElement for Stateful<E>
4542where
4543 E: ParentElement,
4544{
4545 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4546 self.element.extend(elements)
4547 }
4548}
4549
4550#[derive(Clone)]
4553pub struct ScrollAnchor {
4554 handle: ScrollHandle,
4555 last_origin: Rc<RefCell<Point<Pixels>>>,
4556}
4557
4558impl ScrollAnchor {
4559 pub fn for_handle(handle: ScrollHandle) -> Self {
4561 Self {
4562 handle,
4563 last_origin: Default::default(),
4564 }
4565 }
4566 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4568 let this = self.clone();
4569
4570 window.on_next_frame(move |_, _| {
4571 let viewport_bounds = this.handle.bounds();
4572 let self_bounds = *this.last_origin.borrow();
4573 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4574 });
4575 }
4576}
4577
4578#[derive(Default, Debug)]
4579struct ScrollHandleState {
4580 offset: Rc<RefCell<Point<Pixels>>>,
4581 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4582 bounds: Bounds<Pixels>,
4583 max_offset: Point<Pixels>,
4584 child_bounds: Vec<Bounds<Pixels>>,
4585 scroll_to_bottom: bool,
4586 overflow: Point<Overflow>,
4587 active_item: Option<ScrollActiveItem>,
4588}
4589
4590#[derive(Default, Debug, Clone, Copy)]
4591struct ScrollActiveItem {
4592 index: usize,
4593 strategy: ScrollStrategy,
4594}
4595
4596#[derive(Default, Debug, Clone, Copy)]
4597enum ScrollStrategy {
4598 #[default]
4599 FirstVisible,
4600 Top,
4601}
4602
4603#[derive(Clone, Debug)]
4607pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4608
4609impl Default for ScrollHandle {
4610 fn default() -> Self {
4611 Self::new()
4612 }
4613}
4614
4615impl ScrollHandle {
4616 pub fn new() -> Self {
4618 Self(Rc::default())
4619 }
4620
4621 pub fn offset(&self) -> Point<Pixels> {
4623 *self.0.borrow().offset.borrow()
4624 }
4625
4626 pub fn max_offset(&self) -> Point<Pixels> {
4628 self.0.borrow().max_offset
4629 }
4630
4631 pub fn top_item(&self) -> usize {
4633 let state = self.0.borrow();
4634 let top = state.bounds.top() - state.offset.borrow().y;
4635
4636 match state.child_bounds.binary_search_by(|bounds| {
4637 if top < bounds.top() {
4638 Ordering::Greater
4639 } else if top > bounds.bottom() {
4640 Ordering::Less
4641 } else {
4642 Ordering::Equal
4643 }
4644 }) {
4645 Ok(ix) => ix,
4646 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4647 }
4648 }
4649
4650 pub fn bottom_item(&self) -> usize {
4652 let state = self.0.borrow();
4653 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4654
4655 match state.child_bounds.binary_search_by(|bounds| {
4656 if bottom < bounds.top() {
4657 Ordering::Greater
4658 } else if bottom > bounds.bottom() {
4659 Ordering::Less
4660 } else {
4661 Ordering::Equal
4662 }
4663 }) {
4664 Ok(ix) => ix,
4665 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4666 }
4667 }
4668
4669 pub fn bounds(&self) -> Bounds<Pixels> {
4671 self.0.borrow().bounds
4672 }
4673
4674 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4676 self.0.borrow().child_bounds.get(ix).cloned()
4677 }
4678
4679 pub fn scroll_to_item(&self, ix: usize) {
4681 let mut state = self.0.borrow_mut();
4682 state.active_item = Some(ScrollActiveItem {
4683 index: ix,
4684 strategy: ScrollStrategy::default(),
4685 });
4686 }
4687
4688 pub fn scroll_to_top_of_item(&self, ix: usize) {
4691 let mut state = self.0.borrow_mut();
4692 state.active_item = Some(ScrollActiveItem {
4693 index: ix,
4694 strategy: ScrollStrategy::Top,
4695 });
4696 }
4697
4698 fn scroll_to_active_item(&self) {
4702 let mut state = self.0.borrow_mut();
4703
4704 let Some(active_item) = state.active_item else {
4705 return;
4706 };
4707
4708 let active_item = match state.child_bounds.get(active_item.index) {
4709 Some(bounds) => {
4710 let mut scroll_offset = state.offset.borrow_mut();
4711
4712 match active_item.strategy {
4713 ScrollStrategy::FirstVisible => {
4714 if state.overflow.y == Overflow::Scroll {
4715 let child_height = bounds.size.height;
4716 let viewport_height = state.bounds.size.height;
4717 if child_height > viewport_height {
4718 scroll_offset.y = state.bounds.top() - bounds.top();
4719 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4720 scroll_offset.y = state.bounds.top() - bounds.top();
4721 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4722 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4723 }
4724 }
4725 }
4726 ScrollStrategy::Top => {
4727 scroll_offset.y = state.bounds.top() - bounds.top();
4728 }
4729 }
4730
4731 if state.overflow.x == Overflow::Scroll {
4732 let child_width = bounds.size.width;
4733 let viewport_width = state.bounds.size.width;
4734 if child_width > viewport_width {
4735 scroll_offset.x = state.bounds.left() - bounds.left();
4736 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4737 scroll_offset.x = state.bounds.left() - bounds.left();
4738 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4739 scroll_offset.x = state.bounds.right() - bounds.right();
4740 }
4741 }
4742 None
4743 }
4744 None => Some(active_item),
4745 };
4746 state.active_item = active_item;
4747 }
4748
4749 pub fn scroll_to_bottom(&self) {
4751 let mut state = self.0.borrow_mut();
4752 state.scroll_to_bottom = true;
4753 }
4754
4755 pub fn set_offset(&self, position: Point<Pixels>) {
4759 let state = self.0.borrow();
4760 *state.offset.borrow_mut() = position;
4761 }
4762
4763 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4765 let ix = self.top_item();
4766 let state = self.0.borrow();
4767
4768 if let Some(child_bounds) = state.child_bounds.get(ix) {
4769 (
4770 ix,
4771 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4772 )
4773 } else {
4774 (ix, px(0.))
4775 }
4776 }
4777
4778 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4780 let ix = self.bottom_item();
4781 let state = self.0.borrow();
4782
4783 if let Some(child_bounds) = state.child_bounds.get(ix) {
4784 (
4785 ix,
4786 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4787 )
4788 } else {
4789 (ix, px(0.))
4790 }
4791 }
4792
4793 pub fn children_count(&self) -> usize {
4795 self.0.borrow().child_bounds.len()
4796 }
4797}
4798
4799#[cfg(test)]
4800mod tests {
4801 use super::*;
4802 use crate::{
4803 AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, IntoElement,
4804 Keystroke, MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas,
4805 util::FluentBuilder as _,
4806 };
4807 use std::{cell::Cell, rc::Weak};
4808
4809 struct GroupHoverTestView {
4810 render_count: Rc<Cell<usize>>,
4811 anonymous_paint_count: Rc<Cell<usize>>,
4812 stateful_width: Rc<Cell<Pixels>>,
4813 }
4814
4815 impl Render for GroupHoverTestView {
4816 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4817 self.render_count.set(self.render_count.get() + 1);
4818 let anonymous_paint_count = self.anonymous_paint_count.clone();
4819 let stateful_width = self.stateful_width.clone();
4820 div().size_full().child(
4821 div()
4822 .ml(px(20.))
4823 .mt(px(20.))
4824 .size(px(50.))
4825 .relative()
4826 .group("hover-group")
4827 .child(
4828 div()
4829 .absolute()
4830 .size_full()
4831 .invisible()
4832 .group_hover("hover-group", |style| style.visible())
4833 .child(canvas(
4834 |_, _, _| {},
4835 move |_, _, _, _| {
4836 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4837 },
4838 )),
4839 )
4840 .child(
4841 div()
4842 .id("stateful-group-hover-target")
4843 .absolute()
4844 .top_0()
4845 .left_0()
4846 .size(px(10.))
4847 .group_hover("hover-group", |style| style.size(px(20.)))
4848 .child(canvas(
4849 move |bounds, _, _| stateful_width.set(bounds.size.width),
4850 |_, _, _, _| {},
4851 )),
4852 ),
4853 )
4854 }
4855 }
4856
4857 #[gpui::test]
4858 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4859 let render_count = Rc::new(Cell::new(0));
4860 let anonymous_paint_count = Rc::new(Cell::new(0));
4861 let stateful_width = Rc::new(Cell::new(px(0.)));
4862 let window = cx.add_window({
4863 let render_count = render_count.clone();
4864 let anonymous_paint_count = anonymous_paint_count.clone();
4865 let stateful_width = stateful_width.clone();
4866 move |_, _| GroupHoverTestView {
4867 render_count,
4868 anonymous_paint_count,
4869 stateful_width,
4870 }
4871 });
4872 let window = AnyWindowHandle::from(window);
4873
4874 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4875 .unwrap();
4876 assert_eq!(anonymous_paint_count.get(), 0);
4877 assert_eq!(stateful_width.get(), px(10.));
4878
4879 let move_mouse = |cx: &mut TestAppContext, position| {
4880 cx.update_window(window, |_, window, cx| {
4881 window.simulate_mouse_move(position, cx)
4882 })
4883 .unwrap();
4884 };
4885
4886 let initial_render_count = render_count.get();
4887 move_mouse(cx, point(px(25.), px(25.)));
4888 assert_eq!(render_count.get(), initial_render_count + 1);
4889 assert_eq!(anonymous_paint_count.get(), 1);
4890 assert_eq!(stateful_width.get(), px(20.));
4891
4892 move_mouse(cx, point(px(30.), px(30.)));
4893 assert_eq!(render_count.get(), initial_render_count + 1);
4894 assert_eq!(anonymous_paint_count.get(), 1);
4895 assert_eq!(stateful_width.get(), px(20.));
4896
4897 move_mouse(cx, point(px(5.), px(5.)));
4898 assert_eq!(render_count.get(), initial_render_count + 2);
4899 assert_eq!(anonymous_paint_count.get(), 1);
4900 assert_eq!(stateful_width.get(), px(10.));
4901
4902 move_mouse(cx, point(px(10.), px(10.)));
4903 assert_eq!(render_count.get(), initial_render_count + 2);
4904 assert_eq!(anonymous_paint_count.get(), 1);
4905 assert_eq!(stateful_width.get(), px(10.));
4906 }
4907
4908 struct GroupHoverDisplayTestView {
4911 group_left: Pixels,
4912 frames: Rc<RefCell<Vec<(bool, Option<Pixels>, bool)>>>,
4915 }
4916
4917 impl Render for GroupHoverDisplayTestView {
4918 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4919 self.frames.borrow_mut().push((true, None, false));
4920 let prepainted = self.frames.clone();
4921 let painted = self.frames.clone();
4922 div().relative().size_full().child(
4923 div()
4924 .id("display-group")
4925 .absolute()
4926 .left(self.group_left)
4927 .top_0()
4928 .size(px(20.))
4929 .group("display-group")
4930 .child(
4931 div()
4932 .id("display-target")
4933 .hidden()
4934 .w(px(12.))
4935 .h(px(8.))
4936 .group_hover("display-group", |style| style.flex())
4937 .child(
4938 canvas(
4939 move |bounds, _, _| {
4940 if let Some(frame) = prepainted.borrow_mut().last_mut() {
4941 frame.1 = Some(bounds.size.width);
4942 }
4943 },
4944 move |_, _, _, _| {
4945 if let Some(frame) = painted.borrow_mut().last_mut() {
4946 frame.2 = true;
4947 }
4948 },
4949 )
4950 .size_full(),
4951 ),
4952 ),
4953 )
4954 }
4955 }
4956
4957 #[gpui::test]
4963 fn group_hover_that_shows_a_hidden_box_under_a_stationary_pointer(cx: &mut TestAppContext) {
4964 let frames = Rc::new(RefCell::new(Vec::new()));
4965 let window = cx.add_window({
4966 let frames = frames.clone();
4967 move |_, _| GroupHoverDisplayTestView {
4968 group_left: px(40.),
4969 frames,
4970 }
4971 });
4972 let any_window = AnyWindowHandle::from(window);
4973 let frames_since = |mark: usize| frames.borrow()[mark..].to_vec();
4976
4977 cx.update_window(any_window, |_, window, cx| {
4978 window.draw(cx).clear(cx);
4979 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4980 })
4981 .unwrap();
4982 assert!(
4983 frames
4984 .borrow()
4985 .iter()
4986 .all(|frame| frame.1.is_none() && !frame.2),
4987 "the group is not under the pointer"
4988 );
4989
4990 let mark = frames.borrow().len();
4993 window
4994 .update(cx, |view, _, cx| {
4995 view.group_left = px(0.);
4996 cx.notify();
4997 })
4998 .unwrap();
4999 assert_eq!(
5000 frames_since(mark),
5001 [
5002 (true, None, false),
5005 (true, Some(px(12.)), true),
5008 ]
5009 );
5010
5011 let mark = frames.borrow().len();
5015 window
5016 .update(cx, |view, _, cx| {
5017 view.group_left = px(40.);
5018 cx.notify();
5019 })
5020 .unwrap();
5021 assert_eq!(
5022 frames_since(mark),
5023 [(true, Some(px(12.)), false), (true, None, false)]
5024 );
5025 }
5026
5027 struct HoverListenerLayoutTestView {
5028 target_left: Pixels,
5029 hover_transitions: Rc<RefCell<Vec<bool>>>,
5030 }
5031
5032 impl Render for HoverListenerLayoutTestView {
5033 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5034 let hover_transitions = self.hover_transitions.clone();
5035 div().relative().size_full().child(
5036 div()
5037 .id("hover-target")
5038 .absolute()
5039 .left(self.target_left)
5040 .top_0()
5041 .size(px(20.))
5042 .on_click(|_, _, _| {})
5043 .on_hover(move |is_hovered, _, _| {
5044 hover_transitions.borrow_mut().push(*is_hovered);
5045 }),
5046 )
5047 }
5048 }
5049
5050 #[gpui::test]
5051 fn default_hover_listener_updates_when_layout_changes_under_stationary_mouse(
5052 cx: &mut TestAppContext,
5053 ) {
5054 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
5055 let window = cx.add_window({
5056 let hover_transitions = hover_transitions.clone();
5057 move |_, _| HoverListenerLayoutTestView {
5058 target_left: px(40.),
5059 hover_transitions,
5060 }
5061 });
5062 let any_window = AnyWindowHandle::from(window);
5063
5064 cx.update_window(any_window, |_, window, cx| {
5065 window.draw(cx).clear(cx);
5066 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
5067 })
5068 .unwrap();
5069 assert!(hover_transitions.borrow().is_empty());
5070
5071 window
5072 .update(cx, |view, _, cx| {
5073 view.target_left = px(0.);
5074 cx.notify();
5075 })
5076 .unwrap();
5077 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5078 .unwrap();
5079 assert_eq!(*hover_transitions.borrow(), [true]);
5080
5081 window
5082 .update(cx, |view, _, cx| {
5083 view.target_left = px(40.);
5084 cx.notify();
5085 })
5086 .unwrap();
5087 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5088 .unwrap();
5089 assert_eq!(*hover_transitions.borrow(), [true, false]);
5090 }
5091
5092 #[gpui::test]
5093 fn default_hover_listener_ends_after_key_press(cx: &mut TestAppContext) {
5094 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
5095 let window = cx.add_window({
5096 let hover_transitions = hover_transitions.clone();
5097 move |_, _| HoverListenerLayoutTestView {
5098 target_left: px(0.),
5099 hover_transitions,
5100 }
5101 });
5102 let any_window = AnyWindowHandle::from(window);
5103
5104 cx.update_window(any_window, |_, window, cx| {
5105 window.draw(cx).clear(cx);
5106 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
5107 })
5108 .unwrap();
5109 assert_eq!(*hover_transitions.borrow(), [true]);
5110
5111 key_down(cx, any_window, "a");
5112 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5113 .unwrap();
5114 assert_eq!(*hover_transitions.borrow(), [true, false]);
5115 }
5116
5117 struct HoverListenerModeLayoutTestView {
5118 target_left: Pixels,
5119 hover_transitions: Rc<RefCell<Vec<bool>>>,
5120 }
5121
5122 impl Render for HoverListenerModeLayoutTestView {
5123 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5124 let hover_transitions = self.hover_transitions.clone();
5125 div().relative().size_full().child(
5126 div()
5127 .id("hover-target")
5128 .absolute()
5129 .left(self.target_left)
5130 .top_0()
5131 .size(px(20.))
5132 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
5133 .on_hover(move |is_hovered, _, _| {
5134 hover_transitions.borrow_mut().push(*is_hovered);
5135 }),
5136 )
5137 }
5138 }
5139
5140 #[gpui::test]
5141 fn input_modality_independent_hover_listener_updates_after_key_press(cx: &mut TestAppContext) {
5142 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
5143 let window = cx.add_window({
5144 let hover_transitions = hover_transitions.clone();
5145 move |_, _| HoverListenerModeLayoutTestView {
5146 target_left: px(40.),
5147 hover_transitions,
5148 }
5149 });
5150 let any_window = AnyWindowHandle::from(window);
5151 let pointer_position = point(px(10.), px(10.));
5152
5153 cx.update_window(any_window, |_, window, cx| {
5154 window.draw(cx).clear(cx);
5155 window.simulate_mouse_move(pointer_position, cx);
5156 })
5157 .unwrap();
5158 assert!(hover_transitions.borrow().is_empty());
5159
5160 key_down(cx, any_window, "a");
5161 window
5162 .update(cx, |view, _, cx| {
5163 view.target_left = px(0.);
5164 cx.notify();
5165 })
5166 .unwrap();
5167 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5168 .unwrap();
5169 assert_eq!(*hover_transitions.borrow(), [true]);
5170
5171 key_down(cx, any_window, "b");
5172 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5173 .unwrap();
5174 assert_eq!(*hover_transitions.borrow(), [true]);
5175
5176 cx.update_window(any_window, |_, window, cx| {
5177 window.simulate_mouse_move(point(px(30.), px(10.)), cx);
5178 })
5179 .unwrap();
5180 assert_eq!(*hover_transitions.borrow(), [true, false]);
5181
5182 cx.update_window(any_window, |_, window, cx| {
5183 window.simulate_mouse_move(pointer_position, cx);
5184 window.dispatch_event(
5185 MouseExitEvent {
5186 position: pointer_position,
5187 ..Default::default()
5188 }
5189 .to_platform_input(),
5190 cx,
5191 );
5192 })
5193 .unwrap();
5194 assert_eq!(*hover_transitions.borrow(), [true, false, true, false]);
5195 }
5196
5197 #[gpui::test]
5198 fn default_hover_listener_remains_hovered_during_stationary_mouse_press(
5199 cx: &mut TestAppContext,
5200 ) {
5201 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
5202 let window = cx.add_window({
5203 let hover_transitions = hover_transitions.clone();
5204 move |_, _| HoverListenerLayoutTestView {
5205 target_left: px(0.),
5206 hover_transitions,
5207 }
5208 });
5209 let any_window = AnyWindowHandle::from(window);
5210 let mouse_position = point(px(10.), px(10.));
5211
5212 cx.update_window(any_window, |_, window, cx| {
5213 window.draw(cx).clear(cx);
5214 window.simulate_mouse_move(mouse_position, cx);
5215 })
5216 .unwrap();
5217 assert_eq!(*hover_transitions.borrow(), [true]);
5218
5219 cx.update_window(any_window, |_, window, cx| {
5220 window.dispatch_event(
5221 MouseDownEvent {
5222 position: mouse_position,
5223 button: MouseButton::Left,
5224 modifiers: Default::default(),
5225 click_count: 1,
5226 first_mouse: false,
5227 }
5228 .to_platform_input(),
5229 cx,
5230 );
5231 window.draw(cx).clear(cx);
5232 })
5233 .unwrap();
5234 assert_eq!(*hover_transitions.borrow(), [true]);
5235
5236 cx.update_window(any_window, |_, window, cx| {
5237 window.dispatch_event(
5238 MouseUpEvent {
5239 position: mouse_position,
5240 button: MouseButton::Left,
5241 modifiers: Default::default(),
5242 click_count: 1,
5243 }
5244 .to_platform_input(),
5245 cx,
5246 );
5247 window.draw(cx).clear(cx);
5248 })
5249 .unwrap();
5250 assert_eq!(*hover_transitions.borrow(), [true]);
5251 }
5252
5253 struct TestTooltipView;
5254
5255 impl Render for TestTooltipView {
5256 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5257 div().w(px(20.)).h(px(20.)).child("tooltip")
5258 }
5259 }
5260
5261 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
5262
5263 struct TooltipCaptureElement {
5264 child: AnyElement,
5265 captured_active_tooltip: CapturedActiveTooltip,
5266 }
5267
5268 impl Element for TooltipCaptureElement {
5269 type RequestLayoutState = ();
5270 type PrepaintState = ();
5271
5272 fn id(&self) -> Option<ElementId> {
5273 None
5274 }
5275
5276 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
5277 None
5278 }
5279
5280 fn request_layout(
5281 &mut self,
5282 _id: Option<&GlobalElementId>,
5283 _inspector_id: Option<&InspectorElementId>,
5284 window: &mut Window,
5285 cx: &mut App,
5286 ) -> (LayoutId, Self::RequestLayoutState) {
5287 (self.child.request_layout(window, cx), ())
5288 }
5289
5290 fn prepaint(
5291 &mut self,
5292 _id: Option<&GlobalElementId>,
5293 _inspector_id: Option<&InspectorElementId>,
5294 _bounds: Bounds<Pixels>,
5295 _request_layout: &mut Self::RequestLayoutState,
5296 window: &mut Window,
5297 cx: &mut App,
5298 ) -> Self::PrepaintState {
5299 self.child.prepaint(window, cx);
5300 }
5301
5302 fn paint(
5303 &mut self,
5304 _id: Option<&GlobalElementId>,
5305 _inspector_id: Option<&InspectorElementId>,
5306 _bounds: Bounds<Pixels>,
5307 _request_layout: &mut Self::RequestLayoutState,
5308 _prepaint: &mut Self::PrepaintState,
5309 window: &mut Window,
5310 cx: &mut App,
5311 ) {
5312 self.child.paint(window, cx);
5313 window.with_global_id("target".into(), |global_id, window| {
5314 window.with_element_state::<InteractiveElementState, _>(
5315 global_id,
5316 |state, _window| {
5317 let state = state.unwrap();
5318 *self.captured_active_tooltip.borrow_mut() =
5319 state.active_tooltip.as_ref().map(Rc::downgrade);
5320 ((), state)
5321 },
5322 )
5323 });
5324 }
5325 }
5326
5327 struct TooltipOwner {
5328 captured_active_tooltip: CapturedActiveTooltip,
5329 show_delay_override: Option<Duration>,
5330 }
5331
5332 impl Render for TooltipOwner {
5333 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5334 TooltipCaptureElement {
5335 child: div()
5336 .size_full()
5337 .child(
5338 div()
5339 .id("target")
5340 .w(px(50.))
5341 .h(px(50.))
5342 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
5343 .when_some(self.show_delay_override, |this, delay| {
5344 this.tooltip_show_delay(delay)
5345 }),
5346 )
5347 .into_any_element(),
5348 captured_active_tooltip: self.captured_active_tooltip.clone(),
5349 }
5350 }
5351 }
5352
5353 #[test]
5354 fn scroll_handle_aligns_wide_children_to_left_edge() {
5355 let handle = ScrollHandle::new();
5356 {
5357 let mut state = handle.0.borrow_mut();
5358 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
5359 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
5360 state.overflow.x = Overflow::Scroll;
5361 state.active_item = Some(ScrollActiveItem {
5362 index: 0,
5363 strategy: ScrollStrategy::default(),
5364 });
5365 }
5366
5367 handle.scroll_to_active_item();
5368
5369 assert_eq!(handle.offset().x, px(-25.));
5370 }
5371
5372 #[test]
5373 fn scroll_handle_aligns_tall_children_to_top_edge() {
5374 let handle = ScrollHandle::new();
5375 {
5376 let mut state = handle.0.borrow_mut();
5377 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
5378 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
5379 state.overflow.y = Overflow::Scroll;
5380 state.active_item = Some(ScrollActiveItem {
5381 index: 0,
5382 strategy: ScrollStrategy::default(),
5383 });
5384 }
5385
5386 handle.scroll_to_active_item();
5387
5388 assert_eq!(handle.offset().y, px(-25.));
5389 }
5390
5391 #[test]
5392 fn long_press_shows_tooltip_until_touch_ends() {
5393 let (mut test_app, any_window, captured_active_tooltip) = create_tooltip_owner_test(None);
5394 let active_tooltip = captured_active_tooltip
5395 .borrow()
5396 .clone()
5397 .unwrap()
5398 .upgrade()
5399 .unwrap();
5400 let touch_id = TouchId(1);
5401 let touch_position = point(px(49.), px(10.));
5402
5403 test_app
5404 .update_window(any_window, |_, window, cx| {
5405 window.dispatch_event(
5406 TouchEvent {
5407 id: touch_id,
5408 phase: TouchPhase::Started,
5409 position: touch_position,
5410 predicted_position: None,
5411 force: None,
5412 }
5413 .to_platform_input(),
5414 cx,
5415 );
5416 })
5417 .unwrap();
5418 test_app
5419 .dispatcher
5420 .advance_clock(GestureTuning::default().long_press_duration + Duration::from_millis(1));
5421 test_app.run_until_parked();
5422
5423 assert!(matches!(
5424 active_tooltip.borrow().as_ref(),
5425 Some(ActiveTooltip::Visible { .. })
5426 ));
5427
5428 let moved_position = point(px(55.), px(10.));
5429 test_app
5430 .update_window(any_window, |_, window, cx| {
5431 window.dispatch_event(
5432 TouchEvent {
5433 id: touch_id,
5434 phase: TouchPhase::Moved,
5435 position: moved_position,
5436 predicted_position: None,
5437 force: None,
5438 }
5439 .to_platform_input(),
5440 cx,
5441 );
5442 window.draw(cx).clear(cx);
5443 })
5444 .unwrap();
5445 assert!(matches!(
5446 active_tooltip.borrow().as_ref(),
5447 Some(ActiveTooltip::Visible { .. })
5448 ));
5449
5450 test_app
5451 .update_window(any_window, |_, window, cx| {
5452 window.dispatch_event(
5453 TouchEvent {
5454 id: touch_id,
5455 phase: TouchPhase::Ended,
5456 position: moved_position,
5457 predicted_position: None,
5458 force: None,
5459 }
5460 .to_platform_input(),
5461 cx,
5462 );
5463 })
5464 .unwrap();
5465
5466 assert!(active_tooltip.borrow().is_none());
5467 }
5468
5469 fn setup_tooltip_owner_test(
5470 show_delay_override: Option<Duration>,
5471 ) -> (
5472 TestAppContext,
5473 crate::AnyWindowHandle,
5474 CapturedActiveTooltip,
5475 ) {
5476 let (mut test_app, any_window, captured_active_tooltip) =
5477 create_tooltip_owner_test(show_delay_override);
5478
5479 test_app
5480 .update_window(any_window, |_, window, cx| {
5481 window.dispatch_event(
5482 MouseMoveEvent {
5483 position: point(px(10.), px(10.)),
5484 modifiers: Default::default(),
5485 pressed_button: None,
5486 }
5487 .to_platform_input(),
5488 cx,
5489 );
5490 })
5491 .unwrap();
5492
5493 test_app
5494 .update_window(any_window, |_, window, cx| {
5495 window.draw(cx).clear(cx);
5496 })
5497 .unwrap();
5498
5499 (test_app, any_window, captured_active_tooltip)
5500 }
5501
5502 fn create_tooltip_owner_test(
5503 show_delay_override: Option<Duration>,
5504 ) -> (
5505 TestAppContext,
5506 crate::AnyWindowHandle,
5507 CapturedActiveTooltip,
5508 ) {
5509 let mut test_app = TestAppContext::single();
5510 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
5511 let window = test_app.add_window({
5512 let captured_active_tooltip = captured_active_tooltip.clone();
5513 move |_, _| TooltipOwner {
5514 captured_active_tooltip,
5515 show_delay_override,
5516 }
5517 });
5518 let any_window = window.into();
5519
5520 test_app
5521 .update_window(any_window, |_, window, cx| {
5522 window.draw(cx).clear(cx);
5523 })
5524 .unwrap();
5525
5526 (test_app, any_window, captured_active_tooltip)
5527 }
5528
5529 #[test]
5530 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
5531 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5532
5533 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5534 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5535 assert!(matches!(
5536 active_tooltip.borrow().as_ref(),
5537 Some(ActiveTooltip::WaitingForShow { .. })
5538 ));
5539
5540 test_app
5541 .update_window(any_window, |_, window, _| {
5542 window.remove_window();
5543 })
5544 .unwrap();
5545 test_app.run_until_parked();
5546 drop(active_tooltip);
5547
5548 assert!(weak_active_tooltip.upgrade().is_none());
5549 }
5550
5551 #[test]
5552 fn tooltip_respects_custom_show_delay() {
5553 let extra_delay = Duration::from_secs(1);
5554 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
5555 let (test_app, _any_window, captured_active_tooltip) =
5556 setup_tooltip_owner_test(Some(show_delay_override));
5557
5558 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5559 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5560
5561 test_app
5562 .dispatcher
5563 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5564 test_app.run_until_parked();
5565
5566 assert!(matches!(
5567 active_tooltip.borrow().as_ref(),
5568 Some(ActiveTooltip::WaitingForShow { .. })
5569 ));
5570
5571 test_app.dispatcher.advance_clock(extra_delay);
5572 test_app.run_until_parked();
5573
5574 assert!(matches!(
5575 active_tooltip.borrow().as_ref(),
5576 Some(ActiveTooltip::Visible { .. })
5577 ));
5578 }
5579
5580 #[test]
5581 fn tooltip_is_released_when_its_owner_disappears() {
5582 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5583
5584 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5585 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5586
5587 test_app
5588 .dispatcher
5589 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5590 test_app.run_until_parked();
5591
5592 assert!(matches!(
5593 active_tooltip.borrow().as_ref(),
5594 Some(ActiveTooltip::Visible { .. })
5595 ));
5596
5597 test_app
5598 .update_window(any_window, |_, window, _| {
5599 window.remove_window();
5600 })
5601 .unwrap();
5602 test_app.run_until_parked();
5603 drop(active_tooltip);
5604
5605 assert!(weak_active_tooltip.upgrade().is_none());
5606 }
5607
5608 #[test]
5609 fn tooltip_hides_after_mouse_leaves_origin() {
5610 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5611
5612 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5613 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5614
5615 test_app
5616 .dispatcher
5617 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5618 test_app.run_until_parked();
5619
5620 assert!(matches!(
5621 active_tooltip.borrow().as_ref(),
5622 Some(ActiveTooltip::Visible { .. })
5623 ));
5624
5625 test_app
5626 .update_window(any_window, |_, window, cx| {
5627 window.dispatch_event(
5628 MouseMoveEvent {
5629 position: point(px(75.), px(75.)),
5630 modifiers: Default::default(),
5631 pressed_button: None,
5632 }
5633 .to_platform_input(),
5634 cx,
5635 );
5636 })
5637 .unwrap();
5638
5639 assert!(active_tooltip.borrow().is_none());
5640 }
5641
5642 struct MouseDownOutOwner {
5643 mouse_down_out_count: Rc<RefCell<usize>>,
5644 }
5645
5646 impl Render for MouseDownOutOwner {
5647 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5648 let mouse_down_out_count = self.mouse_down_out_count.clone();
5649 div()
5650 .size_full()
5651 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
5652 move |_, _, _| {
5653 *mouse_down_out_count.borrow_mut() += 1;
5654 },
5655 ))
5656 }
5657 }
5658
5659 #[test]
5660 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
5661 let mut test_app = TestAppContext::single();
5662 let mouse_down_out_count = Rc::new(RefCell::new(0));
5663 let window = test_app.add_window({
5664 let mouse_down_out_count = mouse_down_out_count.clone();
5665 move |_, _| MouseDownOutOwner {
5666 mouse_down_out_count,
5667 }
5668 });
5669 let any_window: AnyWindowHandle = window.into();
5670
5671 fn dispatch_mouse_down_outside_target(
5672 test_app: &mut TestAppContext,
5673 any_window: AnyWindowHandle,
5674 ) {
5675 test_app
5676 .update_window(any_window, |_, window, cx| {
5677 window.dispatch_event(
5678 MouseDownEvent {
5679 position: point(px(75.), px(75.)),
5680 button: MouseButton::Left,
5681 modifiers: Default::default(),
5682 click_count: 1,
5683 first_mouse: false,
5684 }
5685 .to_platform_input(),
5686 cx,
5687 );
5688 })
5689 .unwrap();
5690 }
5691
5692 test_app
5693 .update_window(any_window, |_, window, cx| {
5694 window.draw(cx).clear(cx);
5695 })
5696 .unwrap();
5697
5698 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5699 assert_eq!(
5700 *mouse_down_out_count.borrow(),
5701 1,
5702 "mouse down outside the element should fire mouse-down-out listeners"
5703 );
5704
5705 test_app
5706 .update_window(any_window, |_, window, cx| {
5707 cx.set_prompt_builder(crate::fallback_prompt_renderer);
5708 let _receiver =
5709 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
5710 assert!(window.has_active_prompt());
5711 window.draw(cx).clear(cx);
5712 })
5713 .unwrap();
5714
5715 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5716 assert_eq!(
5717 *mouse_down_out_count.borrow(),
5718 1,
5719 "mouse down over an active prompt should not fire mouse-down-out listeners"
5720 );
5721 }
5722
5723 #[test]
5724 fn touch_tap_out_fires_once_after_release() {
5725 let mut test_app = TestAppContext::single();
5726 let mouse_down_out_count = Rc::new(RefCell::new(0));
5727 let window = test_app.add_window({
5728 let mouse_down_out_count = mouse_down_out_count.clone();
5729 move |_, _| MouseDownOutOwner {
5730 mouse_down_out_count,
5731 }
5732 });
5733 let any_window: AnyWindowHandle = window.into();
5734
5735 test_app
5736 .update_window(any_window, |_, window, cx| {
5737 window.draw(cx).clear(cx);
5738 let started = TouchEvent {
5739 id: TouchId(1),
5740 phase: TouchPhase::Started,
5741 position: point(px(75.), px(75.)),
5742 force: None,
5743 predicted_position: None,
5744 };
5745 window.dispatch_event(started.clone().to_platform_input(), cx);
5746 assert_eq!(*mouse_down_out_count.borrow(), 0);
5747 window.dispatch_event(
5748 TouchEvent {
5749 phase: TouchPhase::Ended,
5750 ..started
5751 }
5752 .to_platform_input(),
5753 cx,
5754 );
5755 })
5756 .unwrap();
5757
5758 assert_eq!(
5759 *mouse_down_out_count.borrow(),
5760 1,
5761 "a touch tap outside the element should use mouse-down-out listeners"
5762 );
5763 }
5764
5765 #[crate::test]
5766 fn touch_pan_and_cancel_do_not_fire_mouse_down_out(cx: &mut TestAppContext) {
5767 let mouse_down_out_count = Rc::new(RefCell::new(0));
5768 let window = cx.add_window({
5769 let mouse_down_out_count = mouse_down_out_count.clone();
5770 move |_, _| MouseDownOutOwner {
5771 mouse_down_out_count,
5772 }
5773 });
5774 cx.update_window(window.into(), |_, window, cx| {
5775 window.draw(cx).clear(cx);
5776 for (id, samples) in [
5777 (
5778 TouchId(1),
5779 [
5780 (TouchPhase::Started, 100.),
5781 (TouchPhase::Moved, 75.),
5782 (TouchPhase::Ended, 75.),
5783 ],
5784 ),
5785 (
5786 TouchId(2),
5787 [
5788 (TouchPhase::Started, 100.),
5789 (TouchPhase::Moved, 100.),
5790 (TouchPhase::Cancelled, 100.),
5791 ],
5792 ),
5793 ] {
5794 for (phase, vertical_position) in samples {
5795 window.dispatch_event(
5796 TouchEvent {
5797 id,
5798 phase,
5799 position: point(px(75.), px(vertical_position)),
5800 predicted_position: None,
5801 force: None,
5802 }
5803 .to_platform_input(),
5804 cx,
5805 );
5806 }
5807 }
5808 })
5809 .unwrap();
5810 assert_eq!(*mouse_down_out_count.borrow(), 0);
5811 }
5812
5813 #[test]
5814 fn test_accessibility_id_builder_writes_author_id() {
5815 let mut element = div()
5816 .id("buffer-font-size")
5817 .accessibility_id("settings.buffer-font-size");
5818 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5819
5820 element.interactivity().write_a11y_info(&mut node);
5821
5822 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5823 }
5824
5825 #[test]
5826 fn test_write_a11y_info_string_and_numeric_properties() {
5827 let mut interactivity = Interactivity::default();
5828 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
5829 interactivity.aria.label = Some("Buffer Font Size".into());
5830 interactivity.aria.value = Some("15".into());
5831 interactivity.aria.placeholder = Some("Search".into());
5832 interactivity.aria.numeric_value = Some(15.0);
5833 interactivity.aria.min_numeric_value = Some(6.0);
5834 interactivity.aria.max_numeric_value = Some(72.0);
5835 interactivity.aria.numeric_value_step = Some(1.0);
5836
5837 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5838 interactivity.write_a11y_info(&mut node);
5839
5840 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5841 assert_eq!(node.label(), Some("Buffer Font Size"));
5842 assert_eq!(node.value(), Some("15"));
5843 assert_eq!(node.placeholder(), Some("Search"));
5844 assert_eq!(node.numeric_value(), Some(15.0));
5845 assert_eq!(node.min_numeric_value(), Some(6.0));
5846 assert_eq!(node.max_numeric_value(), Some(72.0));
5847 assert_eq!(node.numeric_value_step(), Some(1.0));
5848 }
5849
5850 struct KeyboardActivationTest {
5853 focus_a: FocusHandle,
5854 focus_b: FocusHandle,
5855 clicks: Rc<RefCell<Vec<&'static str>>>,
5856 }
5857
5858 impl Render for KeyboardActivationTest {
5859 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5860 let clicks_a = self.clicks.clone();
5861 let clicks_b = self.clicks.clone();
5862 div()
5863 .size_full()
5864 .child(
5865 div()
5866 .id("a")
5867 .w(px(50.))
5868 .h(px(50.))
5869 .track_focus(&self.focus_a)
5870 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
5871 )
5872 .child(
5873 div()
5874 .id("b")
5875 .w(px(50.))
5876 .h(px(50.))
5877 .track_focus(&self.focus_b)
5878 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
5879 )
5880 }
5881 }
5882
5883 fn setup_keyboard_activation_test() -> (
5884 TestAppContext,
5885 AnyWindowHandle,
5886 Rc<RefCell<Vec<&'static str>>>,
5887 FocusHandle,
5888 FocusHandle,
5889 ) {
5890 let mut cx = TestAppContext::single();
5891 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
5892 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
5893 let window = cx.add_window({
5894 let focus_a = focus_a.clone();
5895 let focus_b = focus_b.clone();
5896 let clicks = clicks.clone();
5897 move |_, _| KeyboardActivationTest {
5898 focus_a,
5899 focus_b,
5900 clicks,
5901 }
5902 });
5903 (cx, window.into(), clicks, focus_a, focus_b)
5904 }
5905
5906 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
5909 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
5910 .unwrap();
5911 cx.run_until_parked();
5912 cx.update_window(window, |_, window, cx| {
5913 window.draw(cx).clear(cx);
5914 })
5915 .unwrap();
5916 }
5917
5918 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5919 let os = cx.read(|cx| cx.platform_info().os);
5920 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5921 cx.update_window(window, |_, window, cx| {
5922 window.dispatch_event(
5923 KeyDownEvent {
5924 keystroke,
5925 is_held: false,
5926 prefer_character_input: false,
5927 }
5928 .to_platform_input(),
5929 cx,
5930 );
5931 })
5932 .unwrap();
5933 }
5934
5935 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5936 let os = cx.read(|cx| cx.platform_info().os);
5937 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5938 cx.update_window(window, |_, window, cx| {
5939 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
5940 })
5941 .unwrap();
5942 }
5943
5944 #[test]
5946 fn keyboard_activation_fires_click_on_same_element() {
5947 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5948
5949 focus_and_draw(&mut cx, window, &focus_a);
5950 key_down(&mut cx, window, "enter");
5951 key_up(&mut cx, window, "enter");
5952
5953 assert_eq!(*clicks.borrow(), vec!["a"]);
5954 }
5955
5956 #[test]
5961 fn keyboard_activation_does_not_leak_across_focus_change() {
5962 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5963
5964 focus_and_draw(&mut cx, window, &focus_a);
5966 key_down(&mut cx, window, "enter");
5967
5968 focus_and_draw(&mut cx, window, &focus_b);
5970 key_up(&mut cx, window, "enter");
5971
5972 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5975 }
5976
5977 #[test]
5982 fn keyboard_activation_does_not_leak_when_focus_returns() {
5983 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5984
5985 focus_and_draw(&mut cx, window, &focus_a);
5987 key_down(&mut cx, window, "enter");
5988
5989 focus_and_draw(&mut cx, window, &focus_b);
5992 focus_and_draw(&mut cx, window, &focus_a);
5993 key_up(&mut cx, window, "enter");
5994
5995 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5997 }
5998
5999 #[test]
6004 fn keyboard_activation_cleared_by_intervening_key_release() {
6005 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
6006
6007 focus_and_draw(&mut cx, window, &focus_a);
6008 key_down(&mut cx, window, "escape");
6009 key_down(&mut cx, window, "space");
6010 key_up(&mut cx, window, "escape");
6011 key_up(&mut cx, window, "space");
6012
6013 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
6014 }
6015
6016 #[test]
6020 fn keyboard_activation_does_not_distinguish_space_and_enter() {
6021 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
6022
6023 focus_and_draw(&mut cx, window, &focus_a);
6024 key_down(&mut cx, window, "space");
6025 key_up(&mut cx, window, "enter");
6026
6027 assert_eq!(*clicks.borrow(), vec!["a"]);
6028 }
6029
6030 #[test]
6033 fn keyboard_activation_cleared_by_intervening_keydown() {
6034 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
6035
6036 focus_and_draw(&mut cx, window, &focus_a);
6037 key_down(&mut cx, window, "enter");
6038 key_down(&mut cx, window, "a");
6039 key_up(&mut cx, window, "enter");
6040
6041 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
6042 }
6043
6044 #[test]
6047 fn keyboard_activation_ignores_modified_keys() {
6048 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
6049
6050 focus_and_draw(&mut cx, window, &focus_a);
6051 key_down(&mut cx, window, "cmd-enter");
6052 key_up(&mut cx, window, "cmd-enter");
6053
6054 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
6055 }
6056
6057 struct TabGroupFocus {
6061 group_a: FocusHandle,
6062 item_a: FocusHandle,
6063 group_b: FocusHandle,
6064 item_b: FocusHandle,
6065 }
6066
6067 impl Render for TabGroupFocus {
6068 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6069 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
6070 div()
6071 .track_focus(container)
6072 .tab_group()
6073 .child(div().track_focus(item))
6074 }
6075 div()
6076 .child(group(&self.group_a, &self.item_a))
6077 .child(group(&self.group_b, &self.item_b))
6078 }
6079 }
6080
6081 #[test]
6085 fn focus_next_from_tab_group_container_enters_that_group() {
6086 let mut cx = TestAppContext::single();
6087 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
6088 (
6089 cx.focus_handle(),
6090 cx.focus_handle().tab_stop(true),
6091 cx.focus_handle(),
6092 cx.focus_handle().tab_stop(true),
6093 )
6094 });
6095 let window: AnyWindowHandle = cx
6096 .add_window({
6097 let (group_a, item_a, group_b, item_b) =
6098 (group_a, item_a, group_b.clone(), item_b.clone());
6099 move |_, _| TabGroupFocus {
6100 group_a,
6101 item_a,
6102 group_b,
6103 item_b,
6104 }
6105 })
6106 .into();
6107 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6108 .unwrap();
6109
6110 let focused = cx
6112 .update_window(window, |_, window, cx| {
6113 window.focus(&group_b, cx);
6114 window.focus_next(cx);
6115 window.focused(cx).map(|handle| handle.id)
6116 })
6117 .unwrap();
6118
6119 assert_eq!(focused, Some(item_b.id));
6120 }
6121
6122 #[gpui::test]
6123 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
6124 cx: &mut TestAppContext,
6125 ) {
6126 struct PaddedContainer {
6127 scroll_handle: ScrollHandle,
6128 }
6129
6130 impl Render for PaddedContainer {
6131 fn render(
6132 &mut self,
6133 _window: &mut Window,
6134 _cx: &mut Context<Self>,
6135 ) -> impl IntoElement {
6136 div().size_full().child(
6139 div()
6140 .id("container")
6141 .h(px(50.))
6142 .w(px(100.))
6143 .py(px(4.25))
6144 .overflow_y_scroll()
6145 .track_scroll(&self.scroll_handle)
6146 .child(div().w_full().h(px(42.))),
6147 )
6148 }
6149 }
6150
6151 let scroll_handle = ScrollHandle::new();
6152 let window: AnyWindowHandle = cx
6153 .add_window({
6154 let scroll_handle = scroll_handle.clone();
6155 move |_, _| PaddedContainer { scroll_handle }
6156 })
6157 .into();
6158 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6159 .unwrap();
6160
6161 assert_eq!(scroll_handle.max_offset().y, px(0.));
6162 }
6163
6164 struct ScrollBurstTestView {
6165 root: ScrollHandle,
6166 short: ScrollHandle,
6167 long: ScrollHandle,
6168 deltas: Rc<RefCell<Vec<Point<Pixels>>>>,
6169 }
6170
6171 impl Render for ScrollBurstTestView {
6172 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6173 let deltas = self.deltas.clone();
6174 div()
6175 .id("burst-root")
6176 .relative()
6177 .w(px(300.))
6178 .h(px(100.))
6179 .overflow_scroll()
6180 .track_scroll(&self.root)
6181 .child(
6182 div()
6183 .id("burst-short")
6184 .absolute()
6185 .top_0()
6186 .left_0()
6187 .size(px(100.))
6188 .overflow_y_scroll()
6189 .track_scroll(&self.short)
6190 .child(div().w_full().h(px(20.))),
6191 )
6192 .child(
6193 div()
6194 .id("burst-long")
6195 .absolute()
6196 .top_0()
6197 .left(px(100.))
6198 .w(px(200.))
6199 .h(px(100.))
6200 .overflow_y_scroll()
6201 .track_scroll(&self.long)
6202 .on_scroll(move |event, window, _| {
6203 deltas
6204 .borrow_mut()
6205 .push(event.delta.pixel_delta(window.line_height()));
6206 })
6207 .child(div().w_full().h(px(600.))),
6208 )
6209 }
6210 }
6211
6212 fn dispatch_test_scroll(
6213 window: &mut Window,
6214 cx: &mut App,
6215 position: Point<Pixels>,
6216 delta: Point<Pixels>,
6217 ) {
6218 window.dispatch_event(
6219 crate::PlatformInput::Scroll(ScrollEvent {
6220 position,
6221 delta: crate::ScrollDelta::Pixels(delta),
6222 ..Default::default()
6223 }),
6224 cx,
6225 );
6226 }
6227
6228 #[gpui::test]
6229 fn wheel_bursts_and_sibling_transfer_keep_live_offsets_in_bounds(cx: &mut TestAppContext) {
6230 let root = ScrollHandle::new();
6231 let short = ScrollHandle::new();
6232 let long = ScrollHandle::new();
6233 let deltas = Rc::new(RefCell::new(Vec::new()));
6234 let window: AnyWindowHandle = cx
6235 .add_window({
6236 let root = root.clone();
6237 let short = short.clone();
6238 let long = long.clone();
6239 let deltas = deltas.clone();
6240 move |_, _| ScrollBurstTestView {
6241 root,
6242 short,
6243 long,
6244 deltas,
6245 }
6246 })
6247 .into();
6248
6249 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6250 .unwrap();
6251 assert_eq!(root.max_offset(), Point::default());
6252 assert_eq!(short.max_offset(), Point::default());
6253 assert_eq!(long.max_offset().y, px(500.));
6254
6255 cx.update_window(window, |_, window, cx| {
6256 let chat_position = point(px(150.), px(50.));
6257 let sidebar_position = point(px(50.), px(50.));
6258 dispatch_test_scroll(window, cx, chat_position, point(px(0.), px(-0.25)));
6259 assert_eq!(long.offset().y, px(-0.25));
6260 assert_eq!(root.offset(), Point::default());
6261
6262 for _ in 0..24 {
6264 dispatch_test_scroll(window, cx, chat_position, point(px(0.), px(-1000.)));
6265 assert_eq!(long.offset().y, px(-500.));
6266 assert_eq!(root.offset(), Point::default());
6267 }
6268 for delta in [-1000., 1000., -1000.] {
6269 dispatch_test_scroll(window, cx, sidebar_position, point(px(0.), px(delta)));
6270 assert_eq!(short.offset(), Point::default());
6271 assert_eq!(root.offset(), Point::default());
6272 assert_eq!(long.offset().y, px(-500.));
6273 }
6274 })
6275 .unwrap();
6276 assert_eq!(deltas.borrow().len(), 25);
6277 assert_eq!(deltas.borrow()[0], point(px(0.), px(-0.25)));
6278 assert!(
6279 deltas.borrow()[1..]
6280 .iter()
6281 .all(|delta| *delta == point(px(0.), px(-1000.)))
6282 );
6283 }
6284
6285 struct TranslatedScrollExtentTestView {
6286 outer: ScrollHandle,
6287 inner: ScrollHandle,
6288 negative_child: bool,
6289 }
6290
6291 impl Render for TranslatedScrollExtentTestView {
6292 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6293 div()
6294 .id("extent-outer")
6295 .size(px(100.))
6296 .overflow_scroll()
6297 .track_scroll(&self.outer)
6298 .child(
6299 div().relative().size(px(1000.)).child(
6300 div()
6301 .id("extent-inner")
6302 .absolute()
6303 .top_0()
6304 .left_0()
6305 .size(px(100.))
6306 .overflow_scroll()
6307 .track_scroll(&self.inner)
6308 .child(div().w(px(100.)).h(px(20.)))
6309 .child(div().absolute().top_0().left_0().size(px(0.)))
6311 .when(self.negative_child, |element| {
6312 element.child(
6313 div().absolute().left(px(-60.)).top(px(-120.)).size(px(20.)),
6314 )
6315 }),
6316 ),
6317 )
6318 }
6319 }
6320
6321 #[gpui::test]
6322 fn negative_ancestor_origins_do_not_create_or_inflate_scroll_extents(cx: &mut TestAppContext) {
6323 for negative_child in [false, true] {
6326 let outer = ScrollHandle::new();
6327 let inner = ScrollHandle::new();
6328 let window: AnyWindowHandle = cx
6329 .add_window({
6330 let outer = outer.clone();
6331 let inner = inner.clone();
6332 move |_, _| TranslatedScrollExtentTestView {
6333 outer,
6334 inner,
6335 negative_child,
6336 }
6337 })
6338 .into();
6339 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6340 .unwrap();
6341 let expected = Point::default();
6342 assert_eq!(inner.max_offset(), expected);
6343
6344 for displacement in [px(500.), px(800.), px(500.), px(0.)] {
6347 outer.set_offset(point(-displacement, -displacement));
6348 cx.update_window(window, |_, window, cx| {
6349 window.refresh();
6350 window.draw(cx).clear(cx);
6351 })
6352 .unwrap();
6353 assert_eq!(outer.offset(), point(-displacement, -displacement));
6354 assert_eq!(inner.max_offset(), expected);
6355 assert_eq!(inner.offset(), Point::default());
6356 }
6357 }
6358 }
6359
6360 struct PaddedScrollExtentTestView {
6361 handle: ScrollHandle,
6362 far_child: bool,
6363 }
6364
6365 impl Render for PaddedScrollExtentTestView {
6366 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6367 div()
6368 .id("padded")
6369 .size(px(100.))
6370 .p(px(10.))
6371 .overflow_scroll()
6372 .track_scroll(&self.handle)
6373 .child(div().w(px(80.)).h(px(80.)))
6375 .child(div().absolute().top(px(4.)).right(px(4.)).size(px(6.)))
6378 .child(div().absolute().top_0().right_0().size(px(0.)))
6379 .when(self.far_child, |element| {
6380 element.child(div().absolute().left(px(150.)).top_0().size(px(20.)))
6381 })
6382 }
6383 }
6384
6385 #[gpui::test]
6386 fn absolute_children_count_as_their_own_box_not_with_the_padding(cx: &mut TestAppContext) {
6387 for (far_child, expected) in [(false, Point::default()), (true, point(px(70.), px(0.)))] {
6391 let handle = ScrollHandle::new();
6392 let window: AnyWindowHandle = cx
6393 .add_window({
6394 let handle = handle.clone();
6395 move |_, _| PaddedScrollExtentTestView { handle, far_child }
6396 })
6397 .into();
6398 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6399 .unwrap();
6400 assert_eq!(handle.max_offset(), expected, "far child: {far_child}");
6401 }
6402 }
6403
6404 struct ContentSizedGrid;
6405
6406 impl Render for ContentSizedGrid {
6407 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6408 let widths = [px(100.), px(200.), px(50.)];
6409 div().size_full().child(
6410 div()
6411 .w_full()
6412 .grid()
6413 .grid_cols_max_content(widths.len() as u16)
6414 .children(widths.into_iter().enumerate().map(|(index, width)| {
6415 div()
6416 .debug_selector(move || format!("cell-{index}"))
6417 .w(width)
6418 .h(px(10.))
6419 })),
6420 )
6421 }
6422 }
6423
6424 #[gpui::test]
6425 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
6426 let window = cx.add_window(|_, _| ContentSizedGrid);
6427 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
6428 .unwrap();
6429
6430 let mut bounds = |selector: &'static str| {
6431 cx.update_window(window.into(), |_, window, _| {
6432 window.rendered_frame.debug_bounds.get(selector).copied()
6433 })
6434 .unwrap()
6435 .unwrap_or_else(|| panic!("{selector} was not rendered"))
6436 };
6437
6438 assert_eq!(bounds("cell-0").origin.x, px(0.));
6439 assert_eq!(bounds("cell-1").origin.x, px(100.));
6440 assert_eq!(bounds("cell-2").origin.x, px(300.));
6441 }
6442}