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 scale = window.scale_factor();
2725 let border = style
2726 .border_widths
2727 .to_pixels(rem_size)
2728 .map(|w| px(crate::util::round_stroke_to_device_pixel(w.0, scale) / scale));
2729 let padding_size = size(
2731 padding.left + padding.right + border.left + border.right,
2732 padding.top + padding.bottom + border.top + border.bottom,
2733 );
2734 let padded_content_size = self.content_size + padding_size;
2741 let padded_content_size = size(
2742 padded_content_size
2743 .width
2744 .max(self.out_of_flow_extent.width + border.right),
2745 padded_content_size
2746 .height
2747 .max(self.out_of_flow_extent.height + border.bottom),
2748 );
2749 Point::from(padded_content_size - bounds.size)
2750 .map(round_to_two_decimals)
2751 .max(&Default::default())
2752 }
2753
2754 fn clamp_scroll_position(
2755 &self,
2756 bounds: Bounds<Pixels>,
2757 style: &Style,
2758 window: &mut Window,
2759 _cx: &mut App,
2760 ) -> Point<Pixels> {
2761 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2762 let mut scroll_to_bottom = false;
2763 let mut tracked_scroll_handle = self
2764 .tracked_scroll_handle
2765 .as_ref()
2766 .map(|handle| handle.0.borrow_mut());
2767 if let Some(scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2768 scroll_handle_state.overflow = style.overflow;
2769 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2770 }
2771
2772 let scroll_max = self.max_scroll_offset(bounds, style, window);
2773 let mut scroll_offset = scroll_offset.borrow_mut();
2776
2777 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2778 if scroll_to_bottom {
2779 scroll_offset.y = -scroll_max.y;
2780 } else {
2781 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2782 }
2783
2784 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2785 scroll_handle_state.max_offset = scroll_max;
2786 scroll_handle_state.bounds = bounds;
2787 }
2788
2789 *scroll_offset
2790 } else {
2791 Point::default()
2792 }
2793 }
2794
2795 pub fn paint(
2804 &mut self,
2805 global_id: Option<&GlobalElementId>,
2806 _inspector_id: Option<&InspectorElementId>,
2807 bounds: Bounds<Pixels>,
2808 hitbox: Option<&Hitbox>,
2809 window: &mut Window,
2810 cx: &mut App,
2811 f: impl FnOnce(&Style, &mut Window, &mut App),
2812 ) {
2813 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2814 window.with_optional_element_state::<InteractiveElementState, _>(
2815 global_id,
2816 |element_state, window| {
2817 let mut element_state =
2818 element_state.map(|element_state| element_state.unwrap_or_default());
2819
2820 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2821
2822 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2823 if let Some(debug_selector) = &self.debug_selector {
2824 window
2825 .next_frame
2826 .record_debug_bounds(debug_selector.clone(), bounds);
2827 }
2828
2829 self.paint_hover_group_handler(window, cx);
2830
2831 if style.visibility == Visibility::Hidden {
2832 return ((), element_state);
2833 }
2834
2835 let mut tab_group = None;
2836 if self.tab_group {
2837 tab_group = self.tab_index;
2838 }
2839
2840 let own_transform = style.transform_matrix(bounds, window.scale_factor());
2841 window.vn_with_capture(style.vn_capture, bounds, own_transform, |window| {
2842 window.vn_set_effect_element(global_id);
2843 window.with_element_opacity(style.opacity, |window| {
2844 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2845 window.with_text_style(style.text_style_for_bounds(bounds, window), |window| {
2846 window.with_content_mask(
2847 style.overflow_mask(bounds, window.rem_size()),
2848 |window| {
2849 window.with_tab_group(tab_group, |window| {
2850 if let Some(focus_handle) = &self.tracked_focus_handle {
2859 window.next_frame.tab_stops.insert(focus_handle);
2860 }
2861 if let Some(hitbox) = hitbox {
2862 #[cfg(debug_assertions)]
2863 self.paint_debug_info(
2864 global_id, hitbox, &style, window, cx,
2865 );
2866
2867 if let Some(drag) = cx.active_drag.as_ref() {
2868 if let Some(mouse_cursor) = drag.cursor_style {
2869 window.set_window_cursor_style(mouse_cursor);
2870 }
2871 } else {
2872 if let Some(mouse_cursor) = style.mouse_cursor {
2873 window.set_cursor_style(mouse_cursor, hitbox);
2874 }
2875 }
2876
2877 if let Some(group) = self.group.clone() {
2878 GroupHitboxes::push(group, hitbox.id, cx);
2879 }
2880
2881 if let Some(area) = self.window_control {
2882 window.insert_window_control_hitbox(
2883 area,
2884 hitbox.clone(),
2885 );
2886 }
2887
2888 self.paint_mouse_listeners(
2889 hitbox,
2890 element_state.as_mut(),
2891 window,
2892 cx,
2893 );
2894 self.paint_scroll_listener(hitbox, &style, window, cx);
2895 }
2896
2897 self.paint_keyboard_listeners(window, cx);
2898
2899 if window.a11y.is_active() {
2900 if let Some(global_id) = global_id {
2901 if !self.a11y_action_listeners.is_empty() {
2902 let node_id = global_id.accesskit_node_id();
2903 for (action, listener) in
2904 self.a11y_action_listeners.drain(..)
2905 {
2906 window.on_a11y_action(
2907 node_id, action, listener,
2908 );
2909 }
2910 }
2911 }
2912 }
2913
2914 f(&style, window, cx);
2915
2916 if let Some(_hitbox) = hitbox {
2917 #[cfg(any(feature = "inspector", debug_assertions))]
2918 window.insert_inspector_hitbox(
2919 _hitbox.id,
2920 _inspector_id,
2921 cx,
2922 );
2923
2924 if let Some(group) = self.group.as_ref() {
2925 GroupHitboxes::pop(group, cx);
2926 }
2927 }
2928 })
2929 },
2930 );
2931 });
2932 });
2933 });
2934 });
2935
2936 ((), element_state)
2937 },
2938 );
2939 }
2940
2941 #[cfg(debug_assertions)]
2942 fn paint_debug_info(
2943 &self,
2944 global_id: Option<&GlobalElementId>,
2945 hitbox: &Hitbox,
2946 style: &Style,
2947 window: &mut Window,
2948 cx: &mut App,
2949 ) {
2950 use crate::{BorderStyle, TextAlign};
2951
2952 if let Some(global_id) = global_id
2953 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2954 && hitbox.is_hovered(window)
2955 {
2956 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2957 let element_id = format!("{global_id:?}");
2958 let str_len = element_id.len();
2959
2960 let render_debug_text = |window: &mut Window| {
2961 if let Some(text) = window
2962 .text_system()
2963 .shape_text(
2964 element_id.into(),
2965 FONT_SIZE,
2966 &[window.text_style().to_run(str_len)],
2967 None,
2968 None,
2969 )
2970 .ok()
2971 .and_then(|mut text| text.pop())
2972 {
2973 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2974 .ok();
2975
2976 let text_bounds = crate::Bounds {
2977 origin: hitbox.origin,
2978 size: text.size(FONT_SIZE),
2979 };
2980 if let Some(source_location) = self.source_location
2981 && text_bounds.contains(&window.mouse_position())
2982 && window.modifiers().secondary(cx)
2983 {
2984 let secondary_held = window.modifiers().secondary(cx);
2985 window.on_key_event({
2986 move |e: &crate::ModifiersChangedEvent, _phase, window, cx| {
2987 if e.modifiers.secondary(cx) != secondary_held
2988 && text_bounds.contains(&window.mouse_position())
2989 {
2990 window.refresh();
2991 }
2992 }
2993 });
2994
2995 let was_hovered = hitbox.is_hovered(window);
2996 let current_view = window.current_view();
2997 window.on_mouse_event({
2998 let hitbox = hitbox.clone();
2999 move |_: &MouseMoveEvent, phase, window, cx| {
3000 if phase == DispatchPhase::Capture {
3001 let hovered = hitbox.is_hovered(window);
3002 if hovered != was_hovered {
3003 cx.notify(current_view)
3004 }
3005 }
3006 }
3007 });
3008
3009 window.on_mouse_event({
3010 let hitbox = hitbox.clone();
3011 move |e: &crate::MouseDownEvent, phase, window, cx| {
3012 if text_bounds.contains(&e.position)
3013 && phase.capture()
3014 && hitbox.is_hovered(window)
3015 {
3016 cx.stop_propagation();
3017 let Ok(dir) = std::env::current_dir() else {
3018 return;
3019 };
3020
3021 eprintln!(
3022 "This element was created at:\n{}:{}:{}",
3023 dir.join(source_location.file()).to_string_lossy(),
3024 source_location.line(),
3025 source_location.column()
3026 );
3027 }
3028 }
3029 });
3030 window.paint_quad(crate::outline(
3031 crate::Bounds {
3032 origin: hitbox.origin
3033 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
3034 size: crate::Size {
3035 width: text_bounds.size.width,
3036 height: crate::px(1.),
3037 },
3038 },
3039 crate::red(),
3040 BorderStyle::default(),
3041 ))
3042 }
3043 }
3044 };
3045
3046 window.with_text_style(
3047 Some(crate::TextStyleRefinement {
3048 color: Some(crate::red()),
3049 line_height: Some(FONT_SIZE.into()),
3050 background_color: Some(crate::white()),
3051 ..Default::default()
3052 }),
3053 render_debug_text,
3054 )
3055 }
3056 }
3057
3058 fn paint_mouse_listeners(
3059 &mut self,
3060 hitbox: &Hitbox,
3061 element_state: Option<&mut InteractiveElementState>,
3062 window: &mut Window,
3063 cx: &mut App,
3064 ) {
3065 let is_focused = self
3066 .tracked_focus_handle
3067 .as_ref()
3068 .map(|handle| handle.is_focused(window))
3069 .unwrap_or(false);
3070
3071 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
3075 let hitbox = hitbox.clone();
3076 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
3077 if phase == DispatchPhase::Bubble
3078 && hitbox.is_hovered(window)
3079 && !window.default_prevented()
3080 {
3081 window.focus(&focus_handle, cx);
3082 window.prevent_default();
3085 }
3086 });
3087 }
3088
3089 for listener in self.mouse_down_listeners.drain(..) {
3090 let hitbox = hitbox.clone();
3091 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
3092 listener(event, phase, &hitbox, window, cx);
3093 })
3094 }
3095
3096 for listener in self.mouse_up_listeners.drain(..) {
3097 let hitbox = hitbox.clone();
3098 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
3099 listener(event, phase, &hitbox, window, cx);
3100 })
3101 }
3102
3103 for listener in self.mouse_pressure_listeners.drain(..) {
3104 let hitbox = hitbox.clone();
3105 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
3106 listener(event, phase, &hitbox, window, cx);
3107 })
3108 }
3109
3110 for listener in self.mouse_move_listeners.drain(..) {
3111 let hitbox = hitbox.clone();
3112 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
3113 listener(event, phase, &hitbox, window, cx);
3114 })
3115 }
3116
3117 for listener in self.mouse_exit_listeners.drain(..) {
3118 let hitbox = hitbox.clone();
3119 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
3120 listener(event, phase, &hitbox, window, cx);
3121 })
3122 }
3123
3124 for listener in self.file_drop_exit_listeners.drain(..) {
3125 let hitbox = hitbox.clone();
3126 window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
3127 listener(event, phase, &hitbox, window, cx);
3128 })
3129 }
3130
3131 for listener in self.scroll_listeners.drain(..) {
3132 let hitbox = hitbox.clone();
3133 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
3134 listener(event, phase, &hitbox, window, cx);
3135 })
3136 }
3137
3138 for listener in self.pinch_listeners.drain(..) {
3139 let hitbox = hitbox.clone();
3140 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
3141 listener(event, phase, &hitbox, window, cx);
3142 })
3143 }
3144
3145 for listener in self.back_gesture_listeners.drain(..) {
3146 let hitbox = hitbox.clone();
3147 window.on_mouse_event(move |event: &BackGestureEvent, phase, window, cx| {
3148 listener(event, phase, &hitbox, window, cx);
3149 })
3150 }
3151
3152 if self.hover_style.is_some()
3153 || self.base_style.mouse_cursor.is_some()
3154 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
3155 {
3156 let hitbox = hitbox.clone();
3157 let hover_state = self.hover_style.as_ref().and_then(|_| {
3158 element_state
3159 .as_ref()
3160 .and_then(|state| state.hover_state.as_ref())
3161 .cloned()
3162 });
3163 let current_view = window.current_view();
3164
3165 let hover_style_mode = self.hover_style_mode;
3166 if let Some(hover_state) = &hover_state {
3167 let hovered = hover_style_mode.is_hovered(&hitbox, window);
3168 catch_up_stored_hover(hover_state, |s| &mut s.element, hovered, window, cx);
3169 }
3170 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3171 let hovered = hover_style_mode.is_hovered(&hitbox, window);
3173 let was_hovered = hover_state
3174 .as_ref()
3175 .is_some_and(|state| state.borrow().element);
3176 if phase == DispatchPhase::Capture && hovered != was_hovered {
3177 if let Some(hover_state) = &hover_state {
3178 hover_state.borrow_mut().element = hovered;
3179 cx.notify(current_view);
3180 }
3181 }
3182 });
3183 }
3184
3185 if let Some(group_hover) = self.group_hover_style.as_ref() {
3186 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3187 let hover_state = element_state
3188 .as_ref()
3189 .and_then(|element| element.hover_state.as_ref())
3190 .cloned();
3191 let current_view = window.current_view();
3192
3193 let hover_style_mode = self.hover_style_mode;
3194 if let Some(hover_state) = &hover_state {
3195 let group_hovered = hover_style_mode.is_hovered_id(group_hitbox_id, window);
3196 catch_up_stored_hover(hover_state, |s| &mut s.group, group_hovered, window, cx);
3197 }
3198 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3199 let group_hovered = hover_style_mode.is_hovered_id(group_hitbox_id, window);
3201 let was_group_hovered = hover_state
3202 .as_ref()
3203 .is_some_and(|state| state.borrow().group);
3204 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
3205 if let Some(hover_state) = &hover_state {
3206 hover_state.borrow_mut().group = group_hovered;
3207 cx.notify(current_view);
3208 }
3209 }
3210 });
3211 }
3212 }
3213
3214 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
3215
3216 let mut drag_listener = mem::take(&mut self.drag_listener);
3217 let drop_listeners = mem::take(&mut self.drop_listeners);
3218 let click_listeners = mem::take(&mut self.click_listeners);
3219 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
3220 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
3221
3222 if !drop_listeners.is_empty() {
3223 let hitbox = hitbox.clone();
3224 window.on_mouse_event({
3225 move |_: &MouseUpEvent, phase, window, cx| {
3226 if let Some(drag) = &cx.active_drag
3227 && phase == DispatchPhase::Bubble
3228 && hitbox.is_hovered(window)
3229 {
3230 let drag_state_type = drag.value.as_ref().type_id();
3231 for (drop_state_type, listener) in &drop_listeners {
3232 if *drop_state_type == drag_state_type {
3233 let drag = cx
3234 .active_drag
3235 .take()
3236 .expect("checked for type drag state type above");
3237
3238 let mut can_drop = true;
3239 if let Some(predicate) = &can_drop_predicate {
3240 can_drop = predicate(drag.value.as_ref(), window, cx);
3241 }
3242
3243 if can_drop {
3244 listener(drag.value.as_ref(), window, cx);
3245 window.refresh();
3246 cx.stop_propagation();
3247 }
3248 }
3249 }
3250 }
3251 }
3252 });
3253 }
3254
3255 if let Some(element_state) = element_state {
3256 if !click_listeners.is_empty()
3257 || !aux_click_listeners.is_empty()
3258 || drag_listener.is_some()
3259 {
3260 let pending_mouse_down = element_state
3261 .pending_mouse_down
3262 .get_or_insert_with(Default::default)
3263 .clone();
3264
3265 let pending_keyboard_down = element_state
3266 .pending_keyboard_down
3267 .get_or_insert_with(Default::default)
3268 .clone();
3269
3270 let clicked_state = element_state
3271 .clicked_state
3272 .get_or_insert_with(Default::default)
3273 .clone();
3274
3275 window.on_mouse_event({
3276 let pending_mouse_down = pending_mouse_down.clone();
3277 let hitbox = hitbox.clone();
3278 let has_aux_click_listeners = !aux_click_listeners.is_empty();
3279 move |event: &MouseDownEvent, phase, window, _cx| {
3280 if phase == DispatchPhase::Bubble
3281 && (event.button == MouseButton::Left || has_aux_click_listeners)
3282 && hitbox.is_hovered(window)
3283 {
3284 *pending_mouse_down.borrow_mut() = Some(event.clone());
3285 window.refresh();
3286 }
3287 }
3288 });
3289
3290 window.on_mouse_event({
3291 let pending_mouse_down = pending_mouse_down.clone();
3292 let hitbox = hitbox.clone();
3293 move |event: &MouseMoveEvent, phase, window, cx| {
3294 if phase == DispatchPhase::Capture {
3295 return;
3296 }
3297
3298 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3299 if let Some(mouse_down) = pending_mouse_down.clone()
3300 && !cx.has_active_drag()
3301 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
3302 && let Some(listener) = drag_listener.take()
3303 && mouse_down.button == MouseButton::Left
3304 {
3305 *clicked_state.borrow_mut() = ElementClickedState::default();
3306 let cursor_offset = event.position - hitbox.origin;
3307 let drag = (listener.render)(
3308 listener.value.as_ref(),
3309 cursor_offset,
3310 window,
3311 cx,
3312 );
3313 let external_payload_source =
3314 listener.external_payload.map(|external_payload| {
3315 let value = listener.value.clone();
3316 Box::new(move |window: &mut Window, cx: &mut App| {
3317 external_payload(value.as_ref(), window, cx)
3318 })
3319 as ExternalDragPayloadSource
3320 });
3321 cx.active_drag = Some(AnyDrag {
3322 view: drag,
3323 value: listener.value,
3324 cursor_offset,
3325 cursor_style: drag_cursor_style,
3326 external_payload_source,
3327 });
3328 pending_mouse_down.take();
3329 window.refresh();
3330 cx.stop_propagation();
3331 }
3332 }
3333 });
3334
3335 if is_focused {
3336 window.on_key_event({
3346 let pending_keyboard_down = pending_keyboard_down.clone();
3347 move |event: &KeyDownEvent, phase, window, _cx| {
3348 if phase.bubble() && !window.default_prevented() {
3349 let stroke = &event.keystroke;
3350 let is_activation_key = (stroke.key.eq("enter")
3351 || stroke.key.eq("space"))
3352 && !stroke.modifiers.modified();
3353 *pending_keyboard_down.borrow_mut() =
3354 is_activation_key.then_some(window.focus_generation);
3355 }
3356 }
3357 });
3358
3359 window.on_key_event({
3361 let click_listeners = click_listeners.clone();
3362 let hitbox = hitbox.clone();
3363 move |event: &KeyUpEvent, phase, window, cx| {
3364 if phase.bubble() && !window.default_prevented() {
3365 let stroke = &event.keystroke;
3366 let keyboard_button = if stroke.key.eq("enter") {
3367 Some(KeyboardButton::Enter)
3368 } else if stroke.key.eq("space") {
3369 Some(KeyboardButton::Space)
3370 } else {
3371 None
3372 };
3373
3374 if let Some(button) = keyboard_button
3375 && !stroke.modifiers.modified()
3376 {
3377 let pending =
3378 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
3379 if pending != Some(window.focus_generation) {
3380 return;
3381 }
3382
3383 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
3384 button,
3385 bounds: hitbox.bounds,
3386 });
3387
3388 for listener in &click_listeners {
3389 listener(&click_event, window, cx);
3390 }
3391 } else {
3392 *pending_keyboard_down.borrow_mut() = None;
3396 }
3397 }
3398 }
3399 });
3400 }
3401
3402 window.on_mouse_event({
3403 let mut captured_mouse_down = None;
3404 let hitbox = hitbox.clone();
3405 move |event: &MouseUpEvent, phase, window, cx| match phase {
3406 DispatchPhase::Capture => {
3410 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3411 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
3412 captured_mouse_down = pending_mouse_down.take();
3413 window.refresh();
3414 } else if pending_mouse_down.is_some() {
3415 pending_mouse_down.take();
3421 window.refresh();
3422 }
3423 }
3424 DispatchPhase::Bubble => {
3426 if let Some(mouse_down) = captured_mouse_down.take() {
3427 let btn = mouse_down.button;
3428
3429 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
3430 down: mouse_down,
3431 up: event.clone(),
3432 });
3433
3434 match btn {
3435 MouseButton::Left => {
3436 for listener in &click_listeners {
3437 listener(&mouse_click, window, cx);
3438 }
3439 }
3440 _ => {
3441 for listener in &aux_click_listeners {
3442 listener(&mouse_click, window, cx);
3443 }
3444 }
3445 }
3446 }
3447 }
3448 }
3449 });
3450 }
3451
3452 if let Some(hover_listener) = self.hover_listener.take() {
3453 let was_hovered = element_state
3454 .hover_listener_state
3455 .get_or_insert_with(Default::default)
3456 .clone();
3457 let has_mouse_down = element_state
3458 .pending_mouse_down
3459 .get_or_insert_with(Default::default)
3460 .clone();
3461 let hover_listener = Rc::new(hover_listener);
3462 let hover_listener_state = was_hovered.clone();
3463 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3464 let mut was_hovered = hover_listener_state.borrow_mut();
3465 if is_hovered != *was_hovered {
3466 *was_hovered = is_hovered;
3467 drop(was_hovered);
3468 hover_listener(&is_hovered, window, cx);
3469 }
3470 };
3471 let hover_listener_mode = self.hover_listener_mode;
3472
3473 if has_mouse_down.borrow().is_none() {
3474 let is_hovered =
3475 !cx.has_active_drag() && hover_listener_mode.is_hovered(hitbox, window);
3476 if is_hovered != *was_hovered.borrow() {
3477 let update_hover = update_hover.clone();
3478 window.defer(cx, move |window, cx| {
3479 update_hover(is_hovered, window, cx);
3480 });
3481 }
3482 }
3483
3484 window.on_mouse_event({
3485 let update_hover = update_hover.clone();
3486 let hitbox = hitbox.clone();
3487 move |_: &MouseMoveEvent, phase, window, cx| {
3488 if phase == DispatchPhase::Bubble {
3489 let is_hovered = has_mouse_down.borrow().is_none()
3490 && !cx.has_active_drag()
3491 && hover_listener_mode.is_hovered(&hitbox, window);
3492 update_hover(is_hovered, window, cx);
3493 }
3494 }
3495 });
3496
3497 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3500 if phase == DispatchPhase::Bubble {
3501 update_hover(false, window, cx);
3502 }
3503 });
3504 }
3505
3506 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3507 let active_tooltip = element_state
3508 .active_tooltip
3509 .get_or_insert_with(Default::default)
3510 .clone();
3511 let pending_mouse_down = element_state
3512 .pending_mouse_down
3513 .get_or_insert_with(Default::default)
3514 .clone();
3515 let long_press_tooltip_active = element_state
3516 .long_press_tooltip_active
3517 .get_or_insert_with(Default::default)
3518 .clone();
3519
3520 let tooltip_is_hoverable = tooltip_builder.hoverable;
3521 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3522 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3523 });
3524 let check_is_hovered_during_prepaint = Rc::new({
3526 let pending_mouse_down = pending_mouse_down.clone();
3527 let source_bounds = hitbox.bounds;
3528 move |window: &Window| {
3529 !window.last_input_was_keyboard()
3530 && pending_mouse_down.borrow().is_none()
3531 && source_bounds.contains(&window.mouse_position())
3532 }
3533 });
3534 let check_is_hovered = Rc::new({
3535 let hitbox = hitbox.clone();
3536 move |window: &Window| {
3537 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3538 }
3539 });
3540 register_tooltip_mouse_handlers(
3541 &active_tooltip,
3542 self.tooltip_id,
3543 build_tooltip,
3544 check_is_hovered,
3545 check_is_hovered_during_prepaint,
3546 long_press_tooltip_active,
3547 self.tooltip_show_delay,
3548 window,
3549 );
3550 }
3551
3552 let active_state = element_state
3555 .clicked_state
3556 .get_or_insert_with(Default::default)
3557 .clone();
3558
3559 {
3560 let active_state = active_state.clone();
3561 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3562 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3563 *active_state.borrow_mut() = ElementClickedState::default();
3564 window.refresh();
3565 }
3566 });
3567 }
3568
3569 {
3570 let active_group_hitbox = self
3571 .group_active_style
3572 .as_ref()
3573 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3574 let hitbox = hitbox.clone();
3575 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3576 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3577 let group_hovered = active_group_hitbox
3578 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3579 let element_hovered = hitbox.is_hovered(window);
3580 if group_hovered || element_hovered {
3581 *active_state.borrow_mut() = ElementClickedState {
3582 group: group_hovered,
3583 element: element_hovered,
3584 };
3585 window.refresh();
3586 }
3587 }
3588 });
3589 }
3590 }
3591 }
3592
3593 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3594 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3595 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3596 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3597 let action_listeners = mem::take(&mut self.action_listeners);
3598 if let Some(context) = self.key_context.clone() {
3599 window.set_key_context(context);
3600 }
3601
3602 for listener in key_down_listeners {
3603 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3604 listener(event, phase, window, cx);
3605 })
3606 }
3607
3608 for listener in key_up_listeners {
3609 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3610 listener(event, phase, window, cx);
3611 })
3612 }
3613
3614 for listener in modifiers_changed_listeners {
3615 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3616 listener(event, window, cx);
3617 })
3618 }
3619
3620 for (action_type, listener) in action_listeners {
3621 window.on_action(action_type, listener)
3622 }
3623 }
3624
3625 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3626 let group_hitbox = self
3627 .group_hover_style
3628 .as_ref()
3629 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3630
3631 if let Some(group_hitbox) = group_hitbox {
3632 let was_hovered = group_hitbox.is_hovered(window);
3633 let current_view = window.current_view();
3634 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3635 let hovered = group_hitbox.is_hovered(window);
3636 if phase == DispatchPhase::Capture && hovered != was_hovered {
3637 cx.notify(current_view);
3638 }
3639 });
3640 }
3641 }
3642
3643 fn paint_scroll_listener(
3644 &self,
3645 hitbox: &Hitbox,
3646 style: &Style,
3647 window: &mut Window,
3648 _cx: &mut App,
3649 ) {
3650 if let Some(scroll_offset) = self.scroll_offset.clone() {
3651 let scroll_max = self.max_scroll_offset(hitbox.bounds, style, window);
3652 let ongoing_scroll = self.ongoing_scroll.clone();
3653 let overflow = style.overflow;
3654 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3655 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3656 let line_height = window.line_height();
3657 let hitbox = hitbox.clone();
3658 let current_view = window.current_view();
3659 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
3660 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3661 let mut scroll_offset = scroll_offset.borrow_mut();
3662 let old_scroll_offset = *scroll_offset;
3663 let mut delta = event.delta.pixel_delta(line_height);
3664
3665 if restrict_scroll_to_axis
3666 && event.delta.precise()
3667 && let Some(ongoing_scroll) = &ongoing_scroll
3668 {
3669 ongoing_scroll
3670 .borrow_mut()
3671 .filter(&mut delta, event.touch_phase);
3672 }
3673
3674 let mut delta_x = match overflow.x {
3675 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3676 Overflow::Scroll
3677 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3678 {
3679 delta.y
3680 }
3681 _ => Pixels::ZERO,
3682 };
3683 let mut delta_y = match overflow.y {
3684 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3685 Overflow::Scroll
3686 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3687 {
3688 delta.x
3689 }
3690 _ => Pixels::ZERO,
3691 };
3692 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3693 if delta_x.abs() > delta_y.abs() {
3694 delta_y = Pixels::ZERO;
3695 } else {
3696 delta_x = Pixels::ZERO;
3697 }
3698 }
3699 scroll_offset.y = (scroll_offset.y + delta_y).clamp(-scroll_max.y, px(0.));
3702 scroll_offset.x = (scroll_offset.x + delta_x).clamp(-scroll_max.x, px(0.));
3703 if *scroll_offset != old_scroll_offset {
3704 cx.notify(current_view);
3705 }
3706 }
3707 });
3708 }
3709 }
3710
3711 pub fn compute_style(
3713 &self,
3714 global_id: Option<&GlobalElementId>,
3715 hitbox: Option<&Hitbox>,
3716 window: &mut Window,
3717 cx: &mut App,
3718 ) -> Style {
3719 window.with_optional_element_state(global_id, |element_state, window| {
3720 let mut element_state =
3721 element_state.map(|element_state| element_state.unwrap_or_default());
3722 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3723 (style, element_state)
3724 })
3725 }
3726
3727 fn compute_style_internal(
3729 &self,
3730 hitbox: Option<&Hitbox>,
3731 element_state: Option<&mut InteractiveElementState>,
3732 window: &mut Window,
3733 cx: &mut App,
3734 ) -> Style {
3735 let mut style = Style::default();
3736 style.refine(&self.base_style);
3737
3738 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3739 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3740 && focus_handle.within_focused(window, cx)
3741 {
3742 style.refine(in_focus_style);
3743 }
3744
3745 if let Some(focus_style) = self.focus_style.as_ref()
3746 && focus_handle.is_focused(window)
3747 {
3748 style.refine(focus_style);
3749 }
3750
3751 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3752 && focus_handle.is_focused(window)
3753 && window.last_input_was_keyboard()
3754 {
3755 style.refine(focus_visible_style);
3756 }
3757 }
3758
3759 if !cx.has_active_drag() {
3760 if let Some(group_hover) = self.group_hover_style.as_ref() {
3761 let is_group_hovered =
3762 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3763 !window.last_input_was_touch()
3765 && self.hover_style_mode.is_hovered_id(group_hitbox_id, window)
3766 } else if let Some(element_state) = element_state.as_ref() {
3767 !window.last_input_was_touch()
3768 && element_state
3769 .hover_state
3770 .as_ref()
3771 .map(|state| state.borrow().group)
3772 .unwrap_or(false)
3773 } else {
3774 false
3775 };
3776
3777 if is_group_hovered {
3778 style.refine(&group_hover.style);
3779 }
3780 }
3781
3782 if let Some(hover_style) = self.hover_style.as_ref() {
3783 let is_hovered = if let Some(hitbox) = hitbox {
3784 !window.last_input_was_touch()
3786 && self.hover_style_mode.is_hovered(hitbox, window)
3787 } else if let Some(element_state) = element_state.as_ref() {
3788 !window.last_input_was_touch()
3789 && element_state
3790 .hover_state
3791 .as_ref()
3792 .map(|state| state.borrow().element)
3793 .unwrap_or(false)
3794 } else {
3795 false
3796 };
3797
3798 if is_hovered {
3799 style.refine(hover_style);
3800 }
3801 }
3802 }
3803
3804 if let Some(hitbox) = hitbox {
3805 if let Some(drag) = cx.active_drag.take() {
3806 let mut can_drop = true;
3807 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3808 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3809 }
3810
3811 if can_drop {
3812 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3813 if let Some(group_hitbox_id) =
3814 GroupHitboxes::get(&group_drag_style.group, cx)
3815 && *state_type == drag.value.as_ref().type_id()
3816 && group_hitbox_id.is_hovered(window)
3817 {
3818 style.refine(&group_drag_style.style);
3819 }
3820 }
3821
3822 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3823 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3824 {
3825 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3826 }
3827 }
3828 }
3829
3830 style.mouse_cursor = drag.cursor_style;
3831 cx.active_drag = Some(drag);
3832 }
3833 }
3834
3835 if let Some(element_state) = element_state {
3836 let clicked_state = element_state
3837 .clicked_state
3838 .get_or_insert_with(Default::default)
3839 .borrow();
3840 if clicked_state.group
3841 && let Some(group) = self.group_active_style.as_ref()
3842 {
3843 style.refine(&group.style)
3844 }
3845
3846 if let Some(active_style) = self.active_style.as_ref()
3847 && clicked_state.element
3848 {
3849 style.refine(active_style)
3850 }
3851 }
3852
3853 style
3854 }
3855
3856 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3857 if let Some(id) = &self.aria.author_id {
3858 node.set_author_id(id.to_string());
3859 }
3860 if let Some(label) = &self.aria.label {
3861 node.set_label(label.to_string());
3862 }
3863 if let Some(description) = &self.aria.description {
3864 node.set_description(description.to_string());
3865 }
3866 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3867 node.set_keyboard_shortcut(keyshortcuts.to_string());
3868 }
3869 if let Some(selected) = self.aria.selected {
3870 node.set_selected(selected);
3871 }
3872 if let Some(expanded) = self.aria.expanded {
3873 node.set_expanded(expanded);
3874 }
3875 if let Some(toggled) = self.aria.toggled {
3876 node.set_toggled(toggled);
3877 }
3878 if let Some(value) = self.aria.numeric_value {
3879 node.set_numeric_value(value);
3880 }
3881 if let Some(value) = self.aria.min_numeric_value {
3882 node.set_min_numeric_value(value);
3883 }
3884 if let Some(value) = self.aria.max_numeric_value {
3885 node.set_max_numeric_value(value);
3886 }
3887 if let Some(step) = self.aria.numeric_value_step {
3888 node.set_numeric_value_step(step);
3889 }
3890 if let Some(value) = &self.aria.value {
3891 node.set_value(value.to_string());
3892 }
3893 if let Some(placeholder) = &self.aria.placeholder {
3894 node.set_placeholder(placeholder.to_string());
3895 }
3896 if let Some(orientation) = self.aria.orientation {
3897 node.set_orientation(orientation);
3898 }
3899 if let Some(level) = self.aria.level {
3900 node.set_level(level);
3901 }
3902 if let Some(position) = self.aria.position_in_set {
3903 node.set_position_in_set(position);
3904 }
3905 if let Some(size) = self.aria.size_of_set {
3906 node.set_size_of_set(size);
3907 }
3908 if let Some(index) = self.aria.row_index {
3909 node.set_row_index(index);
3910 }
3911 if let Some(index) = self.aria.column_index {
3912 node.set_column_index(index);
3913 }
3914 if let Some(count) = self.aria.row_count {
3915 node.set_row_count(count);
3916 }
3917 if let Some(count) = self.aria.column_count {
3918 node.set_column_count(count);
3919 }
3920 match self.aria.disabled {
3923 Some(true) => node.set_disabled(),
3924 Some(false) => node.clear_disabled(),
3925 None => {}
3926 }
3927 match self.aria.read_only {
3928 Some(true) => node.set_read_only(),
3929 Some(false) => node.clear_read_only(),
3930 None => {}
3931 }
3932 match self.aria.required {
3933 Some(true) => node.set_required(),
3934 Some(false) => node.clear_required(),
3935 None => {}
3936 }
3937 match self.aria.modal {
3938 Some(true) => node.set_modal(),
3939 Some(false) => node.clear_modal(),
3940 None => {}
3941 }
3942 match self.aria.hidden {
3943 Some(true) => node.set_hidden(),
3944 Some(false) => node.clear_hidden(),
3945 None => {}
3946 }
3947 if !self.click_listeners.is_empty() {
3948 node.add_action(accesskit::Action::Click);
3949 }
3950 if self.tracked_focus_handle.is_some() || self.focusable {
3951 node.add_action(accesskit::Action::Focus);
3952 }
3953 for (action, _) in &self.a11y_action_listeners {
3954 node.add_action(*action);
3955 }
3956 }
3957}
3958
3959#[derive(Default)]
3962pub struct InteractiveElementState {
3963 pub(crate) focus_handle: Option<FocusHandle>,
3964 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3965 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3966 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3967 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3968 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3976 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3977 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3978 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3979 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3980}
3981
3982#[derive(Copy, Clone, Default, Eq, PartialEq)]
3984pub struct ElementClickedState {
3985 pub group: bool,
3987
3988 pub element: bool,
3990}
3991
3992impl ElementClickedState {
3993 fn is_clicked(&self) -> bool {
3994 self.group || self.element
3995 }
3996}
3997
3998#[derive(Copy, Clone, Default, Eq, PartialEq)]
4000pub struct ElementHoverState {
4001 pub group: bool,
4003
4004 pub element: bool,
4006}
4007
4008fn catch_up_stored_hover(
4022 state: &Rc<RefCell<ElementHoverState>>,
4023 field: impl FnOnce(&mut ElementHoverState) -> &mut bool,
4024 hovered: bool,
4025 window: &mut Window,
4026 cx: &mut App,
4027) {
4028 let mut state = state.borrow_mut();
4029 let stored = field(&mut state);
4030 if *stored != hovered {
4031 *stored = hovered;
4032 let current_view = window.current_view();
4033 window.defer(cx, move |_, cx| cx.notify(current_view));
4034 }
4035}
4036
4037pub(crate) enum ActiveTooltip {
4038 WaitingForShow { _task: Task<()> },
4040 Visible {
4042 tooltip: AnyTooltip,
4043 is_hoverable: bool,
4044 },
4045 WaitingForHide {
4048 tooltip: AnyTooltip,
4049 _task: Task<()>,
4050 },
4051}
4052
4053pub(crate) fn clear_active_tooltip(
4054 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4055 window: &mut Window,
4056) {
4057 match active_tooltip.borrow_mut().take() {
4058 None => {}
4059 Some(ActiveTooltip::WaitingForShow { .. }) => {}
4060 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
4061 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
4062 }
4063}
4064
4065pub(crate) fn clear_active_tooltip_if_not_hoverable(
4066 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4067 window: &mut Window,
4068) {
4069 let should_clear = match active_tooltip.borrow().as_ref() {
4070 None => false,
4071 Some(ActiveTooltip::WaitingForShow { .. }) => false,
4072 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
4073 Some(ActiveTooltip::WaitingForHide { .. }) => false,
4074 };
4075 if should_clear {
4076 active_tooltip.borrow_mut().take();
4077 window.refresh();
4078 }
4079}
4080
4081pub(crate) fn set_tooltip_on_window(
4082 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4083 window: &mut Window,
4084) -> Option<TooltipId> {
4085 let tooltip = match active_tooltip.borrow().as_ref() {
4086 None => return None,
4087 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
4088 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
4089 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
4090 };
4091 Some(window.set_tooltip(tooltip))
4092}
4093
4094pub(crate) fn register_tooltip_mouse_handlers(
4095 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4096 tooltip_id: Option<TooltipId>,
4097 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4098 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
4099 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
4100 long_press_tooltip_active: Rc<Cell<bool>>,
4101 show_delay: Option<Duration>,
4102 window: &mut Window,
4103) {
4104 let current_view = window.current_view();
4105 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
4106
4107 window.on_mouse_event({
4108 let active_tooltip = active_tooltip.clone();
4109 let build_tooltip = build_tooltip.clone();
4110 let check_is_hovered = check_is_hovered.clone();
4111 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4112 move |_: &MouseMoveEvent, phase, window, cx| {
4113 handle_tooltip_mouse_move(
4114 &active_tooltip,
4115 &build_tooltip,
4116 &check_is_hovered,
4117 &check_is_hovered_during_prepaint,
4118 tooltip_id,
4119 current_view,
4120 phase,
4121 show_delay,
4122 window,
4123 cx,
4124 )
4125 }
4126 });
4127
4128 window.on_mouse_event({
4129 let active_tooltip = active_tooltip.clone();
4130 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
4131 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
4132 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
4133 }
4134 }
4135 });
4136
4137 window.on_mouse_event({
4138 let active_tooltip = active_tooltip.clone();
4139 let build_tooltip = build_tooltip.clone();
4140 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4141 move |event: &LongPressEvent, phase, window, cx| {
4142 if !phase.bubble() {
4143 return;
4144 }
4145
4146 match event.phase {
4147 TouchPhase::Started if !window.default_prevented() && check_is_hovered(window) => {
4148 if show_tooltip(
4149 &active_tooltip,
4150 &build_tooltip,
4151 &check_is_hovered_during_prepaint,
4152 Some(long_press_tooltip_active.clone()),
4153 window,
4154 cx,
4155 ) {
4156 long_press_tooltip_active.set(true);
4157 window.prevent_default();
4158 cx.stop_propagation();
4159 }
4160 }
4161 TouchPhase::Ended | TouchPhase::Cancelled
4162 if long_press_tooltip_active.replace(false) =>
4163 {
4164 clear_active_tooltip(&active_tooltip, window);
4165 cx.stop_propagation();
4166 }
4167 TouchPhase::Started
4168 | TouchPhase::Moved
4169 | TouchPhase::Ended
4170 | TouchPhase::Cancelled => {}
4171 }
4172 }
4173 });
4174
4175 window.on_mouse_event({
4176 let active_tooltip = active_tooltip.clone();
4177 move |_: &ScrollEvent, _phase, window: &mut Window, _cx| {
4178 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
4179 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
4180 }
4181 }
4182 });
4183}
4184
4185fn handle_tooltip_mouse_move(
4197 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4198 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4199 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
4200 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
4201 tooltip_id: Option<TooltipId>,
4202 current_view: EntityId,
4203 phase: DispatchPhase,
4204 show_delay: Duration,
4205 window: &mut Window,
4206 cx: &mut App,
4207) {
4208 enum Action {
4211 None,
4212 CancelShow,
4213 ScheduleShow,
4214 CheckVisible,
4215 }
4216
4217 let action = match active_tooltip.borrow().as_ref() {
4218 None => {
4219 let is_hovered = check_is_hovered(window);
4220 if is_hovered && phase.bubble() {
4221 Action::ScheduleShow
4222 } else {
4223 Action::None
4224 }
4225 }
4226 Some(ActiveTooltip::WaitingForShow { .. }) => {
4227 let is_hovered = check_is_hovered(window);
4228 if is_hovered {
4229 Action::None
4230 } else {
4231 Action::CancelShow
4232 }
4233 }
4234 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
4235 if phase.capture()
4236 && !check_is_hovered(window)
4237 && (!*is_hoverable
4238 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
4239 {
4240 Action::CheckVisible
4241 } else {
4242 Action::None
4243 }
4244 }
4245 Some(ActiveTooltip::WaitingForHide { .. }) => {
4246 if phase.capture()
4247 && (check_is_hovered(window)
4248 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
4249 {
4250 Action::CheckVisible
4251 } else {
4252 Action::None
4253 }
4254 }
4255 };
4256
4257 match action {
4258 Action::None => {}
4259 Action::CancelShow => {
4260 active_tooltip.borrow_mut().take();
4262 }
4263 Action::ScheduleShow => {
4264 let delayed_show_task = window.spawn(cx, {
4265 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4266 let build_tooltip = build_tooltip.clone();
4267 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4268 async move |cx| {
4269 cx.background_executor().timer(show_delay).await;
4270 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4271 return;
4272 };
4273 cx.update(|window, cx| {
4274 show_tooltip(
4275 &active_tooltip,
4276 &build_tooltip,
4277 &check_is_hovered_during_prepaint,
4278 None,
4279 window,
4280 cx,
4281 );
4282 })
4283 .ok();
4284 }
4285 });
4286 active_tooltip
4287 .borrow_mut()
4288 .replace(ActiveTooltip::WaitingForShow {
4289 _task: delayed_show_task,
4290 });
4291 }
4292 Action::CheckVisible => cx.notify(current_view),
4293 }
4294}
4295
4296fn show_tooltip(
4297 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4298 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4299 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
4300 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
4301 window: &mut Window,
4302 cx: &mut App,
4303) -> bool {
4304 let new_tooltip = build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
4305 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4306 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4307 ActiveTooltip::Visible {
4308 tooltip: AnyTooltip {
4309 view,
4310 mouse_position: window.mouse_position(),
4311 check_visible_and_update: Rc::new(move |tooltip_bounds, window, cx| {
4312 if long_press_tooltip_active
4313 .as_ref()
4314 .is_some_and(|active| active.get())
4315 {
4316 return true;
4317 }
4318 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4319 return false;
4320 };
4321 handle_tooltip_check_visible_and_update(
4322 &active_tooltip,
4323 tooltip_is_hoverable,
4324 &check_is_hovered_during_prepaint,
4325 tooltip_bounds,
4326 window,
4327 cx,
4328 )
4329 }),
4330 },
4331 is_hoverable: tooltip_is_hoverable,
4332 }
4333 });
4334 let did_show = new_tooltip.is_some();
4335 *active_tooltip.borrow_mut() = new_tooltip;
4336 window.refresh();
4337 did_show
4338}
4339
4340fn handle_tooltip_check_visible_and_update(
4344 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4345 tooltip_is_hoverable: bool,
4346 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
4347 tooltip_bounds: Bounds<Pixels>,
4348 window: &mut Window,
4349 cx: &mut App,
4350) -> bool {
4351 enum Action {
4354 None,
4355 Hide,
4356 ScheduleHide(AnyTooltip),
4357 CancelHide(AnyTooltip),
4358 }
4359
4360 let is_hovered = check_is_hovered(window)
4361 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
4362 let action = match active_tooltip.borrow().as_ref() {
4363 Some(ActiveTooltip::Visible { tooltip, .. }) => {
4364 if is_hovered {
4365 Action::None
4366 } else {
4367 if tooltip_is_hoverable {
4368 Action::ScheduleHide(tooltip.clone())
4369 } else {
4370 Action::Hide
4371 }
4372 }
4373 }
4374 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
4375 if is_hovered {
4376 Action::CancelHide(tooltip.clone())
4377 } else {
4378 Action::None
4379 }
4380 }
4381 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
4382 };
4383
4384 match action {
4385 Action::None => {}
4386 Action::Hide => clear_active_tooltip(active_tooltip, window),
4387 Action::ScheduleHide(tooltip) => {
4388 let delayed_hide_task = window.spawn(cx, {
4389 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4390 async move |cx| {
4391 cx.background_executor()
4392 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
4393 .await;
4394 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4395 return;
4396 };
4397 if active_tooltip.borrow_mut().take().is_some() {
4398 cx.update(|window, _cx| window.refresh()).ok();
4399 }
4400 }
4401 });
4402 active_tooltip
4403 .borrow_mut()
4404 .replace(ActiveTooltip::WaitingForHide {
4405 tooltip,
4406 _task: delayed_hide_task,
4407 });
4408 }
4409 Action::CancelHide(tooltip) => {
4410 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
4412 tooltip,
4413 is_hoverable: true,
4414 });
4415 }
4416 }
4417
4418 active_tooltip.borrow().is_some()
4419}
4420
4421#[derive(Default)]
4422pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
4423
4424impl Global for GroupHitboxes {}
4425
4426impl GroupHitboxes {
4427 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
4428 cx.default_global::<Self>()
4429 .0
4430 .get(name)
4431 .and_then(|bounds_stack| bounds_stack.last())
4432 .cloned()
4433 }
4434
4435 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
4436 cx.default_global::<Self>()
4437 .0
4438 .entry(name)
4439 .or_default()
4440 .push(hitbox_id);
4441 }
4442
4443 pub fn pop(name: &SharedString, cx: &mut App) {
4444 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
4445 }
4446}
4447
4448pub struct Stateful<E> {
4450 pub(crate) element: E,
4451}
4452
4453impl<E> Styled for Stateful<E>
4454where
4455 E: Styled,
4456{
4457 fn style(&mut self) -> &mut StyleRefinement {
4458 self.element.style()
4459 }
4460}
4461
4462impl<E> StatefulInteractiveElement for Stateful<E>
4463where
4464 E: Element,
4465 Self: InteractiveElement,
4466{
4467}
4468
4469impl<E> InteractiveElement for Stateful<E>
4470where
4471 E: InteractiveElement,
4472{
4473 fn interactivity(&mut self) -> &mut Interactivity {
4474 self.element.interactivity()
4475 }
4476}
4477
4478impl<E> Element for Stateful<E>
4479where
4480 E: Element,
4481{
4482 type RequestLayoutState = E::RequestLayoutState;
4483 type PrepaintState = E::PrepaintState;
4484
4485 fn id(&self) -> Option<ElementId> {
4486 self.element.id()
4487 }
4488
4489 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4490 self.element.source_location()
4491 }
4492
4493 fn a11y_role(&self) -> Option<accesskit::Role> {
4494 self.element.a11y_role()
4495 }
4496
4497 fn write_a11y_info(&self, node: &mut accesskit::Node) {
4498 self.element.write_a11y_info(node);
4499 }
4500
4501 fn a11y_synthetic_children(
4502 &mut self,
4503 prepaint: &mut Self::PrepaintState,
4504 builder: &mut crate::A11ySubtreeBuilder,
4505 ) {
4506 self.element.a11y_synthetic_children(prepaint, builder);
4507 }
4508
4509 fn request_layout(
4510 &mut self,
4511 id: Option<&GlobalElementId>,
4512 inspector_id: Option<&InspectorElementId>,
4513 window: &mut Window,
4514 cx: &mut App,
4515 ) -> (LayoutId, Self::RequestLayoutState) {
4516 self.element.request_layout(id, inspector_id, window, cx)
4517 }
4518
4519 fn prepaint(
4520 &mut self,
4521 id: Option<&GlobalElementId>,
4522 inspector_id: Option<&InspectorElementId>,
4523 bounds: Bounds<Pixels>,
4524 state: &mut Self::RequestLayoutState,
4525 window: &mut Window,
4526 cx: &mut App,
4527 ) -> E::PrepaintState {
4528 self.element
4529 .prepaint(id, inspector_id, bounds, state, window, cx)
4530 }
4531
4532 fn paint(
4533 &mut self,
4534 id: Option<&GlobalElementId>,
4535 inspector_id: Option<&InspectorElementId>,
4536 bounds: Bounds<Pixels>,
4537 request_layout: &mut Self::RequestLayoutState,
4538 prepaint: &mut Self::PrepaintState,
4539 window: &mut Window,
4540 cx: &mut App,
4541 ) {
4542 self.element.paint(
4543 id,
4544 inspector_id,
4545 bounds,
4546 request_layout,
4547 prepaint,
4548 window,
4549 cx,
4550 );
4551 }
4552}
4553
4554impl<E> ParentElement for Stateful<E>
4555where
4556 E: ParentElement,
4557{
4558 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4559 self.element.extend(elements)
4560 }
4561}
4562
4563#[derive(Clone)]
4566pub struct ScrollAnchor {
4567 handle: ScrollHandle,
4568 last_origin: Rc<RefCell<Point<Pixels>>>,
4569}
4570
4571impl ScrollAnchor {
4572 pub fn for_handle(handle: ScrollHandle) -> Self {
4574 Self {
4575 handle,
4576 last_origin: Default::default(),
4577 }
4578 }
4579 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4581 let this = self.clone();
4582
4583 window.on_next_frame(move |_, _| {
4584 let viewport_bounds = this.handle.bounds();
4585 let self_bounds = *this.last_origin.borrow();
4586 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4587 });
4588 }
4589}
4590
4591#[derive(Default, Debug)]
4592struct ScrollHandleState {
4593 offset: Rc<RefCell<Point<Pixels>>>,
4594 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4595 bounds: Bounds<Pixels>,
4596 max_offset: Point<Pixels>,
4597 child_bounds: Vec<Bounds<Pixels>>,
4598 scroll_to_bottom: bool,
4599 overflow: Point<Overflow>,
4600 active_item: Option<ScrollActiveItem>,
4601}
4602
4603#[derive(Default, Debug, Clone, Copy)]
4604struct ScrollActiveItem {
4605 index: usize,
4606 strategy: ScrollStrategy,
4607}
4608
4609#[derive(Default, Debug, Clone, Copy)]
4610enum ScrollStrategy {
4611 #[default]
4612 FirstVisible,
4613 Top,
4614}
4615
4616#[derive(Clone, Debug)]
4620pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4621
4622impl Default for ScrollHandle {
4623 fn default() -> Self {
4624 Self::new()
4625 }
4626}
4627
4628impl ScrollHandle {
4629 pub fn new() -> Self {
4631 Self(Rc::default())
4632 }
4633
4634 pub fn offset(&self) -> Point<Pixels> {
4636 *self.0.borrow().offset.borrow()
4637 }
4638
4639 pub fn max_offset(&self) -> Point<Pixels> {
4641 self.0.borrow().max_offset
4642 }
4643
4644 pub fn top_item(&self) -> usize {
4646 let state = self.0.borrow();
4647 let top = state.bounds.top() - state.offset.borrow().y;
4648
4649 match state.child_bounds.binary_search_by(|bounds| {
4650 if top < bounds.top() {
4651 Ordering::Greater
4652 } else if top > bounds.bottom() {
4653 Ordering::Less
4654 } else {
4655 Ordering::Equal
4656 }
4657 }) {
4658 Ok(ix) => ix,
4659 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4660 }
4661 }
4662
4663 pub fn bottom_item(&self) -> usize {
4665 let state = self.0.borrow();
4666 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4667
4668 match state.child_bounds.binary_search_by(|bounds| {
4669 if bottom < bounds.top() {
4670 Ordering::Greater
4671 } else if bottom > bounds.bottom() {
4672 Ordering::Less
4673 } else {
4674 Ordering::Equal
4675 }
4676 }) {
4677 Ok(ix) => ix,
4678 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4679 }
4680 }
4681
4682 pub fn bounds(&self) -> Bounds<Pixels> {
4684 self.0.borrow().bounds
4685 }
4686
4687 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4689 self.0.borrow().child_bounds.get(ix).cloned()
4690 }
4691
4692 pub fn scroll_to_item(&self, ix: usize) {
4694 let mut state = self.0.borrow_mut();
4695 state.active_item = Some(ScrollActiveItem {
4696 index: ix,
4697 strategy: ScrollStrategy::default(),
4698 });
4699 }
4700
4701 pub fn scroll_to_top_of_item(&self, ix: usize) {
4704 let mut state = self.0.borrow_mut();
4705 state.active_item = Some(ScrollActiveItem {
4706 index: ix,
4707 strategy: ScrollStrategy::Top,
4708 });
4709 }
4710
4711 fn scroll_to_active_item(&self) {
4715 let mut state = self.0.borrow_mut();
4716
4717 let Some(active_item) = state.active_item else {
4718 return;
4719 };
4720
4721 let active_item = match state.child_bounds.get(active_item.index) {
4722 Some(bounds) => {
4723 let mut scroll_offset = state.offset.borrow_mut();
4724
4725 match active_item.strategy {
4726 ScrollStrategy::FirstVisible => {
4727 if state.overflow.y == Overflow::Scroll {
4728 let child_height = bounds.size.height;
4729 let viewport_height = state.bounds.size.height;
4730 if child_height > viewport_height {
4731 scroll_offset.y = state.bounds.top() - bounds.top();
4732 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4733 scroll_offset.y = state.bounds.top() - bounds.top();
4734 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4735 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4736 }
4737 }
4738 }
4739 ScrollStrategy::Top => {
4740 scroll_offset.y = state.bounds.top() - bounds.top();
4741 }
4742 }
4743
4744 if state.overflow.x == Overflow::Scroll {
4745 let child_width = bounds.size.width;
4746 let viewport_width = state.bounds.size.width;
4747 if child_width > viewport_width {
4748 scroll_offset.x = state.bounds.left() - bounds.left();
4749 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4750 scroll_offset.x = state.bounds.left() - bounds.left();
4751 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4752 scroll_offset.x = state.bounds.right() - bounds.right();
4753 }
4754 }
4755 None
4756 }
4757 None => Some(active_item),
4758 };
4759 state.active_item = active_item;
4760 }
4761
4762 pub fn scroll_to_bottom(&self) {
4764 let mut state = self.0.borrow_mut();
4765 state.scroll_to_bottom = true;
4766 }
4767
4768 pub fn set_offset(&self, position: Point<Pixels>) {
4772 let state = self.0.borrow();
4773 *state.offset.borrow_mut() = position;
4774 }
4775
4776 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4778 let ix = self.top_item();
4779 let state = self.0.borrow();
4780
4781 if let Some(child_bounds) = state.child_bounds.get(ix) {
4782 (
4783 ix,
4784 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4785 )
4786 } else {
4787 (ix, px(0.))
4788 }
4789 }
4790
4791 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4793 let ix = self.bottom_item();
4794 let state = self.0.borrow();
4795
4796 if let Some(child_bounds) = state.child_bounds.get(ix) {
4797 (
4798 ix,
4799 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4800 )
4801 } else {
4802 (ix, px(0.))
4803 }
4804 }
4805
4806 pub fn children_count(&self) -> usize {
4808 self.0.borrow().child_bounds.len()
4809 }
4810}
4811
4812#[cfg(test)]
4813mod tests {
4814 use super::*;
4815 use crate::{
4816 AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, IntoElement,
4817 Keystroke, MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas,
4818 util::FluentBuilder as _,
4819 };
4820 use std::{cell::Cell, rc::Weak};
4821
4822 struct GroupHoverTestView {
4823 render_count: Rc<Cell<usize>>,
4824 anonymous_paint_count: Rc<Cell<usize>>,
4825 stateful_width: Rc<Cell<Pixels>>,
4826 }
4827
4828 impl Render for GroupHoverTestView {
4829 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4830 self.render_count.set(self.render_count.get() + 1);
4831 let anonymous_paint_count = self.anonymous_paint_count.clone();
4832 let stateful_width = self.stateful_width.clone();
4833 div().size_full().child(
4834 div()
4835 .ml(px(20.))
4836 .mt(px(20.))
4837 .size(px(50.))
4838 .relative()
4839 .group("hover-group")
4840 .child(
4841 div()
4842 .absolute()
4843 .size_full()
4844 .invisible()
4845 .group_hover("hover-group", |style| style.visible())
4846 .child(canvas(
4847 |_, _, _| {},
4848 move |_, _, _, _| {
4849 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4850 },
4851 )),
4852 )
4853 .child(
4854 div()
4855 .id("stateful-group-hover-target")
4856 .absolute()
4857 .top_0()
4858 .left_0()
4859 .size(px(10.))
4860 .group_hover("hover-group", |style| style.size(px(20.)))
4861 .child(canvas(
4862 move |bounds, _, _| stateful_width.set(bounds.size.width),
4863 |_, _, _, _| {},
4864 )),
4865 ),
4866 )
4867 }
4868 }
4869
4870 #[gpui::test]
4871 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4872 let render_count = Rc::new(Cell::new(0));
4873 let anonymous_paint_count = Rc::new(Cell::new(0));
4874 let stateful_width = Rc::new(Cell::new(px(0.)));
4875 let window = cx.add_window({
4876 let render_count = render_count.clone();
4877 let anonymous_paint_count = anonymous_paint_count.clone();
4878 let stateful_width = stateful_width.clone();
4879 move |_, _| GroupHoverTestView {
4880 render_count,
4881 anonymous_paint_count,
4882 stateful_width,
4883 }
4884 });
4885 let window = AnyWindowHandle::from(window);
4886
4887 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4888 .unwrap();
4889 assert_eq!(anonymous_paint_count.get(), 0);
4890 assert_eq!(stateful_width.get(), px(10.));
4891
4892 let move_mouse = |cx: &mut TestAppContext, position| {
4893 cx.update_window(window, |_, window, cx| {
4894 window.simulate_mouse_move(position, cx)
4895 })
4896 .unwrap();
4897 };
4898
4899 let initial_render_count = render_count.get();
4900 move_mouse(cx, point(px(25.), px(25.)));
4901 assert_eq!(render_count.get(), initial_render_count + 1);
4902 assert_eq!(anonymous_paint_count.get(), 1);
4903 assert_eq!(stateful_width.get(), px(20.));
4904
4905 move_mouse(cx, point(px(30.), px(30.)));
4906 assert_eq!(render_count.get(), initial_render_count + 1);
4907 assert_eq!(anonymous_paint_count.get(), 1);
4908 assert_eq!(stateful_width.get(), px(20.));
4909
4910 move_mouse(cx, point(px(5.), px(5.)));
4911 assert_eq!(render_count.get(), initial_render_count + 2);
4912 assert_eq!(anonymous_paint_count.get(), 1);
4913 assert_eq!(stateful_width.get(), px(10.));
4914
4915 move_mouse(cx, point(px(10.), px(10.)));
4916 assert_eq!(render_count.get(), initial_render_count + 2);
4917 assert_eq!(anonymous_paint_count.get(), 1);
4918 assert_eq!(stateful_width.get(), px(10.));
4919 }
4920
4921 struct GroupHoverDisplayTestView {
4924 group_left: Pixels,
4925 frames: Rc<RefCell<Vec<(bool, Option<Pixels>, bool)>>>,
4928 }
4929
4930 impl Render for GroupHoverDisplayTestView {
4931 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4932 self.frames.borrow_mut().push((true, None, false));
4933 let prepainted = self.frames.clone();
4934 let painted = self.frames.clone();
4935 div().relative().size_full().child(
4936 div()
4937 .id("display-group")
4938 .absolute()
4939 .left(self.group_left)
4940 .top_0()
4941 .size(px(20.))
4942 .group("display-group")
4943 .child(
4944 div()
4945 .id("display-target")
4946 .hidden()
4947 .w(px(12.))
4948 .h(px(8.))
4949 .group_hover("display-group", |style| style.flex())
4950 .child(
4951 canvas(
4952 move |bounds, _, _| {
4953 if let Some(frame) = prepainted.borrow_mut().last_mut() {
4954 frame.1 = Some(bounds.size.width);
4955 }
4956 },
4957 move |_, _, _, _| {
4958 if let Some(frame) = painted.borrow_mut().last_mut() {
4959 frame.2 = true;
4960 }
4961 },
4962 )
4963 .size_full(),
4964 ),
4965 ),
4966 )
4967 }
4968 }
4969
4970 #[gpui::test]
4976 fn group_hover_that_shows_a_hidden_box_under_a_stationary_pointer(cx: &mut TestAppContext) {
4977 let frames = Rc::new(RefCell::new(Vec::new()));
4978 let window = cx.add_window({
4979 let frames = frames.clone();
4980 move |_, _| GroupHoverDisplayTestView {
4981 group_left: px(40.),
4982 frames,
4983 }
4984 });
4985 let any_window = AnyWindowHandle::from(window);
4986 let frames_since = |mark: usize| frames.borrow()[mark..].to_vec();
4989
4990 cx.update_window(any_window, |_, window, cx| {
4991 window.draw(cx).clear(cx);
4992 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4993 })
4994 .unwrap();
4995 assert!(
4996 frames
4997 .borrow()
4998 .iter()
4999 .all(|frame| frame.1.is_none() && !frame.2),
5000 "the group is not under the pointer"
5001 );
5002
5003 let mark = frames.borrow().len();
5006 window
5007 .update(cx, |view, _, cx| {
5008 view.group_left = px(0.);
5009 cx.notify();
5010 })
5011 .unwrap();
5012 assert_eq!(
5013 frames_since(mark),
5014 [
5015 (true, None, false),
5018 (true, Some(px(12.)), true),
5021 ]
5022 );
5023
5024 let mark = frames.borrow().len();
5028 window
5029 .update(cx, |view, _, cx| {
5030 view.group_left = px(40.);
5031 cx.notify();
5032 })
5033 .unwrap();
5034 assert_eq!(
5035 frames_since(mark),
5036 [(true, Some(px(12.)), false), (true, None, false)]
5037 );
5038 }
5039
5040 struct HoverListenerLayoutTestView {
5041 target_left: Pixels,
5042 hover_transitions: Rc<RefCell<Vec<bool>>>,
5043 }
5044
5045 impl Render for HoverListenerLayoutTestView {
5046 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5047 let hover_transitions = self.hover_transitions.clone();
5048 div().relative().size_full().child(
5049 div()
5050 .id("hover-target")
5051 .absolute()
5052 .left(self.target_left)
5053 .top_0()
5054 .size(px(20.))
5055 .on_click(|_, _, _| {})
5056 .on_hover(move |is_hovered, _, _| {
5057 hover_transitions.borrow_mut().push(*is_hovered);
5058 }),
5059 )
5060 }
5061 }
5062
5063 #[gpui::test]
5064 fn default_hover_listener_updates_when_layout_changes_under_stationary_mouse(
5065 cx: &mut TestAppContext,
5066 ) {
5067 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
5068 let window = cx.add_window({
5069 let hover_transitions = hover_transitions.clone();
5070 move |_, _| HoverListenerLayoutTestView {
5071 target_left: px(40.),
5072 hover_transitions,
5073 }
5074 });
5075 let any_window = AnyWindowHandle::from(window);
5076
5077 cx.update_window(any_window, |_, window, cx| {
5078 window.draw(cx).clear(cx);
5079 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
5080 })
5081 .unwrap();
5082 assert!(hover_transitions.borrow().is_empty());
5083
5084 window
5085 .update(cx, |view, _, cx| {
5086 view.target_left = px(0.);
5087 cx.notify();
5088 })
5089 .unwrap();
5090 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5091 .unwrap();
5092 assert_eq!(*hover_transitions.borrow(), [true]);
5093
5094 window
5095 .update(cx, |view, _, cx| {
5096 view.target_left = px(40.);
5097 cx.notify();
5098 })
5099 .unwrap();
5100 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5101 .unwrap();
5102 assert_eq!(*hover_transitions.borrow(), [true, false]);
5103 }
5104
5105 #[gpui::test]
5106 fn default_hover_listener_ends_after_key_press(cx: &mut TestAppContext) {
5107 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
5108 let window = cx.add_window({
5109 let hover_transitions = hover_transitions.clone();
5110 move |_, _| HoverListenerLayoutTestView {
5111 target_left: px(0.),
5112 hover_transitions,
5113 }
5114 });
5115 let any_window = AnyWindowHandle::from(window);
5116
5117 cx.update_window(any_window, |_, window, cx| {
5118 window.draw(cx).clear(cx);
5119 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
5120 })
5121 .unwrap();
5122 assert_eq!(*hover_transitions.borrow(), [true]);
5123
5124 key_down(cx, any_window, "a");
5125 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5126 .unwrap();
5127 assert_eq!(*hover_transitions.borrow(), [true, false]);
5128 }
5129
5130 struct HoverListenerModeLayoutTestView {
5131 target_left: Pixels,
5132 hover_transitions: Rc<RefCell<Vec<bool>>>,
5133 }
5134
5135 impl Render for HoverListenerModeLayoutTestView {
5136 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5137 let hover_transitions = self.hover_transitions.clone();
5138 div().relative().size_full().child(
5139 div()
5140 .id("hover-target")
5141 .absolute()
5142 .left(self.target_left)
5143 .top_0()
5144 .size(px(20.))
5145 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
5146 .on_hover(move |is_hovered, _, _| {
5147 hover_transitions.borrow_mut().push(*is_hovered);
5148 }),
5149 )
5150 }
5151 }
5152
5153 #[gpui::test]
5154 fn input_modality_independent_hover_listener_updates_after_key_press(cx: &mut TestAppContext) {
5155 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
5156 let window = cx.add_window({
5157 let hover_transitions = hover_transitions.clone();
5158 move |_, _| HoverListenerModeLayoutTestView {
5159 target_left: px(40.),
5160 hover_transitions,
5161 }
5162 });
5163 let any_window = AnyWindowHandle::from(window);
5164 let pointer_position = point(px(10.), px(10.));
5165
5166 cx.update_window(any_window, |_, window, cx| {
5167 window.draw(cx).clear(cx);
5168 window.simulate_mouse_move(pointer_position, cx);
5169 })
5170 .unwrap();
5171 assert!(hover_transitions.borrow().is_empty());
5172
5173 key_down(cx, any_window, "a");
5174 window
5175 .update(cx, |view, _, cx| {
5176 view.target_left = px(0.);
5177 cx.notify();
5178 })
5179 .unwrap();
5180 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5181 .unwrap();
5182 assert_eq!(*hover_transitions.borrow(), [true]);
5183
5184 key_down(cx, any_window, "b");
5185 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
5186 .unwrap();
5187 assert_eq!(*hover_transitions.borrow(), [true]);
5188
5189 cx.update_window(any_window, |_, window, cx| {
5190 window.simulate_mouse_move(point(px(30.), px(10.)), cx);
5191 })
5192 .unwrap();
5193 assert_eq!(*hover_transitions.borrow(), [true, false]);
5194
5195 cx.update_window(any_window, |_, window, cx| {
5196 window.simulate_mouse_move(pointer_position, cx);
5197 window.dispatch_event(
5198 MouseExitEvent {
5199 position: pointer_position,
5200 ..Default::default()
5201 }
5202 .to_platform_input(),
5203 cx,
5204 );
5205 })
5206 .unwrap();
5207 assert_eq!(*hover_transitions.borrow(), [true, false, true, false]);
5208 }
5209
5210 #[gpui::test]
5211 fn default_hover_listener_remains_hovered_during_stationary_mouse_press(
5212 cx: &mut TestAppContext,
5213 ) {
5214 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
5215 let window = cx.add_window({
5216 let hover_transitions = hover_transitions.clone();
5217 move |_, _| HoverListenerLayoutTestView {
5218 target_left: px(0.),
5219 hover_transitions,
5220 }
5221 });
5222 let any_window = AnyWindowHandle::from(window);
5223 let mouse_position = point(px(10.), px(10.));
5224
5225 cx.update_window(any_window, |_, window, cx| {
5226 window.draw(cx).clear(cx);
5227 window.simulate_mouse_move(mouse_position, cx);
5228 })
5229 .unwrap();
5230 assert_eq!(*hover_transitions.borrow(), [true]);
5231
5232 cx.update_window(any_window, |_, window, cx| {
5233 window.dispatch_event(
5234 MouseDownEvent {
5235 position: mouse_position,
5236 button: MouseButton::Left,
5237 modifiers: Default::default(),
5238 click_count: 1,
5239 first_mouse: false,
5240 }
5241 .to_platform_input(),
5242 cx,
5243 );
5244 window.draw(cx).clear(cx);
5245 })
5246 .unwrap();
5247 assert_eq!(*hover_transitions.borrow(), [true]);
5248
5249 cx.update_window(any_window, |_, window, cx| {
5250 window.dispatch_event(
5251 MouseUpEvent {
5252 position: mouse_position,
5253 button: MouseButton::Left,
5254 modifiers: Default::default(),
5255 click_count: 1,
5256 }
5257 .to_platform_input(),
5258 cx,
5259 );
5260 window.draw(cx).clear(cx);
5261 })
5262 .unwrap();
5263 assert_eq!(*hover_transitions.borrow(), [true]);
5264 }
5265
5266 struct TestTooltipView;
5267
5268 impl Render for TestTooltipView {
5269 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5270 div().w(px(20.)).h(px(20.)).child("tooltip")
5271 }
5272 }
5273
5274 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
5275
5276 struct TooltipCaptureElement {
5277 child: AnyElement,
5278 captured_active_tooltip: CapturedActiveTooltip,
5279 }
5280
5281 impl Element for TooltipCaptureElement {
5282 type RequestLayoutState = ();
5283 type PrepaintState = ();
5284
5285 fn id(&self) -> Option<ElementId> {
5286 None
5287 }
5288
5289 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
5290 None
5291 }
5292
5293 fn request_layout(
5294 &mut self,
5295 _id: Option<&GlobalElementId>,
5296 _inspector_id: Option<&InspectorElementId>,
5297 window: &mut Window,
5298 cx: &mut App,
5299 ) -> (LayoutId, Self::RequestLayoutState) {
5300 (self.child.request_layout(window, cx), ())
5301 }
5302
5303 fn prepaint(
5304 &mut self,
5305 _id: Option<&GlobalElementId>,
5306 _inspector_id: Option<&InspectorElementId>,
5307 _bounds: Bounds<Pixels>,
5308 _request_layout: &mut Self::RequestLayoutState,
5309 window: &mut Window,
5310 cx: &mut App,
5311 ) -> Self::PrepaintState {
5312 self.child.prepaint(window, cx);
5313 }
5314
5315 fn paint(
5316 &mut self,
5317 _id: Option<&GlobalElementId>,
5318 _inspector_id: Option<&InspectorElementId>,
5319 _bounds: Bounds<Pixels>,
5320 _request_layout: &mut Self::RequestLayoutState,
5321 _prepaint: &mut Self::PrepaintState,
5322 window: &mut Window,
5323 cx: &mut App,
5324 ) {
5325 self.child.paint(window, cx);
5326 window.with_global_id("target".into(), |global_id, window| {
5327 window.with_element_state::<InteractiveElementState, _>(
5328 global_id,
5329 |state, _window| {
5330 let state = state.unwrap();
5331 *self.captured_active_tooltip.borrow_mut() =
5332 state.active_tooltip.as_ref().map(Rc::downgrade);
5333 ((), state)
5334 },
5335 )
5336 });
5337 }
5338 }
5339
5340 struct TooltipOwner {
5341 captured_active_tooltip: CapturedActiveTooltip,
5342 show_delay_override: Option<Duration>,
5343 }
5344
5345 impl Render for TooltipOwner {
5346 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5347 TooltipCaptureElement {
5348 child: div()
5349 .size_full()
5350 .child(
5351 div()
5352 .id("target")
5353 .w(px(50.))
5354 .h(px(50.))
5355 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
5356 .when_some(self.show_delay_override, |this, delay| {
5357 this.tooltip_show_delay(delay)
5358 }),
5359 )
5360 .into_any_element(),
5361 captured_active_tooltip: self.captured_active_tooltip.clone(),
5362 }
5363 }
5364 }
5365
5366 #[test]
5367 fn scroll_handle_aligns_wide_children_to_left_edge() {
5368 let handle = ScrollHandle::new();
5369 {
5370 let mut state = handle.0.borrow_mut();
5371 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
5372 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
5373 state.overflow.x = Overflow::Scroll;
5374 state.active_item = Some(ScrollActiveItem {
5375 index: 0,
5376 strategy: ScrollStrategy::default(),
5377 });
5378 }
5379
5380 handle.scroll_to_active_item();
5381
5382 assert_eq!(handle.offset().x, px(-25.));
5383 }
5384
5385 #[test]
5386 fn scroll_handle_aligns_tall_children_to_top_edge() {
5387 let handle = ScrollHandle::new();
5388 {
5389 let mut state = handle.0.borrow_mut();
5390 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
5391 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
5392 state.overflow.y = Overflow::Scroll;
5393 state.active_item = Some(ScrollActiveItem {
5394 index: 0,
5395 strategy: ScrollStrategy::default(),
5396 });
5397 }
5398
5399 handle.scroll_to_active_item();
5400
5401 assert_eq!(handle.offset().y, px(-25.));
5402 }
5403
5404 #[test]
5405 fn long_press_shows_tooltip_until_touch_ends() {
5406 let (mut test_app, any_window, captured_active_tooltip) = create_tooltip_owner_test(None);
5407 let active_tooltip = captured_active_tooltip
5408 .borrow()
5409 .clone()
5410 .unwrap()
5411 .upgrade()
5412 .unwrap();
5413 let touch_id = TouchId(1);
5414 let touch_position = point(px(49.), px(10.));
5415
5416 test_app
5417 .update_window(any_window, |_, window, cx| {
5418 window.dispatch_event(
5419 TouchEvent {
5420 id: touch_id,
5421 phase: TouchPhase::Started,
5422 position: touch_position,
5423 predicted_position: None,
5424 force: None,
5425 }
5426 .to_platform_input(),
5427 cx,
5428 );
5429 })
5430 .unwrap();
5431 test_app
5432 .dispatcher
5433 .advance_clock(GestureTuning::default().long_press_duration + Duration::from_millis(1));
5434 test_app.run_until_parked();
5435
5436 assert!(matches!(
5437 active_tooltip.borrow().as_ref(),
5438 Some(ActiveTooltip::Visible { .. })
5439 ));
5440
5441 let moved_position = point(px(55.), px(10.));
5442 test_app
5443 .update_window(any_window, |_, window, cx| {
5444 window.dispatch_event(
5445 TouchEvent {
5446 id: touch_id,
5447 phase: TouchPhase::Moved,
5448 position: moved_position,
5449 predicted_position: None,
5450 force: None,
5451 }
5452 .to_platform_input(),
5453 cx,
5454 );
5455 window.draw(cx).clear(cx);
5456 })
5457 .unwrap();
5458 assert!(matches!(
5459 active_tooltip.borrow().as_ref(),
5460 Some(ActiveTooltip::Visible { .. })
5461 ));
5462
5463 test_app
5464 .update_window(any_window, |_, window, cx| {
5465 window.dispatch_event(
5466 TouchEvent {
5467 id: touch_id,
5468 phase: TouchPhase::Ended,
5469 position: moved_position,
5470 predicted_position: None,
5471 force: None,
5472 }
5473 .to_platform_input(),
5474 cx,
5475 );
5476 })
5477 .unwrap();
5478
5479 assert!(active_tooltip.borrow().is_none());
5480 }
5481
5482 fn setup_tooltip_owner_test(
5483 show_delay_override: Option<Duration>,
5484 ) -> (
5485 TestAppContext,
5486 crate::AnyWindowHandle,
5487 CapturedActiveTooltip,
5488 ) {
5489 let (mut test_app, any_window, captured_active_tooltip) =
5490 create_tooltip_owner_test(show_delay_override);
5491
5492 test_app
5493 .update_window(any_window, |_, window, cx| {
5494 window.dispatch_event(
5495 MouseMoveEvent {
5496 position: point(px(10.), px(10.)),
5497 modifiers: Default::default(),
5498 pressed_button: None,
5499 }
5500 .to_platform_input(),
5501 cx,
5502 );
5503 })
5504 .unwrap();
5505
5506 test_app
5507 .update_window(any_window, |_, window, cx| {
5508 window.draw(cx).clear(cx);
5509 })
5510 .unwrap();
5511
5512 (test_app, any_window, captured_active_tooltip)
5513 }
5514
5515 fn create_tooltip_owner_test(
5516 show_delay_override: Option<Duration>,
5517 ) -> (
5518 TestAppContext,
5519 crate::AnyWindowHandle,
5520 CapturedActiveTooltip,
5521 ) {
5522 let mut test_app = TestAppContext::single();
5523 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
5524 let window = test_app.add_window({
5525 let captured_active_tooltip = captured_active_tooltip.clone();
5526 move |_, _| TooltipOwner {
5527 captured_active_tooltip,
5528 show_delay_override,
5529 }
5530 });
5531 let any_window = window.into();
5532
5533 test_app
5534 .update_window(any_window, |_, window, cx| {
5535 window.draw(cx).clear(cx);
5536 })
5537 .unwrap();
5538
5539 (test_app, any_window, captured_active_tooltip)
5540 }
5541
5542 #[test]
5543 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
5544 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5545
5546 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5547 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5548 assert!(matches!(
5549 active_tooltip.borrow().as_ref(),
5550 Some(ActiveTooltip::WaitingForShow { .. })
5551 ));
5552
5553 test_app
5554 .update_window(any_window, |_, window, _| {
5555 window.remove_window();
5556 })
5557 .unwrap();
5558 test_app.run_until_parked();
5559 drop(active_tooltip);
5560
5561 assert!(weak_active_tooltip.upgrade().is_none());
5562 }
5563
5564 #[test]
5565 fn tooltip_respects_custom_show_delay() {
5566 let extra_delay = Duration::from_secs(1);
5567 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
5568 let (test_app, _any_window, captured_active_tooltip) =
5569 setup_tooltip_owner_test(Some(show_delay_override));
5570
5571 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5572 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5573
5574 test_app
5575 .dispatcher
5576 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5577 test_app.run_until_parked();
5578
5579 assert!(matches!(
5580 active_tooltip.borrow().as_ref(),
5581 Some(ActiveTooltip::WaitingForShow { .. })
5582 ));
5583
5584 test_app.dispatcher.advance_clock(extra_delay);
5585 test_app.run_until_parked();
5586
5587 assert!(matches!(
5588 active_tooltip.borrow().as_ref(),
5589 Some(ActiveTooltip::Visible { .. })
5590 ));
5591 }
5592
5593 #[test]
5594 fn tooltip_is_released_when_its_owner_disappears() {
5595 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5596
5597 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5598 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5599
5600 test_app
5601 .dispatcher
5602 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5603 test_app.run_until_parked();
5604
5605 assert!(matches!(
5606 active_tooltip.borrow().as_ref(),
5607 Some(ActiveTooltip::Visible { .. })
5608 ));
5609
5610 test_app
5611 .update_window(any_window, |_, window, _| {
5612 window.remove_window();
5613 })
5614 .unwrap();
5615 test_app.run_until_parked();
5616 drop(active_tooltip);
5617
5618 assert!(weak_active_tooltip.upgrade().is_none());
5619 }
5620
5621 #[test]
5622 fn tooltip_hides_after_mouse_leaves_origin() {
5623 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5624
5625 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5626 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5627
5628 test_app
5629 .dispatcher
5630 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5631 test_app.run_until_parked();
5632
5633 assert!(matches!(
5634 active_tooltip.borrow().as_ref(),
5635 Some(ActiveTooltip::Visible { .. })
5636 ));
5637
5638 test_app
5639 .update_window(any_window, |_, window, cx| {
5640 window.dispatch_event(
5641 MouseMoveEvent {
5642 position: point(px(75.), px(75.)),
5643 modifiers: Default::default(),
5644 pressed_button: None,
5645 }
5646 .to_platform_input(),
5647 cx,
5648 );
5649 })
5650 .unwrap();
5651
5652 assert!(active_tooltip.borrow().is_none());
5653 }
5654
5655 struct MouseDownOutOwner {
5656 mouse_down_out_count: Rc<RefCell<usize>>,
5657 }
5658
5659 impl Render for MouseDownOutOwner {
5660 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5661 let mouse_down_out_count = self.mouse_down_out_count.clone();
5662 div()
5663 .size_full()
5664 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
5665 move |_, _, _| {
5666 *mouse_down_out_count.borrow_mut() += 1;
5667 },
5668 ))
5669 }
5670 }
5671
5672 #[test]
5673 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
5674 let mut test_app = TestAppContext::single();
5675 let mouse_down_out_count = Rc::new(RefCell::new(0));
5676 let window = test_app.add_window({
5677 let mouse_down_out_count = mouse_down_out_count.clone();
5678 move |_, _| MouseDownOutOwner {
5679 mouse_down_out_count,
5680 }
5681 });
5682 let any_window: AnyWindowHandle = window.into();
5683
5684 fn dispatch_mouse_down_outside_target(
5685 test_app: &mut TestAppContext,
5686 any_window: AnyWindowHandle,
5687 ) {
5688 test_app
5689 .update_window(any_window, |_, window, cx| {
5690 window.dispatch_event(
5691 MouseDownEvent {
5692 position: point(px(75.), px(75.)),
5693 button: MouseButton::Left,
5694 modifiers: Default::default(),
5695 click_count: 1,
5696 first_mouse: false,
5697 }
5698 .to_platform_input(),
5699 cx,
5700 );
5701 })
5702 .unwrap();
5703 }
5704
5705 test_app
5706 .update_window(any_window, |_, window, cx| {
5707 window.draw(cx).clear(cx);
5708 })
5709 .unwrap();
5710
5711 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5712 assert_eq!(
5713 *mouse_down_out_count.borrow(),
5714 1,
5715 "mouse down outside the element should fire mouse-down-out listeners"
5716 );
5717
5718 test_app
5719 .update_window(any_window, |_, window, cx| {
5720 cx.set_prompt_builder(crate::fallback_prompt_renderer);
5721 let _receiver =
5722 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
5723 assert!(window.has_active_prompt());
5724 window.draw(cx).clear(cx);
5725 })
5726 .unwrap();
5727
5728 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5729 assert_eq!(
5730 *mouse_down_out_count.borrow(),
5731 1,
5732 "mouse down over an active prompt should not fire mouse-down-out listeners"
5733 );
5734 }
5735
5736 #[test]
5737 fn touch_tap_out_fires_once_after_release() {
5738 let mut test_app = TestAppContext::single();
5739 let mouse_down_out_count = Rc::new(RefCell::new(0));
5740 let window = test_app.add_window({
5741 let mouse_down_out_count = mouse_down_out_count.clone();
5742 move |_, _| MouseDownOutOwner {
5743 mouse_down_out_count,
5744 }
5745 });
5746 let any_window: AnyWindowHandle = window.into();
5747
5748 test_app
5749 .update_window(any_window, |_, window, cx| {
5750 window.draw(cx).clear(cx);
5751 let started = TouchEvent {
5752 id: TouchId(1),
5753 phase: TouchPhase::Started,
5754 position: point(px(75.), px(75.)),
5755 force: None,
5756 predicted_position: None,
5757 };
5758 window.dispatch_event(started.clone().to_platform_input(), cx);
5759 assert_eq!(*mouse_down_out_count.borrow(), 0);
5760 window.dispatch_event(
5761 TouchEvent {
5762 phase: TouchPhase::Ended,
5763 ..started
5764 }
5765 .to_platform_input(),
5766 cx,
5767 );
5768 })
5769 .unwrap();
5770
5771 assert_eq!(
5772 *mouse_down_out_count.borrow(),
5773 1,
5774 "a touch tap outside the element should use mouse-down-out listeners"
5775 );
5776 }
5777
5778 #[crate::test]
5779 fn touch_pan_and_cancel_do_not_fire_mouse_down_out(cx: &mut TestAppContext) {
5780 let mouse_down_out_count = Rc::new(RefCell::new(0));
5781 let window = cx.add_window({
5782 let mouse_down_out_count = mouse_down_out_count.clone();
5783 move |_, _| MouseDownOutOwner {
5784 mouse_down_out_count,
5785 }
5786 });
5787 cx.update_window(window.into(), |_, window, cx| {
5788 window.draw(cx).clear(cx);
5789 for (id, samples) in [
5790 (
5791 TouchId(1),
5792 [
5793 (TouchPhase::Started, 100.),
5794 (TouchPhase::Moved, 75.),
5795 (TouchPhase::Ended, 75.),
5796 ],
5797 ),
5798 (
5799 TouchId(2),
5800 [
5801 (TouchPhase::Started, 100.),
5802 (TouchPhase::Moved, 100.),
5803 (TouchPhase::Cancelled, 100.),
5804 ],
5805 ),
5806 ] {
5807 for (phase, vertical_position) in samples {
5808 window.dispatch_event(
5809 TouchEvent {
5810 id,
5811 phase,
5812 position: point(px(75.), px(vertical_position)),
5813 predicted_position: None,
5814 force: None,
5815 }
5816 .to_platform_input(),
5817 cx,
5818 );
5819 }
5820 }
5821 })
5822 .unwrap();
5823 assert_eq!(*mouse_down_out_count.borrow(), 0);
5824 }
5825
5826 #[test]
5827 fn test_accessibility_id_builder_writes_author_id() {
5828 let mut element = div()
5829 .id("buffer-font-size")
5830 .accessibility_id("settings.buffer-font-size");
5831 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5832
5833 element.interactivity().write_a11y_info(&mut node);
5834
5835 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5836 }
5837
5838 #[test]
5839 fn test_write_a11y_info_string_and_numeric_properties() {
5840 let mut interactivity = Interactivity::default();
5841 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
5842 interactivity.aria.label = Some("Buffer Font Size".into());
5843 interactivity.aria.value = Some("15".into());
5844 interactivity.aria.placeholder = Some("Search".into());
5845 interactivity.aria.numeric_value = Some(15.0);
5846 interactivity.aria.min_numeric_value = Some(6.0);
5847 interactivity.aria.max_numeric_value = Some(72.0);
5848 interactivity.aria.numeric_value_step = Some(1.0);
5849
5850 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5851 interactivity.write_a11y_info(&mut node);
5852
5853 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5854 assert_eq!(node.label(), Some("Buffer Font Size"));
5855 assert_eq!(node.value(), Some("15"));
5856 assert_eq!(node.placeholder(), Some("Search"));
5857 assert_eq!(node.numeric_value(), Some(15.0));
5858 assert_eq!(node.min_numeric_value(), Some(6.0));
5859 assert_eq!(node.max_numeric_value(), Some(72.0));
5860 assert_eq!(node.numeric_value_step(), Some(1.0));
5861 }
5862
5863 struct KeyboardActivationTest {
5866 focus_a: FocusHandle,
5867 focus_b: FocusHandle,
5868 clicks: Rc<RefCell<Vec<&'static str>>>,
5869 }
5870
5871 impl Render for KeyboardActivationTest {
5872 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5873 let clicks_a = self.clicks.clone();
5874 let clicks_b = self.clicks.clone();
5875 div()
5876 .size_full()
5877 .child(
5878 div()
5879 .id("a")
5880 .w(px(50.))
5881 .h(px(50.))
5882 .track_focus(&self.focus_a)
5883 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
5884 )
5885 .child(
5886 div()
5887 .id("b")
5888 .w(px(50.))
5889 .h(px(50.))
5890 .track_focus(&self.focus_b)
5891 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
5892 )
5893 }
5894 }
5895
5896 fn setup_keyboard_activation_test() -> (
5897 TestAppContext,
5898 AnyWindowHandle,
5899 Rc<RefCell<Vec<&'static str>>>,
5900 FocusHandle,
5901 FocusHandle,
5902 ) {
5903 let mut cx = TestAppContext::single();
5904 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
5905 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
5906 let window = cx.add_window({
5907 let focus_a = focus_a.clone();
5908 let focus_b = focus_b.clone();
5909 let clicks = clicks.clone();
5910 move |_, _| KeyboardActivationTest {
5911 focus_a,
5912 focus_b,
5913 clicks,
5914 }
5915 });
5916 (cx, window.into(), clicks, focus_a, focus_b)
5917 }
5918
5919 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
5922 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
5923 .unwrap();
5924 cx.run_until_parked();
5925 cx.update_window(window, |_, window, cx| {
5926 window.draw(cx).clear(cx);
5927 })
5928 .unwrap();
5929 }
5930
5931 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5932 let os = cx.read(|cx| cx.platform_info().os);
5933 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5934 cx.update_window(window, |_, window, cx| {
5935 window.dispatch_event(
5936 KeyDownEvent {
5937 keystroke,
5938 is_held: false,
5939 prefer_character_input: false,
5940 }
5941 .to_platform_input(),
5942 cx,
5943 );
5944 })
5945 .unwrap();
5946 }
5947
5948 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5949 let os = cx.read(|cx| cx.platform_info().os);
5950 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5951 cx.update_window(window, |_, window, cx| {
5952 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
5953 })
5954 .unwrap();
5955 }
5956
5957 #[test]
5959 fn keyboard_activation_fires_click_on_same_element() {
5960 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5961
5962 focus_and_draw(&mut cx, window, &focus_a);
5963 key_down(&mut cx, window, "enter");
5964 key_up(&mut cx, window, "enter");
5965
5966 assert_eq!(*clicks.borrow(), vec!["a"]);
5967 }
5968
5969 #[test]
5974 fn keyboard_activation_does_not_leak_across_focus_change() {
5975 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5976
5977 focus_and_draw(&mut cx, window, &focus_a);
5979 key_down(&mut cx, window, "enter");
5980
5981 focus_and_draw(&mut cx, window, &focus_b);
5983 key_up(&mut cx, window, "enter");
5984
5985 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5988 }
5989
5990 #[test]
5995 fn keyboard_activation_does_not_leak_when_focus_returns() {
5996 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5997
5998 focus_and_draw(&mut cx, window, &focus_a);
6000 key_down(&mut cx, window, "enter");
6001
6002 focus_and_draw(&mut cx, window, &focus_b);
6005 focus_and_draw(&mut cx, window, &focus_a);
6006 key_up(&mut cx, window, "enter");
6007
6008 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
6010 }
6011
6012 #[test]
6017 fn keyboard_activation_cleared_by_intervening_key_release() {
6018 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
6019
6020 focus_and_draw(&mut cx, window, &focus_a);
6021 key_down(&mut cx, window, "escape");
6022 key_down(&mut cx, window, "space");
6023 key_up(&mut cx, window, "escape");
6024 key_up(&mut cx, window, "space");
6025
6026 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
6027 }
6028
6029 #[test]
6033 fn keyboard_activation_does_not_distinguish_space_and_enter() {
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, "space");
6038 key_up(&mut cx, window, "enter");
6039
6040 assert_eq!(*clicks.borrow(), vec!["a"]);
6041 }
6042
6043 #[test]
6046 fn keyboard_activation_cleared_by_intervening_keydown() {
6047 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
6048
6049 focus_and_draw(&mut cx, window, &focus_a);
6050 key_down(&mut cx, window, "enter");
6051 key_down(&mut cx, window, "a");
6052 key_up(&mut cx, window, "enter");
6053
6054 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
6055 }
6056
6057 #[test]
6060 fn keyboard_activation_ignores_modified_keys() {
6061 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
6062
6063 focus_and_draw(&mut cx, window, &focus_a);
6064 key_down(&mut cx, window, "cmd-enter");
6065 key_up(&mut cx, window, "cmd-enter");
6066
6067 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
6068 }
6069
6070 struct TabGroupFocus {
6074 group_a: FocusHandle,
6075 item_a: FocusHandle,
6076 group_b: FocusHandle,
6077 item_b: FocusHandle,
6078 }
6079
6080 impl Render for TabGroupFocus {
6081 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6082 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
6083 div()
6084 .track_focus(container)
6085 .tab_group()
6086 .child(div().track_focus(item))
6087 }
6088 div()
6089 .child(group(&self.group_a, &self.item_a))
6090 .child(group(&self.group_b, &self.item_b))
6091 }
6092 }
6093
6094 #[test]
6098 fn focus_next_from_tab_group_container_enters_that_group() {
6099 let mut cx = TestAppContext::single();
6100 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
6101 (
6102 cx.focus_handle(),
6103 cx.focus_handle().tab_stop(true),
6104 cx.focus_handle(),
6105 cx.focus_handle().tab_stop(true),
6106 )
6107 });
6108 let window: AnyWindowHandle = cx
6109 .add_window({
6110 let (group_a, item_a, group_b, item_b) =
6111 (group_a, item_a, group_b.clone(), item_b.clone());
6112 move |_, _| TabGroupFocus {
6113 group_a,
6114 item_a,
6115 group_b,
6116 item_b,
6117 }
6118 })
6119 .into();
6120 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6121 .unwrap();
6122
6123 let focused = cx
6125 .update_window(window, |_, window, cx| {
6126 window.focus(&group_b, cx);
6127 window.focus_next(cx);
6128 window.focused(cx).map(|handle| handle.id)
6129 })
6130 .unwrap();
6131
6132 assert_eq!(focused, Some(item_b.id));
6133 }
6134
6135 #[gpui::test]
6136 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
6137 cx: &mut TestAppContext,
6138 ) {
6139 struct PaddedContainer {
6140 scroll_handle: ScrollHandle,
6141 }
6142
6143 impl Render for PaddedContainer {
6144 fn render(
6145 &mut self,
6146 _window: &mut Window,
6147 _cx: &mut Context<Self>,
6148 ) -> impl IntoElement {
6149 div().size_full().child(
6152 div()
6153 .id("container")
6154 .h(px(50.))
6155 .w(px(100.))
6156 .py(px(4.25))
6157 .overflow_y_scroll()
6158 .track_scroll(&self.scroll_handle)
6159 .child(div().w_full().h(px(42.))),
6160 )
6161 }
6162 }
6163
6164 let scroll_handle = ScrollHandle::new();
6165 let window: AnyWindowHandle = cx
6166 .add_window({
6167 let scroll_handle = scroll_handle.clone();
6168 move |_, _| PaddedContainer { scroll_handle }
6169 })
6170 .into();
6171 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6172 .unwrap();
6173
6174 assert_eq!(scroll_handle.max_offset().y, px(0.));
6175 }
6176
6177 struct ScrollBurstTestView {
6178 root: ScrollHandle,
6179 short: ScrollHandle,
6180 long: ScrollHandle,
6181 deltas: Rc<RefCell<Vec<Point<Pixels>>>>,
6182 }
6183
6184 impl Render for ScrollBurstTestView {
6185 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6186 let deltas = self.deltas.clone();
6187 div()
6188 .id("burst-root")
6189 .relative()
6190 .w(px(300.))
6191 .h(px(100.))
6192 .overflow_scroll()
6193 .track_scroll(&self.root)
6194 .child(
6195 div()
6196 .id("burst-short")
6197 .absolute()
6198 .top_0()
6199 .left_0()
6200 .size(px(100.))
6201 .overflow_y_scroll()
6202 .track_scroll(&self.short)
6203 .child(div().w_full().h(px(20.))),
6204 )
6205 .child(
6206 div()
6207 .id("burst-long")
6208 .absolute()
6209 .top_0()
6210 .left(px(100.))
6211 .w(px(200.))
6212 .h(px(100.))
6213 .overflow_y_scroll()
6214 .track_scroll(&self.long)
6215 .on_scroll(move |event, window, _| {
6216 deltas
6217 .borrow_mut()
6218 .push(event.delta.pixel_delta(window.line_height()));
6219 })
6220 .child(div().w_full().h(px(600.))),
6221 )
6222 }
6223 }
6224
6225 fn dispatch_test_scroll(
6226 window: &mut Window,
6227 cx: &mut App,
6228 position: Point<Pixels>,
6229 delta: Point<Pixels>,
6230 ) {
6231 window.dispatch_event(
6232 crate::PlatformInput::Scroll(ScrollEvent {
6233 position,
6234 delta: crate::ScrollDelta::Pixels(delta),
6235 ..Default::default()
6236 }),
6237 cx,
6238 );
6239 }
6240
6241 #[gpui::test]
6242 fn wheel_bursts_and_sibling_transfer_keep_live_offsets_in_bounds(cx: &mut TestAppContext) {
6243 let root = ScrollHandle::new();
6244 let short = ScrollHandle::new();
6245 let long = ScrollHandle::new();
6246 let deltas = Rc::new(RefCell::new(Vec::new()));
6247 let window: AnyWindowHandle = cx
6248 .add_window({
6249 let root = root.clone();
6250 let short = short.clone();
6251 let long = long.clone();
6252 let deltas = deltas.clone();
6253 move |_, _| ScrollBurstTestView {
6254 root,
6255 short,
6256 long,
6257 deltas,
6258 }
6259 })
6260 .into();
6261
6262 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6263 .unwrap();
6264 assert_eq!(root.max_offset(), Point::default());
6265 assert_eq!(short.max_offset(), Point::default());
6266 assert_eq!(long.max_offset().y, px(500.));
6267
6268 cx.update_window(window, |_, window, cx| {
6269 let chat_position = point(px(150.), px(50.));
6270 let sidebar_position = point(px(50.), px(50.));
6271 dispatch_test_scroll(window, cx, chat_position, point(px(0.), px(-0.25)));
6272 assert_eq!(long.offset().y, px(-0.25));
6273 assert_eq!(root.offset(), Point::default());
6274
6275 for _ in 0..24 {
6277 dispatch_test_scroll(window, cx, chat_position, point(px(0.), px(-1000.)));
6278 assert_eq!(long.offset().y, px(-500.));
6279 assert_eq!(root.offset(), Point::default());
6280 }
6281 for delta in [-1000., 1000., -1000.] {
6282 dispatch_test_scroll(window, cx, sidebar_position, point(px(0.), px(delta)));
6283 assert_eq!(short.offset(), Point::default());
6284 assert_eq!(root.offset(), Point::default());
6285 assert_eq!(long.offset().y, px(-500.));
6286 }
6287 })
6288 .unwrap();
6289 assert_eq!(deltas.borrow().len(), 25);
6290 assert_eq!(deltas.borrow()[0], point(px(0.), px(-0.25)));
6291 assert!(
6292 deltas.borrow()[1..]
6293 .iter()
6294 .all(|delta| *delta == point(px(0.), px(-1000.)))
6295 );
6296 }
6297
6298 struct TranslatedScrollExtentTestView {
6299 outer: ScrollHandle,
6300 inner: ScrollHandle,
6301 negative_child: bool,
6302 }
6303
6304 impl Render for TranslatedScrollExtentTestView {
6305 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6306 div()
6307 .id("extent-outer")
6308 .size(px(100.))
6309 .overflow_scroll()
6310 .track_scroll(&self.outer)
6311 .child(
6312 div().relative().size(px(1000.)).child(
6313 div()
6314 .id("extent-inner")
6315 .absolute()
6316 .top_0()
6317 .left_0()
6318 .size(px(100.))
6319 .overflow_scroll()
6320 .track_scroll(&self.inner)
6321 .child(div().w(px(100.)).h(px(20.)))
6322 .child(div().absolute().top_0().left_0().size(px(0.)))
6324 .when(self.negative_child, |element| {
6325 element.child(
6326 div().absolute().left(px(-60.)).top(px(-120.)).size(px(20.)),
6327 )
6328 }),
6329 ),
6330 )
6331 }
6332 }
6333
6334 #[gpui::test]
6335 fn negative_ancestor_origins_do_not_create_or_inflate_scroll_extents(cx: &mut TestAppContext) {
6336 for negative_child in [false, true] {
6339 let outer = ScrollHandle::new();
6340 let inner = ScrollHandle::new();
6341 let window: AnyWindowHandle = cx
6342 .add_window({
6343 let outer = outer.clone();
6344 let inner = inner.clone();
6345 move |_, _| TranslatedScrollExtentTestView {
6346 outer,
6347 inner,
6348 negative_child,
6349 }
6350 })
6351 .into();
6352 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6353 .unwrap();
6354 let expected = Point::default();
6355 assert_eq!(inner.max_offset(), expected);
6356
6357 for displacement in [px(500.), px(800.), px(500.), px(0.)] {
6360 outer.set_offset(point(-displacement, -displacement));
6361 cx.update_window(window, |_, window, cx| {
6362 window.refresh();
6363 window.draw(cx).clear(cx);
6364 })
6365 .unwrap();
6366 assert_eq!(outer.offset(), point(-displacement, -displacement));
6367 assert_eq!(inner.max_offset(), expected);
6368 assert_eq!(inner.offset(), Point::default());
6369 }
6370 }
6371 }
6372
6373 struct PaddedScrollExtentTestView {
6374 handle: ScrollHandle,
6375 far_child: bool,
6376 }
6377
6378 impl Render for PaddedScrollExtentTestView {
6379 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6380 div()
6381 .id("padded")
6382 .size(px(100.))
6383 .p(px(10.))
6384 .overflow_scroll()
6385 .track_scroll(&self.handle)
6386 .child(div().w(px(80.)).h(px(80.)))
6388 .child(div().absolute().top(px(4.)).right(px(4.)).size(px(6.)))
6391 .child(div().absolute().top_0().right_0().size(px(0.)))
6392 .when(self.far_child, |element| {
6393 element.child(div().absolute().left(px(150.)).top_0().size(px(20.)))
6394 })
6395 }
6396 }
6397
6398 #[gpui::test]
6399 fn absolute_children_count_as_their_own_box_not_with_the_padding(cx: &mut TestAppContext) {
6400 for (far_child, expected) in [(false, Point::default()), (true, point(px(70.), px(0.)))] {
6404 let handle = ScrollHandle::new();
6405 let window: AnyWindowHandle = cx
6406 .add_window({
6407 let handle = handle.clone();
6408 move |_, _| PaddedScrollExtentTestView { handle, far_child }
6409 })
6410 .into();
6411 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
6412 .unwrap();
6413 assert_eq!(handle.max_offset(), expected, "far child: {far_child}");
6414 }
6415 }
6416
6417 struct ContentSizedGrid;
6418
6419 impl Render for ContentSizedGrid {
6420 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6421 let widths = [px(100.), px(200.), px(50.)];
6422 div().size_full().child(
6423 div()
6424 .w_full()
6425 .grid()
6426 .grid_cols_max_content(widths.len() as u16)
6427 .children(widths.into_iter().enumerate().map(|(index, width)| {
6428 div()
6429 .debug_selector(move || format!("cell-{index}"))
6430 .w(width)
6431 .h(px(10.))
6432 })),
6433 )
6434 }
6435 }
6436
6437 #[gpui::test]
6438 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
6439 let window = cx.add_window(|_, _| ContentSizedGrid);
6440 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
6441 .unwrap();
6442
6443 let mut bounds = |selector: &'static str| {
6444 cx.update_window(window.into(), |_, window, _| {
6445 window.rendered_frame.debug_bounds.get(selector).copied()
6446 })
6447 .unwrap()
6448 .unwrap_or_else(|| panic!("{selector} was not rendered"))
6449 };
6450
6451 assert_eq!(bounds("cell-0").origin.x, px(0.));
6452 assert_eq!(bounds("cell-1").origin.x, px(100.));
6453 assert_eq!(bounds("cell-2").origin.x, px(300.));
6454 }
6455}