1use crate::{
19 Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent, DispatchPhase,
20 Display, Element, ElementId, Entity, EntityId, ExternalDragPayload, ExternalDragPayloadSource,
21 FileDropEvent, FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, HitboxFilter,
22 HitboxId, IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, KeyboardButton,
23 KeyboardClickEvent, LayoutId, LongPressEvent, ModifiersChangedEvent, MouseButton,
24 MouseClickEvent, MouseDownEvent, MouseExitEvent, MouseMoveEvent, MousePressureEvent,
25 MouseUpEvent, OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels, Point, Render,
26 ScrollWheelEvent, SharedString, Size, Style, StyleRefinement, Styled, Task, TooltipId,
27 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_wheel(
391 &mut self,
392 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
393 ) {
394 self.scroll_wheel_listeners
395 .push(Box::new(move |event, phase, hitbox, window, cx| {
396 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
397 (listener)(event, window, cx);
398 }
399 }));
400 }
401
402 pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
406 self.pinch_listeners
407 .push(Box::new(move |event, phase, hitbox, window, cx| {
408 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
409 (listener)(event, window, cx);
410 }
411 }));
412 }
413
414 pub fn capture_pinch(
418 &mut self,
419 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
420 ) {
421 self.pinch_listeners
422 .push(Box::new(move |event, phase, _hitbox, window, cx| {
423 if phase == DispatchPhase::Capture {
424 (listener)(event, window, cx);
425 } else {
426 cx.propagate();
427 }
428 }));
429 }
430
431 pub fn capture_action<A: Action>(
436 &mut self,
437 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
438 ) {
439 self.action_listeners.push((
440 TypeId::of::<A>(),
441 Box::new(move |action, phase, window, cx| {
442 let action = action.downcast_ref().unwrap();
443 if phase == DispatchPhase::Capture {
444 (listener)(action, window, cx)
445 } else {
446 cx.propagate();
447 }
448 }),
449 ));
450 }
451
452 #[track_caller]
457 #[inline(always)]
458 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
459 self.action_listeners.push((
460 TypeId::of::<A>(),
461 Box::new(move |action, phase, window, cx| {
462 let action = action.downcast_ref().unwrap();
463 if phase == DispatchPhase::Bubble {
464 (listener)(action, window, cx)
465 }
466 }),
467 ));
468 }
469
470 pub fn on_boxed_action(
477 &mut self,
478 action: &dyn Action,
479 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
480 ) {
481 let action = action.boxed_clone();
482 self.action_listeners.push((
483 (*action).type_id(),
484 Box::new(move |_, phase, window, cx| {
485 if phase == DispatchPhase::Bubble {
486 (listener)(&*action, window, cx)
487 }
488 }),
489 ));
490 }
491
492 pub fn on_key_down(
497 &mut self,
498 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
499 ) {
500 self.key_down_listeners
501 .push(Box::new(move |event, phase, window, cx| {
502 if phase == DispatchPhase::Bubble {
503 (listener)(event, window, cx)
504 }
505 }));
506 }
507
508 pub fn capture_key_down(
513 &mut self,
514 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
515 ) {
516 self.key_down_listeners
517 .push(Box::new(move |event, phase, window, cx| {
518 if phase == DispatchPhase::Capture {
519 listener(event, window, cx)
520 }
521 }));
522 }
523
524 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
529 self.key_up_listeners
530 .push(Box::new(move |event, phase, window, cx| {
531 if phase == DispatchPhase::Bubble {
532 listener(event, window, cx)
533 }
534 }));
535 }
536
537 pub fn capture_key_up(
542 &mut self,
543 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
544 ) {
545 self.key_up_listeners
546 .push(Box::new(move |event, phase, window, cx| {
547 if phase == DispatchPhase::Capture {
548 listener(event, window, cx)
549 }
550 }));
551 }
552
553 pub fn on_modifiers_changed(
558 &mut self,
559 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
560 ) {
561 self.modifiers_changed_listeners.push(Box::new(listener));
562 }
563
564 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
569 self.drop_listeners.push((
570 TypeId::of::<T>(),
571 Box::new(move |dragged_value, window, cx| {
572 listener(dragged_value.downcast_ref().unwrap(), window, cx);
573 }),
574 ));
575 }
576
577 pub fn can_drop(
580 &mut self,
581 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
582 ) {
583 self.can_drop_predicate = Some(Box::new(predicate));
584 }
585
586 #[inline(always)]
591 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
592 where
593 Self: Sized,
594 {
595 self.click_listeners.push(Rc::new(listener));
596 }
597
598 pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
603 where
604 Self: Sized,
605 {
606 self.aux_click_listeners.push(Rc::new(listener));
607 }
608
609 pub fn on_drag<T, W>(
616 &mut self,
617 value: T,
618 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
619 ) where
620 Self: Sized,
621 T: 'static,
622 W: 'static + Render,
623 {
624 debug_assert!(
625 self.drag_listener.is_none(),
626 "calling on_drag more than once on the same element is not supported"
627 );
628 self.drag_listener = Some(DragListener {
629 value: Arc::new(value),
630 render: Box::new(move |value, offset, window, cx| {
631 constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
632 }),
633 external_payload: None,
634 });
635 }
636
637 pub fn external_drag_payload<T>(
642 &mut self,
643 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
644 ) where
645 Self: Sized,
646 T: 'static,
647 {
648 let Some(drag_listener) = self.drag_listener.as_mut() else {
649 debug_assert!(false, "external_drag_payload must be called after on_drag");
650 return;
651 };
652 debug_assert!(
653 drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
654 "external_drag_payload must use the same dragged value type as on_drag"
655 );
656 debug_assert!(
657 drag_listener.external_payload.is_none(),
658 "calling external_drag_payload more than once on the same element is not supported"
659 );
660 drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
661 resolver(value.downcast_ref::<T>()?, window, cx)
662 }));
663 }
664
665 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
676 where
677 Self: Sized,
678 {
679 debug_assert!(
680 self.hover_listener.is_none(),
681 "calling on_hover more than once on the same element is not supported"
682 );
683 self.hover_listener = Some(Box::new(listener));
684 }
685
686 pub fn hover_listener_mode(&mut self, mode: HoverListenerMode)
690 where
691 Self: Sized,
692 {
693 self.hover_listener_mode = mode;
694 }
695
696 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
699 where
700 Self: Sized,
701 {
702 debug_assert!(
703 self.tooltip_builder.is_none(),
704 "calling tooltip more than once on the same element is not supported"
705 );
706 self.tooltip_builder = Some(TooltipBuilder {
707 build: Rc::new(build_tooltip),
708 hoverable: false,
709 });
710 }
711
712 pub fn hoverable_tooltip(
716 &mut self,
717 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
718 ) where
719 Self: Sized,
720 {
721 debug_assert!(
722 self.tooltip_builder.is_none(),
723 "calling tooltip more than once on the same element is not supported"
724 );
725 self.tooltip_builder = Some(TooltipBuilder {
726 build: Rc::new(build_tooltip),
727 hoverable: true,
728 });
729 }
730
731 pub fn tooltip_show_delay(&mut self, delay: Duration) {
736 self.tooltip_show_delay = Some(delay);
737 }
738
739 pub fn occlude_mouse(&mut self) {
744 self.hitbox_behavior = HitboxBehavior::BlockMouse;
745 }
746
747 pub fn window_control_area(&mut self, area: WindowControlArea) {
750 self.window_control = Some(area);
751 }
752
753 pub fn block_mouse_except_scroll(&mut self) {
758 self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
759 }
760
761 fn has_pinch_listeners(&self) -> bool {
762 !self.pinch_listeners.is_empty()
763 }
764}
765
766pub trait InteractiveElement: Sized {
769 fn interactivity(&mut self) -> &mut Interactivity;
771
772 fn group(mut self, group: impl Into<SharedString>) -> Self {
774 self.interactivity().group = Some(group.into());
775 self
776 }
777
778 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
780 self.interactivity().element_id = Some(id.into());
781
782 Stateful { element: self }
783 }
784
785 fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
789 self.interactivity().focusable = true;
790 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
791 self
792 }
793
794 fn tab_stop(mut self, tab_stop: bool) -> Self {
801 self.interactivity().tab_stop = tab_stop;
802 self
803 }
804
805 fn tab_index(mut self, index: isize) -> Self {
810 self.interactivity().focusable = true;
811 self.interactivity().tab_index = Some(index);
812 self.interactivity().tab_stop = true;
813 self
814 }
815
816 fn tab_group(mut self) -> Self {
821 self.interactivity().tab_group = true;
822 if self.interactivity().tab_index.is_none() {
823 self.interactivity().tab_index = Some(0);
824 }
825 self
826 }
827
828 fn key_context<C, E>(mut self, key_context: C) -> Self
831 where
832 C: TryInto<KeyContext, Error = E>,
833 E: std::fmt::Display,
834 {
835 if let Some(key_context) = key_context.try_into().log_err() {
836 self.interactivity().key_context = Some(key_context);
837 }
838 self
839 }
840
841 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
843 debug_assert!(
844 self.interactivity().hover_style.is_none(),
845 "hover style already set"
846 );
847 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
848 self
849 }
850
851 fn group_hover(
853 mut self,
854 group_name: impl Into<SharedString>,
855 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
856 ) -> Self {
857 self.interactivity().group_hover_style = Some(GroupStyle {
858 group: group_name.into(),
859 style: Box::new(f(StyleRefinement::default())),
860 });
861 self
862 }
863
864 #[inline(always)]
869 fn on_mouse_down(
870 mut self,
871 button: MouseButton,
872 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
873 ) -> Self {
874 self.interactivity().on_mouse_down(button, listener);
875 self
876 }
877
878 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
885 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
886 self.interactivity().debug_selector = Some(f());
887 self
888 }
889
890 #[cfg(not(any(test, all(debug_assertions, feature = "test-support"))))]
897 #[inline]
898 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
899 self
900 }
901
902 fn capture_any_mouse_down(
907 mut self,
908 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
909 ) -> Self {
910 self.interactivity().capture_any_mouse_down(listener);
911 self
912 }
913
914 fn on_any_mouse_down(
919 mut self,
920 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
921 ) -> Self {
922 self.interactivity().on_any_mouse_down(listener);
923 self
924 }
925
926 fn on_mouse_up(
931 mut self,
932 button: MouseButton,
933 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
934 ) -> Self {
935 self.interactivity().on_mouse_up(button, listener);
936 self
937 }
938
939 fn capture_any_mouse_up(
944 mut self,
945 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
946 ) -> Self {
947 self.interactivity().capture_any_mouse_up(listener);
948 self
949 }
950
951 fn on_mouse_pressure(
956 mut self,
957 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
958 ) -> Self {
959 self.interactivity().on_mouse_pressure(listener);
960 self
961 }
962
963 fn capture_mouse_pressure(
968 mut self,
969 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
970 ) -> Self {
971 self.interactivity().capture_mouse_pressure(listener);
972 self
973 }
974
975 fn on_mouse_down_out(
981 mut self,
982 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
983 ) -> Self {
984 self.interactivity().on_mouse_down_out(listener);
985 self
986 }
987
988 fn on_mouse_up_out(
994 mut self,
995 button: MouseButton,
996 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
997 ) -> Self {
998 self.interactivity().on_mouse_up_out(button, listener);
999 self
1000 }
1001
1002 fn on_mouse_move(
1007 mut self,
1008 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
1009 ) -> Self {
1010 self.interactivity().on_mouse_move(listener);
1011 self
1012 }
1013
1014 fn on_mouse_exit(
1019 mut self,
1020 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
1021 ) -> Self {
1022 self.interactivity().on_mouse_exit(listener);
1023 self
1024 }
1025
1026 fn on_file_drop_exit(
1034 mut self,
1035 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
1036 ) -> Self {
1037 self.interactivity().on_file_drop_exit(listener);
1038 self
1039 }
1040
1041 fn on_drag_move<T: 'static>(
1049 mut self,
1050 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
1051 ) -> Self {
1052 self.interactivity().on_drag_move(listener);
1053 self
1054 }
1055
1056 fn on_scroll_wheel(
1061 mut self,
1062 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
1063 ) -> Self {
1064 self.interactivity().on_scroll_wheel(listener);
1065 self
1066 }
1067
1068 fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
1073 self.interactivity().on_pinch(listener);
1074 self
1075 }
1076
1077 fn capture_pinch(
1082 mut self,
1083 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
1084 ) -> Self {
1085 self.interactivity().capture_pinch(listener);
1086 self
1087 }
1088 fn capture_action<A: Action>(
1093 mut self,
1094 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1095 ) -> Self {
1096 self.interactivity().capture_action(listener);
1097 self
1098 }
1099
1100 #[track_caller]
1105 #[inline(always)]
1106 fn on_action<A: Action>(
1107 mut self,
1108 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1109 ) -> Self {
1110 self.interactivity().on_action(listener);
1111 self
1112 }
1113
1114 fn on_boxed_action(
1121 mut self,
1122 action: &dyn Action,
1123 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1124 ) -> Self {
1125 self.interactivity().on_boxed_action(action, listener);
1126 self
1127 }
1128
1129 fn on_key_down(
1134 mut self,
1135 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1136 ) -> Self {
1137 self.interactivity().on_key_down(listener);
1138 self
1139 }
1140
1141 fn capture_key_down(
1146 mut self,
1147 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1148 ) -> Self {
1149 self.interactivity().capture_key_down(listener);
1150 self
1151 }
1152
1153 fn on_key_up(
1158 mut self,
1159 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1160 ) -> Self {
1161 self.interactivity().on_key_up(listener);
1162 self
1163 }
1164
1165 fn capture_key_up(
1170 mut self,
1171 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1172 ) -> Self {
1173 self.interactivity().capture_key_up(listener);
1174 self
1175 }
1176
1177 #[inline(always)]
1182 fn on_modifiers_changed(
1183 mut self,
1184 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1185 ) -> Self {
1186 self.interactivity().on_modifiers_changed(listener);
1187 self
1188 }
1189
1190 fn drag_over<S: 'static>(
1192 mut self,
1193 f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1194 ) -> Self {
1195 self.interactivity().drag_over_styles.push((
1196 TypeId::of::<S>(),
1197 Box::new(move |currently_dragged: &dyn Any, window, cx| {
1198 f(
1199 StyleRefinement::default(),
1200 currently_dragged.downcast_ref::<S>().unwrap(),
1201 window,
1202 cx,
1203 )
1204 }),
1205 ));
1206 self
1207 }
1208
1209 fn group_drag_over<S: 'static>(
1211 mut self,
1212 group_name: impl Into<SharedString>,
1213 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1214 ) -> Self {
1215 self.interactivity().group_drag_over_styles.push((
1216 TypeId::of::<S>(),
1217 GroupStyle {
1218 group: group_name.into(),
1219 style: Box::new(f(StyleRefinement::default())),
1220 },
1221 ));
1222 self
1223 }
1224
1225 fn on_drop<T: 'static>(
1230 mut self,
1231 listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1232 ) -> Self {
1233 self.interactivity().on_drop(listener);
1234 self
1235 }
1236
1237 fn can_drop(
1240 mut self,
1241 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1242 ) -> Self {
1243 self.interactivity().can_drop(predicate);
1244 self
1245 }
1246
1247 fn occlude(mut self) -> Self {
1251 self.interactivity().occlude_mouse();
1252 self
1253 }
1254
1255 fn window_control_area(mut self, area: WindowControlArea) -> Self {
1258 self.interactivity().window_control_area(area);
1259 self
1260 }
1261
1262 fn block_mouse_except_scroll(mut self) -> Self {
1267 self.interactivity().block_mouse_except_scroll();
1268 self
1269 }
1270
1271 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1274 where
1275 Self: Sized,
1276 {
1277 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1278 self
1279 }
1280
1281 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1284 where
1285 Self: Sized,
1286 {
1287 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1288 self
1289 }
1290
1291 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1296 where
1297 Self: Sized,
1298 {
1299 self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1300 self
1301 }
1302}
1303
1304pub trait StatefulInteractiveElement: InteractiveElement {
1307 fn role(mut self, role: accesskit::Role) -> Self {
1311 debug_assert!(
1312 role != accesskit::Role::GenericContainer,
1313 "GenericContainer is filtered out of the a11y tree and has no effect"
1314 );
1315 self.interactivity().override_role = Some(role);
1316 self
1317 }
1318
1319 fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self {
1327 self.interactivity().aria.author_id = Some(id.into());
1328 self
1329 }
1330
1331 fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1333 self.interactivity().aria.label = Some(label.into());
1334 self
1335 }
1336
1337 fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
1342 self.interactivity().aria.description = Some(description.into());
1343 self
1344 }
1345
1346 fn aria_keyshortcuts(mut self, keyshortcuts: impl Into<SharedString>) -> Self {
1352 self.interactivity().aria.keyshortcuts = Some(keyshortcuts.into());
1353 self
1354 }
1355
1356 fn aria_active_descendant(mut self) -> Self {
1372 self.interactivity().report_active_descendant_focus = true;
1373 self
1374 }
1375
1376 fn a11y_synthetic_children(
1386 mut self,
1387 f: impl FnOnce(&mut crate::A11ySubtreeBuilder) + 'static,
1388 ) -> Self {
1389 self.interactivity().a11y_synthetic_children = Some(Box::new(f));
1390 self
1391 }
1392
1393 fn aria_selected(mut self, selected: bool) -> Self {
1395 self.interactivity().aria.selected = Some(selected);
1396 self
1397 }
1398
1399 fn aria_expanded(mut self, expanded: bool) -> Self {
1401 self.interactivity().aria.expanded = Some(expanded);
1402 self
1403 }
1404
1405 fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1407 self.interactivity().aria.toggled = Some(toggled);
1408 self
1409 }
1410
1411 fn aria_numeric_value(mut self, value: f64) -> Self {
1413 self.interactivity().aria.numeric_value = Some(value);
1414 self
1415 }
1416
1417 fn aria_numeric_value_step(mut self, step: f64) -> Self {
1420 self.interactivity().aria.numeric_value_step = Some(step);
1421 self
1422 }
1423
1424 fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
1427 self.interactivity().aria.value = Some(value.into());
1428 self
1429 }
1430
1431 fn aria_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1434 self.interactivity().aria.placeholder = Some(placeholder.into());
1435 self
1436 }
1437
1438 fn aria_min_numeric_value(mut self, value: f64) -> Self {
1440 self.interactivity().aria.min_numeric_value = Some(value);
1441 self
1442 }
1443
1444 fn aria_max_numeric_value(mut self, value: f64) -> Self {
1446 self.interactivity().aria.max_numeric_value = Some(value);
1447 self
1448 }
1449
1450 fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1452 self.interactivity().aria.orientation = Some(orientation);
1453 self
1454 }
1455
1456 fn aria_level(mut self, level: usize) -> Self {
1458 self.interactivity().aria.level = Some(level);
1459 self
1460 }
1461
1462 fn aria_position_in_set(mut self, position: usize) -> Self {
1464 self.interactivity().aria.position_in_set = Some(position);
1465 self
1466 }
1467
1468 fn aria_size_of_set(mut self, size: usize) -> Self {
1470 self.interactivity().aria.size_of_set = Some(size);
1471 self
1472 }
1473
1474 fn aria_row_index(mut self, index: usize) -> Self {
1476 self.interactivity().aria.row_index = Some(index);
1477 self
1478 }
1479
1480 fn aria_column_index(mut self, index: usize) -> Self {
1482 self.interactivity().aria.column_index = Some(index);
1483 self
1484 }
1485
1486 fn aria_row_count(mut self, count: usize) -> Self {
1488 self.interactivity().aria.row_count = Some(count);
1489 self
1490 }
1491
1492 fn aria_column_count(mut self, count: usize) -> Self {
1494 self.interactivity().aria.column_count = Some(count);
1495 self
1496 }
1497
1498 #[inline(always)]
1503 fn on_a11y_action(
1504 mut self,
1505 action: accesskit::Action,
1506 listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1507 + 'static,
1508 ) -> Self {
1509 self.interactivity()
1510 .a11y_action_listeners
1511 .push((action, Box::new(listener)));
1512 self
1513 }
1514
1515 fn focusable(mut self) -> Self {
1517 self.interactivity().focusable = true;
1518 self
1519 }
1520
1521 fn overflow_scroll(mut self) -> Self {
1523 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1524 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1525 self
1526 }
1527
1528 fn overflow_x_scroll(mut self) -> Self {
1530 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1531 self
1532 }
1533
1534 fn overflow_y_scroll(mut self) -> Self {
1536 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1537 self
1538 }
1539
1540 fn restrict_scroll_to_axis(mut self) -> Self {
1544 self.interactivity().base_style.restrict_scroll_to_axis = Some(true);
1545 self
1546 }
1547
1548 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1550 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1551 self
1552 }
1553
1554 fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1556 self.interactivity().scroll_anchor = scroll_anchor;
1557 self
1558 }
1559
1560 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1562 where
1563 Self: Sized,
1564 {
1565 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1566 self
1567 }
1568
1569 fn group_active(
1571 mut self,
1572 group_name: impl Into<SharedString>,
1573 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1574 ) -> Self
1575 where
1576 Self: Sized,
1577 {
1578 self.interactivity().group_active_style = Some(GroupStyle {
1579 group: group_name.into(),
1580 style: Box::new(f(StyleRefinement::default())),
1581 });
1582 self
1583 }
1584
1585 #[inline(always)]
1590 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1591 where
1592 Self: Sized,
1593 {
1594 self.interactivity().on_click(listener);
1595 self
1596 }
1597
1598 fn on_aux_click(
1603 mut self,
1604 listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1605 ) -> Self
1606 where
1607 Self: Sized,
1608 {
1609 self.interactivity().on_aux_click(listener);
1610 self
1611 }
1612
1613 fn on_drag<T, W>(
1621 mut self,
1622 value: T,
1623 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1624 ) -> Self
1625 where
1626 Self: Sized,
1627 T: 'static,
1628 W: 'static + Render,
1629 {
1630 self.interactivity().on_drag(value, constructor);
1631 self
1632 }
1633
1634 fn external_drag_payload<T>(
1640 mut self,
1641 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
1642 ) -> Self
1643 where
1644 Self: Sized,
1645 T: 'static,
1646 {
1647 self.interactivity().external_drag_payload(resolver);
1648 self
1649 }
1650
1651 fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1662 where
1663 Self: Sized,
1664 {
1665 self.interactivity().on_hover(listener);
1666 self
1667 }
1668
1669 fn hover_listener_mode(mut self, mode: HoverListenerMode) -> Self
1673 where
1674 Self: Sized,
1675 {
1676 self.interactivity().hover_listener_mode(mode);
1677 self
1678 }
1679
1680 fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1683 where
1684 Self: Sized,
1685 {
1686 self.interactivity().tooltip(build_tooltip);
1687 self
1688 }
1689
1690 fn hoverable_tooltip(
1694 mut self,
1695 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1696 ) -> Self
1697 where
1698 Self: Sized,
1699 {
1700 self.interactivity().hoverable_tooltip(build_tooltip);
1701 self
1702 }
1703
1704 fn tooltip_show_delay(mut self, delay: Duration) -> Self
1709 where
1710 Self: Sized,
1711 {
1712 self.interactivity().tooltip_show_delay(delay);
1713 self
1714 }
1715}
1716
1717pub(crate) type MouseDownListener =
1718 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1719pub(crate) type MouseUpListener =
1720 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1721pub(crate) type MousePressureListener =
1722 Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1723pub(crate) type MouseMoveListener =
1724 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1725pub(crate) type MouseExitListener =
1726 Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1727
1728pub(crate) type FileDropExitListener =
1729 Box<dyn Fn(&FileDropEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1730
1731pub(crate) type ScrollWheelListener =
1732 Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1733
1734pub(crate) type PinchListener =
1735 Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1736
1737pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1738
1739#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1742pub enum HoverListenerMode {
1743 #[default]
1746 InputModalityAware,
1747 InputModalityIndependent,
1751}
1752
1753impl HoverListenerMode {
1754 fn is_hovered(self, hitbox: &Hitbox, window: &Window) -> bool {
1755 match self {
1756 Self::InputModalityAware => hitbox.is_hovered(window),
1757 Self::InputModalityIndependent => hitbox.id.is_hovered_ignoring_last_input(window),
1758 }
1759 }
1760}
1761
1762pub(crate) struct DragListener {
1763 value: Arc<dyn Any>,
1764 render: Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>,
1765 external_payload: Option<ExternalDragPayloadResolver>,
1766}
1767
1768type ExternalDragPayloadResolver =
1769 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
1770
1771type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1772
1773type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1774
1775pub(crate) struct TooltipBuilder {
1776 build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1777 hoverable: bool,
1778}
1779
1780pub(crate) type KeyDownListener =
1781 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1782
1783pub(crate) type KeyUpListener =
1784 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1785
1786pub(crate) type ModifiersChangedListener =
1787 Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1788
1789pub(crate) type ActionListener =
1790 Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1791
1792#[track_caller]
1794pub fn div() -> Div {
1795 Div {
1796 interactivity: Interactivity::new(),
1797 children: SmallVec::default(),
1798 prepaint_listener: None,
1799 image_cache: None,
1800 prepaint_order_fn: None,
1801 }
1802}
1803
1804pub struct Div {
1806 interactivity: Interactivity,
1807 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1808 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1809 image_cache: Option<Box<dyn ImageCacheProvider>>,
1810 prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1811}
1812
1813impl Div {
1814 pub fn on_children_prepainted(
1817 mut self,
1818 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1819 ) -> Self {
1820 self.prepaint_listener = Some(Box::new(listener));
1821 self
1822 }
1823
1824 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1826 self.image_cache = Some(Box::new(cache));
1827 self
1828 }
1829
1830 pub fn with_dynamic_prepaint_order(
1839 mut self,
1840 order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1841 ) -> Self {
1842 self.prepaint_order_fn = Some(Box::new(order_fn));
1843 self
1844 }
1845}
1846
1847pub struct DivFrameState {
1854 child_layout_ids: SmallVec<[LayoutId; 2]>,
1855}
1856
1857#[derive(Clone)]
1859pub struct DivInspectorState {
1860 #[cfg(any(feature = "inspector", debug_assertions))]
1864 pub base_style: Box<StyleRefinement>,
1865 pub bounds: Bounds<Pixels>,
1867 pub content_size: Size<Pixels>,
1869}
1870
1871impl Styled for Div {
1872 fn style(&mut self) -> &mut StyleRefinement {
1873 &mut self.interactivity.base_style
1874 }
1875}
1876
1877impl InteractiveElement for Div {
1878 fn interactivity(&mut self) -> &mut Interactivity {
1879 &mut self.interactivity
1880 }
1881}
1882
1883impl ParentElement for Div {
1884 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1885 #[cfg(feature = "stacker")]
1886 self.children
1887 .extend(elements.into_iter().map(StackSafe::new));
1888 #[cfg(not(feature = "stacker"))]
1889 self.children.extend(elements);
1890 }
1891}
1892
1893impl Element for Div {
1894 type RequestLayoutState = DivFrameState;
1895 type PrepaintState = Option<Hitbox>;
1896
1897 fn id(&self) -> Option<ElementId> {
1898 self.interactivity.element_id.clone()
1899 }
1900
1901 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1902 self.interactivity.source_location()
1903 }
1904
1905 fn a11y_role(&self) -> Option<accesskit::Role> {
1906 self.interactivity
1909 .override_role
1910 .filter(|role| *role != accesskit::Role::GenericContainer)
1911 }
1912
1913 fn write_a11y_info(&self, node: &mut accesskit::Node) {
1914 self.interactivity.write_a11y_info(node);
1915 }
1916
1917 fn a11y_synthetic_children(
1918 &mut self,
1919 _prepaint: &mut Self::PrepaintState,
1920 builder: &mut crate::A11ySubtreeBuilder,
1921 ) {
1922 if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
1923 f(builder);
1924 }
1925 }
1926
1927 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
1928 fn request_layout(
1929 &mut self,
1930 global_id: Option<&GlobalElementId>,
1931 window: &mut Window,
1932 cx: &mut App,
1933 ) -> (LayoutId, Self::RequestLayoutState) {
1934 let mut child_layout_ids = SmallVec::new();
1935 let image_cache = self
1936 .image_cache
1937 .as_mut()
1938 .map(|provider| provider.provide(window, cx));
1939
1940 let layout_id = window.with_image_cache(image_cache, |window| {
1941 self.interactivity
1942 .request_layout(global_id, window, cx, |style, window, cx| {
1943 window.with_text_style(style.text_style().cloned(), |window| {
1944 child_layout_ids = self
1945 .children
1946 .iter_mut()
1947 .map(|child| child.request_layout(window, cx))
1948 .collect::<SmallVec<_>>();
1949 window.request_layout(style, child_layout_ids.iter().copied(), cx)
1950 })
1951 })
1952 });
1953
1954 (layout_id, DivFrameState { child_layout_ids })
1955 }
1956
1957 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
1958 fn prepaint(
1959 &mut self,
1960 global_id: Option<&GlobalElementId>,
1961 bounds: Bounds<Pixels>,
1962 request_layout: &mut Self::RequestLayoutState,
1963 window: &mut Window,
1964 cx: &mut App,
1965 ) -> Option<Hitbox> {
1966 let image_cache = self
1967 .image_cache
1968 .as_mut()
1969 .map(|provider| provider.provide(window, cx));
1970
1971 let has_prepaint_listener = self.prepaint_listener.is_some();
1972 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1973 request_layout.child_layout_ids.len()
1974 } else {
1975 0
1976 });
1977
1978 let mut child_min = point(Pixels::MAX, Pixels::MAX);
1979 let mut child_max = Point::default();
1980 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1981 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1982 }
1983 let content_size = if request_layout.child_layout_ids.is_empty() {
1984 bounds.size
1985 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1986 let mut state = scroll_handle.0.borrow_mut();
1987 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1988 for child_layout_id in &request_layout.child_layout_ids {
1989 let child_bounds = window.layout_bounds(*child_layout_id);
1990 child_min = child_min.min(&child_bounds.origin);
1991 child_max = child_max.max(&child_bounds.bottom_right());
1992 state.child_bounds.push(child_bounds);
1993 }
1994 (child_max - child_min).into()
1995 } else {
1996 for child_layout_id in &request_layout.child_layout_ids {
1997 let child_bounds = window.layout_bounds(*child_layout_id);
1998 child_min = child_min.min(&child_bounds.origin);
1999 child_max = child_max.max(&child_bounds.bottom_right());
2000
2001 if has_prepaint_listener {
2002 children_bounds.push(child_bounds);
2003 }
2004 }
2005 (child_max - child_min).into()
2006 };
2007
2008 if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2009 scroll_handle.scroll_to_active_item();
2010 }
2011
2012 self.interactivity.prepaint(
2013 global_id,
2014 bounds,
2015 content_size,
2016 window,
2017 cx,
2018 |style, scroll_offset, hitbox, window, cx| {
2019 if style.display == Display::None {
2021 return hitbox;
2022 }
2023
2024 window.with_image_cache(image_cache, |window| {
2025 window.with_element_offset(scroll_offset, |window| {
2026 if let Some(order_fn) = &self.prepaint_order_fn {
2027 let order = order_fn(window, cx);
2028 for idx in order {
2029 if let Some(child) = self.children.get_mut(idx) {
2030 child.prepaint(window, cx);
2031 }
2032 }
2033 } else {
2034 for child in &mut self.children {
2035 child.prepaint(window, cx);
2036 }
2037 }
2038 });
2039
2040 if let Some(listener) = self.prepaint_listener.as_ref() {
2041 listener(children_bounds, window, cx);
2042 }
2043 });
2044
2045 hitbox
2046 },
2047 )
2048 }
2049
2050 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2051 fn paint(
2052 &mut self,
2053 global_id: Option<&GlobalElementId>,
2054 bounds: Bounds<Pixels>,
2055 _request_layout: &mut Self::RequestLayoutState,
2056 hitbox: &mut Option<Hitbox>,
2057 window: &mut Window,
2058 cx: &mut App,
2059 ) {
2060 let image_cache = self
2061 .image_cache
2062 .as_mut()
2063 .map(|provider| provider.provide(window, cx));
2064
2065 window.with_image_cache(image_cache, |window| {
2066 self.interactivity.paint(
2067 global_id,
2068 bounds,
2069 hitbox.as_ref(),
2070 window,
2071 cx,
2072 |style, window, cx| {
2073 if style.display == Display::None {
2075 return;
2076 }
2077
2078 for child in &mut self.children {
2079 child.paint(window, cx);
2080 }
2081 },
2082 )
2083 });
2084 }
2085}
2086
2087impl IntoElement for Div {
2088 type Element = Self;
2089
2090 fn into_element(self) -> Self::Element {
2091 self
2092 }
2093}
2094
2095#[derive(Default)]
2096pub(crate) struct AriaProperties {
2097 pub(crate) author_id: Option<SharedString>,
2098 pub(crate) label: Option<SharedString>,
2099 pub(crate) description: Option<SharedString>,
2100 pub(crate) keyshortcuts: Option<SharedString>,
2101 pub(crate) selected: Option<bool>,
2102 pub(crate) expanded: Option<bool>,
2103 pub(crate) toggled: Option<accesskit::Toggled>,
2104 pub(crate) numeric_value: Option<f64>,
2105 pub(crate) min_numeric_value: Option<f64>,
2106 pub(crate) max_numeric_value: Option<f64>,
2107 pub(crate) numeric_value_step: Option<f64>,
2108 pub(crate) value: Option<SharedString>,
2109 pub(crate) placeholder: Option<SharedString>,
2110 pub(crate) orientation: Option<accesskit::Orientation>,
2111 pub(crate) level: Option<usize>,
2112 pub(crate) position_in_set: Option<usize>,
2113 pub(crate) size_of_set: Option<usize>,
2114 pub(crate) row_index: Option<usize>,
2115 pub(crate) column_index: Option<usize>,
2116 pub(crate) row_count: Option<usize>,
2117 pub(crate) column_count: Option<usize>,
2118}
2119
2120#[derive(Default)]
2123pub struct Interactivity {
2124 pub element_id: Option<ElementId>,
2126 pub active: Option<bool>,
2128 pub hovered: Option<bool>,
2131 pub(crate) tooltip_id: Option<TooltipId>,
2132 pub(crate) content_size: Size<Pixels>,
2133 pub(crate) key_context: Option<KeyContext>,
2134 pub(crate) focusable: bool,
2135 pub(crate) tracked_focus_handle: Option<FocusHandle>,
2136 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2137 pub(crate) scroll_anchor: Option<ScrollAnchor>,
2138 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2139 pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2140 pub(crate) group: Option<SharedString>,
2141 pub base_style: Box<StyleRefinement>,
2144 pub(crate) focus_style: Option<Box<StyleRefinement>>,
2145 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2146 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2147 pub(crate) hover_style: Option<Box<StyleRefinement>>,
2148 pub(crate) group_hover_style: Option<GroupStyle>,
2149 pub(crate) active_style: Option<Box<StyleRefinement>>,
2150 pub(crate) group_active_style: Option<GroupStyle>,
2151 pub(crate) drag_over_styles: Vec<(
2152 TypeId,
2153 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2154 )>,
2155 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
2156 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
2157 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
2158 pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
2159 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
2160 pub(crate) mouse_exit_listeners: Vec<MouseExitListener>,
2161 pub(crate) file_drop_exit_listeners: Vec<FileDropExitListener>,
2162 pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
2163 pub(crate) pinch_listeners: Vec<PinchListener>,
2164 pub(crate) key_down_listeners: Vec<KeyDownListener>,
2165 pub(crate) key_up_listeners: Vec<KeyUpListener>,
2166 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
2167 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
2168 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
2169 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
2170 pub(crate) click_listeners: Vec<ClickListener>,
2171 pub(crate) aux_click_listeners: Vec<ClickListener>,
2172 pub(crate) drag_listener: Option<DragListener>,
2173 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2174 pub(crate) hover_listener_mode: HoverListenerMode,
2175 pub(crate) tooltip_builder: Option<TooltipBuilder>,
2176 pub(crate) tooltip_show_delay: Option<Duration>,
2177 pub(crate) window_control: Option<WindowControlArea>,
2178 pub(crate) hitbox_behavior: HitboxBehavior,
2179 pub(crate) hitbox_filter: Option<HitboxFilter>,
2183 pub(crate) tab_index: Option<isize>,
2184 pub(crate) tab_group: bool,
2185 pub(crate) tab_stop: bool,
2186
2187 pub(crate) a11y_action_listeners:
2188 Vec<(accesskit::Action, crate::window::a11y::A11yActionListener)>,
2189 pub(crate) a11y_synthetic_children: Option<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2190 pub(crate) report_active_descendant_focus: bool,
2191 pub(crate) override_role: Option<accesskit::Role>,
2192 pub(crate) aria: AriaProperties,
2193
2194 #[cfg(any(feature = "inspector", debug_assertions))]
2195 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2196
2197 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2198 pub(crate) debug_selector: Option<String>,
2199}
2200
2201impl Interactivity {
2202 pub fn request_layout(
2204 &mut self,
2205 global_id: Option<&GlobalElementId>,
2206 window: &mut Window,
2207 cx: &mut App,
2208 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2209 ) -> LayoutId {
2210 #[cfg(any(feature = "inspector", debug_assertions))]
2211 window.with_current_inspector_state(
2212 cx,
2213 |inspector_state: &mut Option<DivInspectorState>, _window| {
2214 if let Some(inspector_state) = inspector_state {
2215 self.base_style = inspector_state.base_style.clone();
2216 } else {
2217 *inspector_state = Some(DivInspectorState {
2218 base_style: self.base_style.clone(),
2219 bounds: Default::default(),
2220 content_size: Default::default(),
2221 })
2222 }
2223 },
2224 );
2225
2226 window.with_optional_element_state::<InteractiveElementState, _>(
2227 global_id,
2228 |element_state, window| {
2229 let mut element_state =
2230 element_state.map(|element_state| element_state.unwrap_or_default());
2231
2232 if let Some(element_state) = element_state.as_ref()
2233 && cx.has_active_drag()
2234 {
2235 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2236 *pending_mouse_down.borrow_mut() = None;
2237 }
2238 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2239 *clicked_state.borrow_mut() = ElementClickedState::default();
2240 }
2241 }
2242
2243 if self.focusable
2248 && self.tracked_focus_handle.is_none()
2249 && let Some(element_state) = element_state.as_mut()
2250 {
2251 let mut handle = element_state
2252 .focus_handle
2253 .get_or_insert_with(|| cx.focus_handle())
2254 .clone()
2255 .tab_stop(self.tab_stop);
2256
2257 if let Some(index) = self.tab_index {
2258 handle = handle.tab_index(index);
2259 }
2260
2261 self.tracked_focus_handle = Some(handle);
2262 }
2263
2264 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2265 let scroll_handle_state = scroll_handle.0.borrow();
2266 self.scroll_offset = Some(scroll_handle_state.offset.clone());
2267 self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2268 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2269 || self.base_style.overflow.y == Some(Overflow::Scroll))
2270 && let Some(element_state) = element_state.as_mut()
2271 {
2272 self.scroll_offset = Some(
2273 element_state
2274 .scroll_offset
2275 .get_or_insert_with(Rc::default)
2276 .clone(),
2277 );
2278 self.ongoing_scroll = Some(
2279 element_state
2280 .ongoing_scroll
2281 .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2282 .clone(),
2283 );
2284 }
2285
2286 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2287 let layout_id = f(style, window, cx);
2288 (layout_id, element_state)
2289 },
2290 )
2291 }
2292
2293 pub fn prepaint<R>(
2295 &mut self,
2296 global_id: Option<&GlobalElementId>,
2297 bounds: Bounds<Pixels>,
2298 content_size: Size<Pixels>,
2299 window: &mut Window,
2300 cx: &mut App,
2301 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2302 ) -> R {
2303 self.content_size = content_size;
2304
2305 #[cfg(any(feature = "inspector", debug_assertions))]
2306 window.with_current_inspector_state(
2307 cx,
2308 |inspector_state: &mut Option<DivInspectorState>, _window| {
2309 if let Some(inspector_state) = inspector_state {
2310 inspector_state.bounds = bounds;
2311 inspector_state.content_size = content_size;
2312 }
2313 },
2314 );
2315
2316 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2317 window.set_focus_handle(focus_handle, cx);
2318
2319 if window.core.a11y.is_active() {
2320 if let Some(global_id) = global_id {
2321 let node_id = global_id.accesskit_node_id();
2322 window.core.a11y.set_focusable(node_id, focus_handle.id);
2323 if focus_handle.is_focused(window) {
2324 window.core.a11y.set_focus(node_id);
2325 }
2326 } else if focus_handle.is_focused(window) {
2327 window
2331 .core
2332 .a11y
2333 .note_focus_without_node(focus_handle.id, "it has no element id");
2334 }
2335 }
2336 }
2337
2338 if self.report_active_descendant_focus && window.core.a11y.is_active() {
2339 if let Some(global_id) = global_id {
2340 window
2341 .core
2342 .a11y
2343 .set_active_descendant(global_id.accesskit_node_id());
2344 }
2345 }
2346 window.with_optional_element_state::<InteractiveElementState, _>(
2347 global_id,
2348 |element_state, window| {
2349 let mut element_state =
2350 element_state.map(|element_state| element_state.unwrap_or_default());
2351 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2352
2353 if let Some(element_state) = element_state.as_mut() {
2354 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2355 let clicked_state = clicked_state.borrow();
2356 self.active = Some(clicked_state.element);
2357 }
2358 if self.hover_style.is_some() || self.group_hover_style.is_some() {
2359 element_state
2360 .hover_state
2361 .get_or_insert_with(Default::default);
2362 }
2363 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2364 if self.tooltip_builder.is_some() {
2365 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2366 } else {
2367 if let Some(long_press_tooltip_active) =
2369 element_state.long_press_tooltip_active.as_ref()
2370 {
2371 long_press_tooltip_active.set(false);
2372 }
2373 element_state.active_tooltip.take();
2374 }
2375 }
2376 }
2377
2378 window.with_text_style(style.text_style().cloned(), |window| {
2379 window.with_content_mask(
2380 style.overflow_mask(bounds, window.rem_size()),
2381 |window| {
2382 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2383 Some(window.insert_hitbox_with_filter(
2384 bounds,
2385 self.hitbox_behavior,
2386 self.hitbox_filter.clone(),
2387 ))
2388 } else {
2389 None
2390 };
2391
2392 let scroll_offset =
2393 self.clamp_scroll_position(bounds, &style, window, cx);
2394 let result = f(&style, scroll_offset, hitbox, window, cx);
2395 (result, element_state)
2396 },
2397 )
2398 })
2399 },
2400 )
2401 }
2402
2403 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2404 self.hitbox_behavior != HitboxBehavior::Normal
2405 || self.window_control.is_some()
2406 || style.mouse_cursor.is_some()
2407 || self.group.is_some()
2408 || self.scroll_offset.is_some()
2409 || self.tracked_focus_handle.is_some()
2410 || self.hover_style.is_some()
2411 || self.group_hover_style.is_some()
2412 || self.hover_listener.is_some()
2413 || !self.mouse_up_listeners.is_empty()
2414 || !self.mouse_pressure_listeners.is_empty()
2415 || !self.mouse_down_listeners.is_empty()
2416 || !self.mouse_move_listeners.is_empty()
2417 || !self.mouse_exit_listeners.is_empty()
2418 || !self.file_drop_exit_listeners.is_empty()
2419 || !self.click_listeners.is_empty()
2420 || !self.aux_click_listeners.is_empty()
2421 || !self.scroll_wheel_listeners.is_empty()
2422 || self.has_pinch_listeners()
2423 || self.drag_listener.is_some()
2424 || !self.drop_listeners.is_empty()
2425 || !self.drag_over_styles.is_empty()
2426 || self.tooltip_builder.is_some()
2427 || window.is_inspector_picking(cx)
2428 }
2429
2430 fn clamp_scroll_position(
2431 &self,
2432 bounds: Bounds<Pixels>,
2433 style: &Style,
2434 window: &mut Window,
2435 _cx: &mut App,
2436 ) -> Point<Pixels> {
2437 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2438 const ROUNDING_FACTOR: f32 = 100.0;
2439 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2440 }
2441
2442 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2443 let mut scroll_to_bottom = false;
2444 let mut tracked_scroll_handle = self
2445 .tracked_scroll_handle
2446 .as_ref()
2447 .map(|handle| handle.0.borrow_mut());
2448 if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2449 scroll_handle_state.overflow = style.overflow;
2450 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2451 }
2452
2453 let rem_size = window.rem_size();
2454 let padding = style
2459 .padding
2460 .to_pixels(bounds.size.into(), rem_size)
2461 .map(|edge| window.pixel_snap(*edge));
2462 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2463 let padded_content_size = self.content_size + padding_size;
2470 let scroll_max = Point::from(padded_content_size - bounds.size)
2471 .map(round_to_two_decimals)
2472 .max(&Default::default());
2473 let mut scroll_offset = scroll_offset.borrow_mut();
2476
2477 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2478 if scroll_to_bottom {
2479 scroll_offset.y = -scroll_max.y;
2480 } else {
2481 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2482 }
2483
2484 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2485 scroll_handle_state.max_offset = scroll_max;
2486 scroll_handle_state.bounds = bounds;
2487 }
2488
2489 *scroll_offset
2490 } else {
2491 Point::default()
2492 }
2493 }
2494
2495 pub fn paint(
2504 &mut self,
2505 global_id: Option<&GlobalElementId>,
2506 bounds: Bounds<Pixels>,
2507 hitbox: Option<&Hitbox>,
2508 window: &mut Window,
2509 cx: &mut App,
2510 f: impl FnOnce(&Style, &mut Window, &mut App),
2511 ) {
2512 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2513 window.with_optional_element_state::<InteractiveElementState, _>(
2514 global_id,
2515 |element_state, window| {
2516 let mut element_state =
2517 element_state.map(|element_state| element_state.unwrap_or_default());
2518
2519 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2520
2521 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2522 if let Some(debug_selector) = &self.debug_selector {
2523 window
2524 .frame_state
2525 .next_frame
2526 .record_debug_bounds(debug_selector.clone(), bounds);
2527 }
2528
2529 self.paint_hover_group_handler(window, cx);
2530
2531 if style.visibility == Visibility::Hidden {
2532 return ((), element_state);
2533 }
2534
2535 let mut tab_group = None;
2536 if self.tab_group {
2537 tab_group = self.tab_index;
2538 }
2539
2540 window.with_element_opacity(style.opacity, |window| {
2541 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2542 window.with_text_style(style.text_style().cloned(), |window| {
2543 window.with_content_mask(
2544 style.overflow_mask(bounds, window.rem_size()),
2545 |window| {
2546 window.with_tab_group(tab_group, |window| {
2547 if let Some(focus_handle) = &self.tracked_focus_handle {
2556 window
2557 .frame_state
2558 .next_frame
2559 .tab_stops
2560 .insert(focus_handle);
2561 }
2562 if let Some(hitbox) = hitbox {
2563 #[cfg(debug_assertions)]
2564 self.paint_debug_info(
2565 global_id, hitbox, &style, window, cx,
2566 );
2567
2568 if let Some(drag) = cx.active_drag.as_ref() {
2569 if let Some(mouse_cursor) = drag.cursor_style {
2570 window.set_window_cursor_style(mouse_cursor);
2571 }
2572 } else {
2573 if let Some(mouse_cursor) = style.mouse_cursor {
2574 window.set_cursor_style(mouse_cursor, hitbox);
2575 }
2576 }
2577
2578 if let Some(group) = self.group.clone() {
2579 GroupHitboxes::push(group, hitbox.id, cx);
2580 }
2581
2582 if let Some(area) = self.window_control {
2583 window.insert_window_control_hitbox(
2584 area,
2585 hitbox.clone(),
2586 );
2587 }
2588
2589 self.paint_mouse_listeners(
2590 hitbox,
2591 element_state.as_mut(),
2592 window,
2593 cx,
2594 );
2595 self.paint_scroll_listener(hitbox, &style, window, cx);
2596 }
2597
2598 self.paint_keyboard_listeners(window, cx);
2599
2600 if window.core.a11y.is_active() {
2601 if let Some(global_id) = global_id {
2602 if !self.a11y_action_listeners.is_empty() {
2603 let node_id = global_id.accesskit_node_id();
2604 for (action, listener) in
2605 self.a11y_action_listeners.drain(..)
2606 {
2607 window.on_a11y_action(
2608 node_id, action, listener,
2609 );
2610 }
2611 }
2612 }
2613 }
2614
2615 f(&style, window, cx);
2616
2617 if let Some(_hitbox) = hitbox {
2618 #[cfg(any(feature = "inspector", debug_assertions))]
2619 window.insert_inspector_hitbox(_hitbox.id, cx);
2620
2621 if let Some(group) = self.group.as_ref() {
2622 GroupHitboxes::pop(group, cx);
2623 }
2624 }
2625 })
2626 },
2627 );
2628 });
2629 });
2630 });
2631
2632 ((), element_state)
2633 },
2634 );
2635 }
2636
2637 #[cfg(debug_assertions)]
2638 fn paint_debug_info(
2639 &self,
2640 global_id: Option<&GlobalElementId>,
2641 hitbox: &Hitbox,
2642 style: &Style,
2643 window: &mut Window,
2644 cx: &mut App,
2645 ) {
2646 use crate::{BorderStyle, TextAlign};
2647
2648 if let Some(global_id) = global_id
2649 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2650 && hitbox.is_hovered(window)
2651 {
2652 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2653 let element_id = format!("{global_id:?}");
2654 let str_len = element_id.len();
2655
2656 let render_debug_text = |window: &mut Window| {
2657 if let Some(text) = window
2658 .text_system()
2659 .shape_text(
2660 element_id.into(),
2661 FONT_SIZE,
2662 &[window.text_style().to_run(str_len)],
2663 None,
2664 None,
2665 )
2666 .ok()
2667 .and_then(|mut text| text.pop())
2668 {
2669 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2670 .ok();
2671
2672 let text_bounds = crate::Bounds {
2673 origin: hitbox.origin,
2674 size: text.size(FONT_SIZE),
2675 };
2676 if let Some(source_location) = self.source_location
2677 && text_bounds.contains(&window.mouse_position())
2678 && window.modifiers().secondary()
2679 {
2680 let secondary_held = window.modifiers().secondary();
2681 window.on_key_event({
2682 move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2683 if e.modifiers.secondary() != secondary_held
2684 && text_bounds.contains(&window.mouse_position())
2685 {
2686 window.refresh();
2687 }
2688 }
2689 });
2690
2691 let was_hovered = hitbox.is_hovered(window);
2692 let current_view = window.current_view();
2693 window.on_mouse_event({
2694 let hitbox = hitbox.clone();
2695 move |_: &MouseMoveEvent, phase, window, cx| {
2696 if phase == DispatchPhase::Capture {
2697 let hovered = hitbox.is_hovered(window);
2698 if hovered != was_hovered {
2699 cx.notify(current_view)
2700 }
2701 }
2702 }
2703 });
2704
2705 window.on_mouse_event({
2706 let hitbox = hitbox.clone();
2707 move |e: &crate::MouseDownEvent, phase, window, cx| {
2708 if text_bounds.contains(&e.position)
2709 && phase.capture()
2710 && hitbox.is_hovered(window)
2711 {
2712 cx.stop_propagation();
2713 let Ok(dir) = std::env::current_dir() else {
2714 return;
2715 };
2716
2717 eprintln!(
2718 "This element was created at:\n{}:{}:{}",
2719 dir.join(source_location.file()).to_string_lossy(),
2720 source_location.line(),
2721 source_location.column()
2722 );
2723 }
2724 }
2725 });
2726 window.paint_quad(crate::outline(
2727 crate::Bounds {
2728 origin: hitbox.origin
2729 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2730 size: crate::Size {
2731 width: text_bounds.size.width,
2732 height: crate::px(1.),
2733 },
2734 },
2735 crate::red(),
2736 BorderStyle::default(),
2737 ))
2738 }
2739 }
2740 };
2741
2742 window.with_text_style(
2743 Some(crate::TextStyleRefinement {
2744 color: Some(crate::red()),
2745 line_height: Some(FONT_SIZE.into()),
2746 background_color: Some(crate::white()),
2747 ..Default::default()
2748 }),
2749 render_debug_text,
2750 )
2751 }
2752 }
2753
2754 fn paint_mouse_listeners(
2755 &mut self,
2756 hitbox: &Hitbox,
2757 element_state: Option<&mut InteractiveElementState>,
2758 window: &mut Window,
2759 cx: &mut App,
2760 ) {
2761 let is_focused = self
2762 .tracked_focus_handle
2763 .as_ref()
2764 .map(|handle| handle.is_focused(window))
2765 .unwrap_or(false);
2766
2767 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2771 let hitbox = hitbox.clone();
2772 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2773 if phase == DispatchPhase::Bubble
2774 && hitbox.is_hovered(window)
2775 && !window.default_prevented()
2776 {
2777 window.focus(&focus_handle, cx);
2778 window.prevent_default();
2781 }
2782 });
2783 }
2784
2785 for listener in self.mouse_down_listeners.drain(..) {
2786 let hitbox = hitbox.clone();
2787 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2788 listener(event, phase, &hitbox, window, cx);
2789 })
2790 }
2791
2792 for listener in self.mouse_up_listeners.drain(..) {
2793 let hitbox = hitbox.clone();
2794 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2795 listener(event, phase, &hitbox, window, cx);
2796 })
2797 }
2798
2799 for listener in self.mouse_pressure_listeners.drain(..) {
2800 let hitbox = hitbox.clone();
2801 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2802 listener(event, phase, &hitbox, window, cx);
2803 })
2804 }
2805
2806 for listener in self.mouse_move_listeners.drain(..) {
2807 let hitbox = hitbox.clone();
2808 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2809 listener(event, phase, &hitbox, window, cx);
2810 })
2811 }
2812
2813 for listener in self.mouse_exit_listeners.drain(..) {
2814 let hitbox = hitbox.clone();
2815 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2816 listener(event, phase, &hitbox, window, cx);
2817 })
2818 }
2819
2820 for listener in self.file_drop_exit_listeners.drain(..) {
2821 let hitbox = hitbox.clone();
2822 window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
2823 listener(event, phase, &hitbox, window, cx);
2824 })
2825 }
2826
2827 for listener in self.scroll_wheel_listeners.drain(..) {
2828 let hitbox = hitbox.clone();
2829 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2830 listener(event, phase, &hitbox, window, cx);
2831 })
2832 }
2833
2834 for listener in self.pinch_listeners.drain(..) {
2835 let hitbox = hitbox.clone();
2836 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2837 listener(event, phase, &hitbox, window, cx);
2838 })
2839 }
2840
2841 if self.hover_style.is_some()
2842 || self.base_style.mouse_cursor.is_some()
2843 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2844 {
2845 let hitbox = hitbox.clone();
2846 let hover_state = self.hover_style.as_ref().and_then(|_| {
2847 element_state
2848 .as_ref()
2849 .and_then(|state| state.hover_state.as_ref())
2850 .cloned()
2851 });
2852 let current_view = window.current_view();
2853
2854 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2855 let hovered = hitbox.is_hovered(window);
2856 let was_hovered = hover_state
2857 .as_ref()
2858 .is_some_and(|state| state.borrow().element);
2859 if phase == DispatchPhase::Capture && hovered != was_hovered {
2860 if let Some(hover_state) = &hover_state {
2861 hover_state.borrow_mut().element = hovered;
2862 cx.notify(current_view);
2863 }
2864 }
2865 });
2866 }
2867
2868 if let Some(group_hover) = self.group_hover_style.as_ref() {
2869 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2870 let hover_state = element_state
2871 .as_ref()
2872 .and_then(|element| element.hover_state.as_ref())
2873 .cloned();
2874 let current_view = window.current_view();
2875
2876 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2877 let group_hovered = group_hitbox_id.is_hovered(window);
2878 let was_group_hovered = hover_state
2879 .as_ref()
2880 .is_some_and(|state| state.borrow().group);
2881 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2882 if let Some(hover_state) = &hover_state {
2883 hover_state.borrow_mut().group = group_hovered;
2884 cx.notify(current_view);
2885 }
2886 }
2887 });
2888 }
2889 }
2890
2891 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2892
2893 let mut drag_listener = mem::take(&mut self.drag_listener);
2894 let drop_listeners = mem::take(&mut self.drop_listeners);
2895 let click_listeners = mem::take(&mut self.click_listeners);
2896 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2897 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2898
2899 if !drop_listeners.is_empty() {
2900 let hitbox = hitbox.clone();
2901 window.on_mouse_event({
2902 move |_: &MouseUpEvent, phase, window, cx| {
2903 if let Some(drag) = &cx.active_drag
2904 && phase == DispatchPhase::Bubble
2905 && hitbox.is_hovered(window)
2906 {
2907 let drag_state_type = drag.value.as_ref().type_id();
2908 for (drop_state_type, listener) in &drop_listeners {
2909 if *drop_state_type == drag_state_type {
2910 let drag = cx
2911 .active_drag
2912 .take()
2913 .expect("checked for type drag state type above");
2914
2915 let mut can_drop = true;
2916 if let Some(predicate) = &can_drop_predicate {
2917 can_drop = predicate(drag.value.as_ref(), window, cx);
2918 }
2919
2920 if can_drop {
2921 listener(drag.value.as_ref(), window, cx);
2922 window.refresh();
2923 cx.stop_propagation();
2924 }
2925 }
2926 }
2927 }
2928 }
2929 });
2930 }
2931
2932 if let Some(element_state) = element_state {
2933 if !click_listeners.is_empty()
2934 || !aux_click_listeners.is_empty()
2935 || drag_listener.is_some()
2936 {
2937 let pending_mouse_down = element_state
2938 .pending_mouse_down
2939 .get_or_insert_with(Default::default)
2940 .clone();
2941
2942 let pending_keyboard_down = element_state
2943 .pending_keyboard_down
2944 .get_or_insert_with(Default::default)
2945 .clone();
2946
2947 let clicked_state = element_state
2948 .clicked_state
2949 .get_or_insert_with(Default::default)
2950 .clone();
2951
2952 window.on_mouse_event({
2953 let pending_mouse_down = pending_mouse_down.clone();
2954 let hitbox = hitbox.clone();
2955 let has_aux_click_listeners = !aux_click_listeners.is_empty();
2956 move |event: &MouseDownEvent, phase, window, _cx| {
2957 if phase == DispatchPhase::Bubble
2958 && (event.button == MouseButton::Left || has_aux_click_listeners)
2959 && hitbox.is_hovered(window)
2960 {
2961 *pending_mouse_down.borrow_mut() = Some(event.clone());
2962 window.refresh();
2963 }
2964 }
2965 });
2966
2967 window.on_mouse_event({
2968 let pending_mouse_down = pending_mouse_down.clone();
2969 let hitbox = hitbox.clone();
2970 move |event: &MouseMoveEvent, phase, window, cx| {
2971 if phase == DispatchPhase::Capture {
2972 return;
2973 }
2974
2975 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2976 if let Some(mouse_down) = pending_mouse_down.clone()
2977 && !cx.has_active_drag()
2978 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2979 && let Some(listener) = drag_listener.take()
2980 && mouse_down.button == MouseButton::Left
2981 {
2982 *clicked_state.borrow_mut() = ElementClickedState::default();
2983 let cursor_offset = event.position - hitbox.origin;
2984 let drag = (listener.render)(
2985 listener.value.as_ref(),
2986 cursor_offset,
2987 window,
2988 cx,
2989 );
2990 let external_payload_source =
2991 listener.external_payload.map(|external_payload| {
2992 let value = listener.value.clone();
2993 Box::new(move |window: &mut Window, cx: &mut App| {
2994 external_payload(value.as_ref(), window, cx)
2995 })
2996 as ExternalDragPayloadSource
2997 });
2998 cx.active_drag = Some(AnyDrag {
2999 view: drag,
3000 value: listener.value,
3001 cursor_offset,
3002 cursor_style: drag_cursor_style,
3003 external_payload_source,
3004 });
3005 pending_mouse_down.take();
3006 window.refresh();
3007 cx.stop_propagation();
3008 }
3009 }
3010 });
3011
3012 if is_focused {
3013 window.on_key_event({
3023 let pending_keyboard_down = pending_keyboard_down.clone();
3024 move |event: &KeyDownEvent, phase, window, _cx| {
3025 if phase.bubble() && !window.default_prevented() {
3026 let stroke = &event.keystroke;
3027 let is_activation_key = (stroke.key.eq("enter")
3028 || stroke.key.eq("space"))
3029 && !stroke.modifiers.modified();
3030 *pending_keyboard_down.borrow_mut() =
3031 is_activation_key.then_some(window.core.focus_generation);
3032 }
3033 }
3034 });
3035
3036 window.on_key_event({
3038 let click_listeners = click_listeners.clone();
3039 let hitbox = hitbox.clone();
3040 move |event: &KeyUpEvent, phase, window, cx| {
3041 if phase.bubble() && !window.default_prevented() {
3042 let stroke = &event.keystroke;
3043 let keyboard_button = if stroke.key.eq("enter") {
3044 Some(KeyboardButton::Enter)
3045 } else if stroke.key.eq("space") {
3046 Some(KeyboardButton::Space)
3047 } else {
3048 None
3049 };
3050
3051 if let Some(button) = keyboard_button
3052 && !stroke.modifiers.modified()
3053 {
3054 let pending =
3055 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
3056 if pending != Some(window.core.focus_generation) {
3057 return;
3058 }
3059
3060 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
3061 button,
3062 bounds: hitbox.bounds,
3063 });
3064
3065 for listener in &click_listeners {
3066 listener(&click_event, window, cx);
3067 }
3068 } else {
3069 *pending_keyboard_down.borrow_mut() = None;
3073 }
3074 }
3075 }
3076 });
3077 }
3078
3079 window.on_mouse_event({
3080 let mut captured_mouse_down = None;
3081 let hitbox = hitbox.clone();
3082 move |event: &MouseUpEvent, phase, window, cx| match phase {
3083 DispatchPhase::Capture => {
3087 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3088 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
3089 captured_mouse_down = pending_mouse_down.take();
3090 window.refresh();
3091 } else if pending_mouse_down.is_some() {
3092 pending_mouse_down.take();
3098 window.refresh();
3099 }
3100 }
3101 DispatchPhase::Bubble => {
3103 if let Some(mouse_down) = captured_mouse_down.take() {
3104 let btn = mouse_down.button;
3105
3106 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
3107 down: mouse_down,
3108 up: event.clone(),
3109 });
3110
3111 match btn {
3112 MouseButton::Left => {
3113 for listener in &click_listeners {
3114 listener(&mouse_click, window, cx);
3115 }
3116 }
3117 _ => {
3118 for listener in &aux_click_listeners {
3119 listener(&mouse_click, window, cx);
3120 }
3121 }
3122 }
3123 }
3124 }
3125 }
3126 });
3127 }
3128
3129 if let Some(hover_listener) = self.hover_listener.take() {
3130 let was_hovered = element_state
3131 .hover_listener_state
3132 .get_or_insert_with(Default::default)
3133 .clone();
3134 let has_mouse_down = element_state
3135 .pending_mouse_down
3136 .get_or_insert_with(Default::default)
3137 .clone();
3138 let hover_listener = Rc::new(hover_listener);
3139 let hover_listener_state = was_hovered.clone();
3140 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3141 let mut was_hovered = hover_listener_state.borrow_mut();
3142 if is_hovered != *was_hovered {
3143 *was_hovered = is_hovered;
3144 drop(was_hovered);
3145 hover_listener(&is_hovered, window, cx);
3146 }
3147 };
3148 let hover_listener_mode = self.hover_listener_mode;
3149
3150 if has_mouse_down.borrow().is_none() {
3151 let is_hovered =
3152 !cx.has_active_drag() && hover_listener_mode.is_hovered(hitbox, window);
3153 if is_hovered != *was_hovered.borrow() {
3154 let update_hover = update_hover.clone();
3155 window.defer(cx, move |window, cx| {
3156 update_hover(is_hovered, window, cx);
3157 });
3158 }
3159 }
3160
3161 window.on_mouse_event({
3162 let update_hover = update_hover.clone();
3163 let hitbox = hitbox.clone();
3164 move |_: &MouseMoveEvent, phase, window, cx| {
3165 if phase == DispatchPhase::Bubble {
3166 let is_hovered = has_mouse_down.borrow().is_none()
3167 && !cx.has_active_drag()
3168 && hover_listener_mode.is_hovered(&hitbox, window);
3169 update_hover(is_hovered, window, cx);
3170 }
3171 }
3172 });
3173
3174 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3177 if phase == DispatchPhase::Bubble {
3178 update_hover(false, window, cx);
3179 }
3180 });
3181 }
3182
3183 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3184 let active_tooltip = element_state
3185 .active_tooltip
3186 .get_or_insert_with(Default::default)
3187 .clone();
3188 let pending_mouse_down = element_state
3189 .pending_mouse_down
3190 .get_or_insert_with(Default::default)
3191 .clone();
3192 let long_press_tooltip_active = element_state
3193 .long_press_tooltip_active
3194 .get_or_insert_with(Default::default)
3195 .clone();
3196
3197 let tooltip_is_hoverable = tooltip_builder.hoverable;
3198 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3199 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3200 });
3201 let check_is_hovered_during_prepaint = Rc::new({
3203 let pending_mouse_down = pending_mouse_down.clone();
3204 let source_bounds = hitbox.bounds;
3205 move |window: &Window| {
3206 !window.last_input_was_keyboard()
3207 && pending_mouse_down.borrow().is_none()
3208 && source_bounds.contains(&window.mouse_position())
3209 }
3210 });
3211 let check_is_hovered = Rc::new({
3212 let hitbox = hitbox.clone();
3213 move |window: &Window| {
3214 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3215 }
3216 });
3217 register_tooltip_mouse_handlers(
3218 &active_tooltip,
3219 self.tooltip_id,
3220 build_tooltip,
3221 check_is_hovered,
3222 check_is_hovered_during_prepaint,
3223 long_press_tooltip_active,
3224 self.tooltip_show_delay,
3225 window,
3226 );
3227 }
3228
3229 let active_state = element_state
3232 .clicked_state
3233 .get_or_insert_with(Default::default)
3234 .clone();
3235
3236 {
3237 let active_state = active_state.clone();
3238 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3239 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3240 *active_state.borrow_mut() = ElementClickedState::default();
3241 window.refresh();
3242 }
3243 });
3244 }
3245
3246 {
3247 let active_group_hitbox = self
3248 .group_active_style
3249 .as_ref()
3250 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3251 let hitbox = hitbox.clone();
3252 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3253 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3254 let group_hovered = active_group_hitbox
3255 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3256 let element_hovered = hitbox.is_hovered(window);
3257 if group_hovered || element_hovered {
3258 *active_state.borrow_mut() = ElementClickedState {
3259 group: group_hovered,
3260 element: element_hovered,
3261 };
3262 window.refresh();
3263 }
3264 }
3265 });
3266 }
3267 }
3268 }
3269
3270 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3271 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3272 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3273 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3274 let action_listeners = mem::take(&mut self.action_listeners);
3275 if let Some(context) = self.key_context.clone() {
3276 window.set_key_context(context);
3277 }
3278
3279 for listener in key_down_listeners {
3280 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3281 listener(event, phase, window, cx);
3282 })
3283 }
3284
3285 for listener in key_up_listeners {
3286 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3287 listener(event, phase, window, cx);
3288 })
3289 }
3290
3291 for listener in modifiers_changed_listeners {
3292 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3293 listener(event, window, cx);
3294 })
3295 }
3296
3297 for (action_type, listener) in action_listeners {
3298 window.on_action(action_type, listener)
3299 }
3300 }
3301
3302 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3303 let group_hitbox = self
3304 .group_hover_style
3305 .as_ref()
3306 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3307
3308 if let Some(group_hitbox) = group_hitbox {
3309 let was_hovered = group_hitbox.is_hovered(window);
3310 let current_view = window.current_view();
3311 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3312 let hovered = group_hitbox.is_hovered(window);
3313 if phase == DispatchPhase::Capture && hovered != was_hovered {
3314 cx.notify(current_view);
3315 }
3316 });
3317 }
3318 }
3319
3320 fn paint_scroll_listener(
3321 &self,
3322 hitbox: &Hitbox,
3323 style: &Style,
3324 window: &mut Window,
3325 _cx: &mut App,
3326 ) {
3327 if let Some(scroll_offset) = self.scroll_offset.clone() {
3328 let ongoing_scroll = self.ongoing_scroll.clone();
3329 let overflow = style.overflow;
3330 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3331 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3332 let line_height = window.line_height();
3333 let hitbox = hitbox.clone();
3334 let current_view = window.current_view();
3335 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
3336 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3337 let mut scroll_offset = scroll_offset.borrow_mut();
3338 let old_scroll_offset = *scroll_offset;
3339 let mut delta = event.delta.pixel_delta(line_height);
3340
3341 if restrict_scroll_to_axis
3342 && event.delta.precise()
3343 && let Some(ongoing_scroll) = &ongoing_scroll
3344 {
3345 ongoing_scroll
3346 .borrow_mut()
3347 .filter(&mut delta, event.touch_phase);
3348 }
3349
3350 let mut delta_x = match overflow.x {
3351 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3352 Overflow::Scroll
3353 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3354 {
3355 delta.y
3356 }
3357 _ => Pixels::ZERO,
3358 };
3359 let mut delta_y = match overflow.y {
3360 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3361 Overflow::Scroll
3362 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3363 {
3364 delta.x
3365 }
3366 _ => Pixels::ZERO,
3367 };
3368 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3369 if delta_x.abs() > delta_y.abs() {
3370 delta_y = Pixels::ZERO;
3371 } else {
3372 delta_x = Pixels::ZERO;
3373 }
3374 }
3375 scroll_offset.y += delta_y;
3376 scroll_offset.x += delta_x;
3377 if *scroll_offset != old_scroll_offset {
3378 cx.notify(current_view);
3379 }
3380 }
3381 });
3382 }
3383 }
3384
3385 pub fn compute_style(
3387 &self,
3388 global_id: Option<&GlobalElementId>,
3389 hitbox: Option<&Hitbox>,
3390 window: &mut Window,
3391 cx: &mut App,
3392 ) -> Style {
3393 window.with_optional_element_state(global_id, |element_state, window| {
3394 let mut element_state =
3395 element_state.map(|element_state| element_state.unwrap_or_default());
3396 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3397 (style, element_state)
3398 })
3399 }
3400
3401 fn compute_style_internal(
3403 &self,
3404 hitbox: Option<&Hitbox>,
3405 element_state: Option<&mut InteractiveElementState>,
3406 window: &mut Window,
3407 cx: &mut App,
3408 ) -> Style {
3409 let mut style = Style::default();
3410 style.refine(&self.base_style);
3411
3412 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3413 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3414 && focus_handle.within_focused(window, cx)
3415 {
3416 style.refine(in_focus_style);
3417 }
3418
3419 if let Some(focus_style) = self.focus_style.as_ref()
3420 && focus_handle.is_focused(window)
3421 {
3422 style.refine(focus_style);
3423 }
3424
3425 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3426 && focus_handle.is_focused(window)
3427 && window.last_input_was_keyboard()
3428 {
3429 style.refine(focus_visible_style);
3430 }
3431 }
3432
3433 if !cx.has_active_drag() {
3434 if let Some(group_hover) = self.group_hover_style.as_ref() {
3435 let is_group_hovered =
3436 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3437 !window.last_input_was_touch() && group_hitbox_id.is_hovered(window)
3438 } else if let Some(element_state) = element_state.as_ref() {
3439 !window.last_input_was_touch()
3440 && element_state
3441 .hover_state
3442 .as_ref()
3443 .map(|state| state.borrow().group)
3444 .unwrap_or(false)
3445 } else {
3446 false
3447 };
3448
3449 if is_group_hovered {
3450 style.refine(&group_hover.style);
3451 }
3452 }
3453
3454 if let Some(hover_style) = self.hover_style.as_ref() {
3455 let is_hovered = if let Some(hitbox) = hitbox {
3456 !window.last_input_was_touch() && hitbox.is_hovered(window)
3457 } else if let Some(element_state) = element_state.as_ref() {
3458 !window.last_input_was_touch()
3459 && element_state
3460 .hover_state
3461 .as_ref()
3462 .map(|state| state.borrow().element)
3463 .unwrap_or(false)
3464 } else {
3465 false
3466 };
3467
3468 if is_hovered {
3469 style.refine(hover_style);
3470 }
3471 }
3472 }
3473
3474 if let Some(hitbox) = hitbox {
3475 if let Some(drag) = cx.active_drag.take() {
3476 let mut can_drop = true;
3477 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3478 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3479 }
3480
3481 if can_drop {
3482 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3483 if let Some(group_hitbox_id) =
3484 GroupHitboxes::get(&group_drag_style.group, cx)
3485 && *state_type == drag.value.as_ref().type_id()
3486 && group_hitbox_id.is_hovered(window)
3487 {
3488 style.refine(&group_drag_style.style);
3489 }
3490 }
3491
3492 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3493 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3494 {
3495 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3496 }
3497 }
3498 }
3499
3500 style.mouse_cursor = drag.cursor_style;
3501 cx.active_drag = Some(drag);
3502 }
3503 }
3504
3505 if let Some(element_state) = element_state {
3506 let clicked_state = element_state
3507 .clicked_state
3508 .get_or_insert_with(Default::default)
3509 .borrow();
3510 if clicked_state.group
3511 && let Some(group) = self.group_active_style.as_ref()
3512 {
3513 style.refine(&group.style)
3514 }
3515
3516 if let Some(active_style) = self.active_style.as_ref()
3517 && clicked_state.element
3518 {
3519 style.refine(active_style)
3520 }
3521 }
3522
3523 style
3524 }
3525
3526 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3527 if let Some(id) = &self.aria.author_id {
3528 node.set_author_id(id.to_string());
3529 }
3530 if let Some(label) = &self.aria.label {
3531 node.set_label(label.to_string());
3532 }
3533 if let Some(description) = &self.aria.description {
3534 node.set_description(description.to_string());
3535 }
3536 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3537 node.set_keyboard_shortcut(keyshortcuts.to_string());
3538 }
3539 if let Some(selected) = self.aria.selected {
3540 node.set_selected(selected);
3541 }
3542 if let Some(expanded) = self.aria.expanded {
3543 node.set_expanded(expanded);
3544 }
3545 if let Some(toggled) = self.aria.toggled {
3546 node.set_toggled(toggled);
3547 }
3548 if let Some(value) = self.aria.numeric_value {
3549 node.set_numeric_value(value);
3550 }
3551 if let Some(value) = self.aria.min_numeric_value {
3552 node.set_min_numeric_value(value);
3553 }
3554 if let Some(value) = self.aria.max_numeric_value {
3555 node.set_max_numeric_value(value);
3556 }
3557 if let Some(step) = self.aria.numeric_value_step {
3558 node.set_numeric_value_step(step);
3559 }
3560 if let Some(value) = &self.aria.value {
3561 node.set_value(value.to_string());
3562 }
3563 if let Some(placeholder) = &self.aria.placeholder {
3564 node.set_placeholder(placeholder.to_string());
3565 }
3566 if let Some(orientation) = self.aria.orientation {
3567 node.set_orientation(orientation);
3568 }
3569 if let Some(level) = self.aria.level {
3570 node.set_level(level);
3571 }
3572 if let Some(position) = self.aria.position_in_set {
3573 node.set_position_in_set(position);
3574 }
3575 if let Some(size) = self.aria.size_of_set {
3576 node.set_size_of_set(size);
3577 }
3578 if let Some(index) = self.aria.row_index {
3579 node.set_row_index(index);
3580 }
3581 if let Some(index) = self.aria.column_index {
3582 node.set_column_index(index);
3583 }
3584 if let Some(count) = self.aria.row_count {
3585 node.set_row_count(count);
3586 }
3587 if let Some(count) = self.aria.column_count {
3588 node.set_column_count(count);
3589 }
3590 if !self.click_listeners.is_empty() {
3591 node.add_action(accesskit::Action::Click);
3592 }
3593 if self.tracked_focus_handle.is_some() || self.focusable {
3594 node.add_action(accesskit::Action::Focus);
3595 }
3596 for (action, _) in &self.a11y_action_listeners {
3597 node.add_action(*action);
3598 }
3599 }
3600}
3601
3602#[derive(Default)]
3605pub struct InteractiveElementState {
3606 pub(crate) focus_handle: Option<FocusHandle>,
3607 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3608 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3609 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3610 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3611 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3619 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3620 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3621 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3622 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3623}
3624
3625#[derive(Copy, Clone, Default, Eq, PartialEq)]
3627pub struct ElementClickedState {
3628 pub group: bool,
3630
3631 pub element: bool,
3633}
3634
3635impl ElementClickedState {
3636 fn is_clicked(&self) -> bool {
3637 self.group || self.element
3638 }
3639}
3640
3641#[derive(Copy, Clone, Default, Eq, PartialEq)]
3643pub struct ElementHoverState {
3644 pub group: bool,
3646
3647 pub element: bool,
3649}
3650
3651pub(crate) enum ActiveTooltip {
3652 WaitingForShow { _task: Task<()> },
3654 Visible {
3656 tooltip: AnyTooltip,
3657 is_hoverable: bool,
3658 },
3659 WaitingForHide {
3662 tooltip: AnyTooltip,
3663 _task: Task<()>,
3664 },
3665}
3666
3667pub(crate) fn clear_active_tooltip(
3668 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3669 window: &mut Window,
3670) {
3671 match active_tooltip.borrow_mut().take() {
3672 None => {}
3673 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3674 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3675 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3676 }
3677}
3678
3679pub(crate) fn clear_active_tooltip_if_not_hoverable(
3680 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3681 window: &mut Window,
3682) {
3683 let should_clear = match active_tooltip.borrow().as_ref() {
3684 None => false,
3685 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3686 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3687 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3688 };
3689 if should_clear {
3690 active_tooltip.borrow_mut().take();
3691 window.refresh();
3692 }
3693}
3694
3695pub(crate) fn set_tooltip_on_window(
3696 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3697 window: &mut Window,
3698) -> Option<TooltipId> {
3699 let tooltip = match active_tooltip.borrow().as_ref() {
3700 None => return None,
3701 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3702 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3703 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3704 };
3705 Some(window.set_tooltip(tooltip))
3706}
3707
3708pub(crate) fn register_tooltip_mouse_handlers(
3709 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3710 tooltip_id: Option<TooltipId>,
3711 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3712 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3713 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3714 long_press_tooltip_active: Rc<Cell<bool>>,
3715 show_delay: Option<Duration>,
3716 window: &mut Window,
3717) {
3718 let current_view = window.current_view();
3719 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3720
3721 window.on_mouse_event({
3722 let active_tooltip = active_tooltip.clone();
3723 let build_tooltip = build_tooltip.clone();
3724 let check_is_hovered = check_is_hovered.clone();
3725 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3726 move |_: &MouseMoveEvent, phase, window, cx| {
3727 handle_tooltip_mouse_move(
3728 &active_tooltip,
3729 &build_tooltip,
3730 &check_is_hovered,
3731 &check_is_hovered_during_prepaint,
3732 tooltip_id,
3733 current_view,
3734 phase,
3735 show_delay,
3736 window,
3737 cx,
3738 )
3739 }
3740 });
3741
3742 window.on_mouse_event({
3743 let active_tooltip = active_tooltip.clone();
3744 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3745 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3746 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3747 }
3748 }
3749 });
3750
3751 window.on_mouse_event({
3752 let active_tooltip = active_tooltip.clone();
3753 let build_tooltip = build_tooltip.clone();
3754 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3755 move |event: &LongPressEvent, phase, window, cx| {
3756 if !phase.bubble() {
3757 return;
3758 }
3759
3760 match event.phase {
3761 TouchPhase::Started if !window.default_prevented() && check_is_hovered(window) => {
3762 if show_tooltip(
3763 &active_tooltip,
3764 &build_tooltip,
3765 &check_is_hovered_during_prepaint,
3766 Some(long_press_tooltip_active.clone()),
3767 window,
3768 cx,
3769 ) {
3770 long_press_tooltip_active.set(true);
3771 window.prevent_default();
3772 cx.stop_propagation();
3773 }
3774 }
3775 TouchPhase::Ended | TouchPhase::Cancelled
3776 if long_press_tooltip_active.replace(false) =>
3777 {
3778 clear_active_tooltip(&active_tooltip, window);
3779 cx.stop_propagation();
3780 }
3781 TouchPhase::Started
3782 | TouchPhase::Moved
3783 | TouchPhase::Ended
3784 | TouchPhase::Cancelled => {}
3785 }
3786 }
3787 });
3788
3789 window.on_mouse_event({
3790 let active_tooltip = active_tooltip.clone();
3791 move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
3792 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3793 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3794 }
3795 }
3796 });
3797}
3798
3799fn handle_tooltip_mouse_move(
3811 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3812 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3813 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3814 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3815 tooltip_id: Option<TooltipId>,
3816 current_view: EntityId,
3817 phase: DispatchPhase,
3818 show_delay: Duration,
3819 window: &mut Window,
3820 cx: &mut App,
3821) {
3822 enum Action {
3825 None,
3826 CancelShow,
3827 ScheduleShow,
3828 CheckVisible,
3829 }
3830
3831 let action = match active_tooltip.borrow().as_ref() {
3832 None => {
3833 let is_hovered = check_is_hovered(window);
3834 if is_hovered && phase.bubble() {
3835 Action::ScheduleShow
3836 } else {
3837 Action::None
3838 }
3839 }
3840 Some(ActiveTooltip::WaitingForShow { .. }) => {
3841 let is_hovered = check_is_hovered(window);
3842 if is_hovered {
3843 Action::None
3844 } else {
3845 Action::CancelShow
3846 }
3847 }
3848 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3849 if phase.capture()
3850 && !check_is_hovered(window)
3851 && (!*is_hoverable
3852 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3853 {
3854 Action::CheckVisible
3855 } else {
3856 Action::None
3857 }
3858 }
3859 Some(ActiveTooltip::WaitingForHide { .. }) => {
3860 if phase.capture()
3861 && (check_is_hovered(window)
3862 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3863 {
3864 Action::CheckVisible
3865 } else {
3866 Action::None
3867 }
3868 }
3869 };
3870
3871 match action {
3872 Action::None => {}
3873 Action::CancelShow => {
3874 active_tooltip.borrow_mut().take();
3876 }
3877 Action::ScheduleShow => {
3878 let delayed_show_task = window.spawn(cx, {
3879 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3880 let build_tooltip = build_tooltip.clone();
3881 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3882 async move |cx| {
3883 cx.background_executor().timer(show_delay).await;
3884 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3885 return;
3886 };
3887 cx.update(|window, cx| {
3888 show_tooltip(
3889 &active_tooltip,
3890 &build_tooltip,
3891 &check_is_hovered_during_prepaint,
3892 None,
3893 window,
3894 cx,
3895 );
3896 })
3897 .ok();
3898 }
3899 });
3900 active_tooltip
3901 .borrow_mut()
3902 .replace(ActiveTooltip::WaitingForShow {
3903 _task: delayed_show_task,
3904 });
3905 }
3906 Action::CheckVisible => cx.notify(current_view),
3907 }
3908}
3909
3910fn show_tooltip(
3911 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3912 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3913 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3914 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3915 window: &mut Window,
3916 cx: &mut App,
3917) -> bool {
3918 let new_tooltip = build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3919 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3920 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3921 ActiveTooltip::Visible {
3922 tooltip: AnyTooltip {
3923 view,
3924 mouse_position: window.mouse_position(),
3925 check_visible_and_update: Rc::new(move |tooltip_bounds, window, cx| {
3926 if long_press_tooltip_active
3927 .as_ref()
3928 .is_some_and(|active| active.get())
3929 {
3930 return true;
3931 }
3932 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3933 return false;
3934 };
3935 handle_tooltip_check_visible_and_update(
3936 &active_tooltip,
3937 tooltip_is_hoverable,
3938 &check_is_hovered_during_prepaint,
3939 tooltip_bounds,
3940 window,
3941 cx,
3942 )
3943 }),
3944 },
3945 is_hoverable: tooltip_is_hoverable,
3946 }
3947 });
3948 let did_show = new_tooltip.is_some();
3949 *active_tooltip.borrow_mut() = new_tooltip;
3950 window.refresh();
3951 did_show
3952}
3953
3954fn handle_tooltip_check_visible_and_update(
3958 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3959 tooltip_is_hoverable: bool,
3960 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3961 tooltip_bounds: Bounds<Pixels>,
3962 window: &mut Window,
3963 cx: &mut App,
3964) -> bool {
3965 enum Action {
3968 None,
3969 Hide,
3970 ScheduleHide(AnyTooltip),
3971 CancelHide(AnyTooltip),
3972 }
3973
3974 let is_hovered = check_is_hovered(window)
3975 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
3976 let action = match active_tooltip.borrow().as_ref() {
3977 Some(ActiveTooltip::Visible { tooltip, .. }) => {
3978 if is_hovered {
3979 Action::None
3980 } else {
3981 if tooltip_is_hoverable {
3982 Action::ScheduleHide(tooltip.clone())
3983 } else {
3984 Action::Hide
3985 }
3986 }
3987 }
3988 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
3989 if is_hovered {
3990 Action::CancelHide(tooltip.clone())
3991 } else {
3992 Action::None
3993 }
3994 }
3995 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
3996 };
3997
3998 match action {
3999 Action::None => {}
4000 Action::Hide => clear_active_tooltip(active_tooltip, window),
4001 Action::ScheduleHide(tooltip) => {
4002 let delayed_hide_task = window.spawn(cx, {
4003 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4004 async move |cx| {
4005 cx.background_executor()
4006 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
4007 .await;
4008 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4009 return;
4010 };
4011 if active_tooltip.borrow_mut().take().is_some() {
4012 cx.update(|window, _cx| window.refresh()).ok();
4013 }
4014 }
4015 });
4016 active_tooltip
4017 .borrow_mut()
4018 .replace(ActiveTooltip::WaitingForHide {
4019 tooltip,
4020 _task: delayed_hide_task,
4021 });
4022 }
4023 Action::CancelHide(tooltip) => {
4024 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
4026 tooltip,
4027 is_hoverable: true,
4028 });
4029 }
4030 }
4031
4032 active_tooltip.borrow().is_some()
4033}
4034
4035#[derive(Default)]
4036pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
4037
4038impl Global for GroupHitboxes {}
4039
4040impl GroupHitboxes {
4041 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
4042 cx.default_global::<Self>()
4043 .0
4044 .get(name)
4045 .and_then(|bounds_stack| bounds_stack.last())
4046 .cloned()
4047 }
4048
4049 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
4050 cx.default_global::<Self>()
4051 .0
4052 .entry(name)
4053 .or_default()
4054 .push(hitbox_id);
4055 }
4056
4057 pub fn pop(name: &SharedString, cx: &mut App) {
4058 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
4059 }
4060}
4061
4062pub struct Stateful<E> {
4064 pub(crate) element: E,
4065}
4066
4067impl<E> Styled for Stateful<E>
4068where
4069 E: Styled,
4070{
4071 fn style(&mut self) -> &mut StyleRefinement {
4072 self.element.style()
4073 }
4074}
4075
4076impl<E> StatefulInteractiveElement for Stateful<E>
4077where
4078 E: Element,
4079 Self: InteractiveElement,
4080{
4081}
4082
4083impl<E> InteractiveElement for Stateful<E>
4084where
4085 E: InteractiveElement,
4086{
4087 fn interactivity(&mut self) -> &mut Interactivity {
4088 self.element.interactivity()
4089 }
4090}
4091
4092impl<E> Element for Stateful<E>
4093where
4094 E: Element,
4095{
4096 type RequestLayoutState = E::RequestLayoutState;
4097 type PrepaintState = E::PrepaintState;
4098
4099 fn id(&self) -> Option<ElementId> {
4100 self.element.id()
4101 }
4102
4103 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4104 self.element.source_location()
4105 }
4106
4107 fn a11y_role(&self) -> Option<accesskit::Role> {
4108 self.element.a11y_role()
4109 }
4110
4111 fn write_a11y_info(&self, node: &mut accesskit::Node) {
4112 self.element.write_a11y_info(node);
4113 }
4114
4115 fn a11y_synthetic_children(
4116 &mut self,
4117 prepaint: &mut Self::PrepaintState,
4118 builder: &mut crate::A11ySubtreeBuilder,
4119 ) {
4120 self.element.a11y_synthetic_children(prepaint, builder);
4121 }
4122
4123 fn request_layout(
4124 &mut self,
4125 id: Option<&GlobalElementId>,
4126 window: &mut Window,
4127 cx: &mut App,
4128 ) -> (LayoutId, Self::RequestLayoutState) {
4129 self.element.request_layout(id, window, cx)
4130 }
4131
4132 fn prepaint(
4133 &mut self,
4134 id: Option<&GlobalElementId>,
4135 bounds: Bounds<Pixels>,
4136 state: &mut Self::RequestLayoutState,
4137 window: &mut Window,
4138 cx: &mut App,
4139 ) -> E::PrepaintState {
4140 self.element.prepaint(id, bounds, state, window, cx)
4141 }
4142
4143 fn paint(
4144 &mut self,
4145 id: Option<&GlobalElementId>,
4146 bounds: Bounds<Pixels>,
4147 request_layout: &mut Self::RequestLayoutState,
4148 prepaint: &mut Self::PrepaintState,
4149 window: &mut Window,
4150 cx: &mut App,
4151 ) {
4152 self.element
4153 .paint(id, bounds, request_layout, prepaint, window, cx);
4154 }
4155}
4156
4157impl<E> IntoElement for Stateful<E>
4158where
4159 E: Element,
4160{
4161 type Element = Self;
4162
4163 fn into_element(self) -> Self::Element {
4164 self
4165 }
4166}
4167
4168impl<E> ParentElement for Stateful<E>
4169where
4170 E: ParentElement,
4171{
4172 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4173 self.element.extend(elements)
4174 }
4175}
4176
4177#[derive(Clone)]
4180pub struct ScrollAnchor {
4181 handle: ScrollHandle,
4182 last_origin: Rc<RefCell<Point<Pixels>>>,
4183}
4184
4185impl ScrollAnchor {
4186 pub fn for_handle(handle: ScrollHandle) -> Self {
4188 Self {
4189 handle,
4190 last_origin: Default::default(),
4191 }
4192 }
4193 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4195 let this = self.clone();
4196
4197 window.on_next_frame(move |_, _| {
4198 let viewport_bounds = this.handle.bounds();
4199 let self_bounds = *this.last_origin.borrow();
4200 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4201 });
4202 }
4203}
4204
4205#[derive(Default, Debug)]
4206struct ScrollHandleState {
4207 offset: Rc<RefCell<Point<Pixels>>>,
4208 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4209 bounds: Bounds<Pixels>,
4210 max_offset: Point<Pixels>,
4211 child_bounds: Vec<Bounds<Pixels>>,
4212 scroll_to_bottom: bool,
4213 overflow: Point<Overflow>,
4214 active_item: Option<ScrollActiveItem>,
4215}
4216
4217#[derive(Default, Debug, Clone, Copy)]
4218struct ScrollActiveItem {
4219 index: usize,
4220 strategy: ScrollStrategy,
4221}
4222
4223#[derive(Default, Debug, Clone, Copy)]
4224enum ScrollStrategy {
4225 #[default]
4226 FirstVisible,
4227 Top,
4228}
4229
4230#[derive(Clone, Debug)]
4234pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4235
4236impl Default for ScrollHandle {
4237 fn default() -> Self {
4238 Self::new()
4239 }
4240}
4241
4242impl ScrollHandle {
4243 pub fn new() -> Self {
4245 Self(Rc::default())
4246 }
4247
4248 pub fn offset(&self) -> Point<Pixels> {
4250 *self.0.borrow().offset.borrow()
4251 }
4252
4253 pub fn max_offset(&self) -> Point<Pixels> {
4255 self.0.borrow().max_offset
4256 }
4257
4258 pub fn top_item(&self) -> usize {
4260 let state = self.0.borrow();
4261 let top = state.bounds.top() - state.offset.borrow().y;
4262
4263 match state.child_bounds.binary_search_by(|bounds| {
4264 if top < bounds.top() {
4265 Ordering::Greater
4266 } else if top > bounds.bottom() {
4267 Ordering::Less
4268 } else {
4269 Ordering::Equal
4270 }
4271 }) {
4272 Ok(ix) => ix,
4273 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4274 }
4275 }
4276
4277 pub fn bottom_item(&self) -> usize {
4279 let state = self.0.borrow();
4280 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4281
4282 match state.child_bounds.binary_search_by(|bounds| {
4283 if bottom < bounds.top() {
4284 Ordering::Greater
4285 } else if bottom > bounds.bottom() {
4286 Ordering::Less
4287 } else {
4288 Ordering::Equal
4289 }
4290 }) {
4291 Ok(ix) => ix,
4292 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4293 }
4294 }
4295
4296 pub fn bounds(&self) -> Bounds<Pixels> {
4298 self.0.borrow().bounds
4299 }
4300
4301 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4303 self.0.borrow().child_bounds.get(ix).cloned()
4304 }
4305
4306 pub fn scroll_to_item(&self, ix: usize) {
4308 let mut state = self.0.borrow_mut();
4309 state.active_item = Some(ScrollActiveItem {
4310 index: ix,
4311 strategy: ScrollStrategy::default(),
4312 });
4313 }
4314
4315 pub fn scroll_to_top_of_item(&self, ix: usize) {
4318 let mut state = self.0.borrow_mut();
4319 state.active_item = Some(ScrollActiveItem {
4320 index: ix,
4321 strategy: ScrollStrategy::Top,
4322 });
4323 }
4324
4325 fn scroll_to_active_item(&self) {
4329 let mut state = self.0.borrow_mut();
4330
4331 let Some(active_item) = state.active_item else {
4332 return;
4333 };
4334
4335 let active_item = match state.child_bounds.get(active_item.index) {
4336 Some(bounds) => {
4337 let mut scroll_offset = state.offset.borrow_mut();
4338
4339 match active_item.strategy {
4340 ScrollStrategy::FirstVisible => {
4341 if state.overflow.y == Overflow::Scroll {
4342 let child_height = bounds.size.height;
4343 let viewport_height = state.bounds.size.height;
4344 if child_height > viewport_height {
4345 scroll_offset.y = state.bounds.top() - bounds.top();
4346 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4347 scroll_offset.y = state.bounds.top() - bounds.top();
4348 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4349 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4350 }
4351 }
4352 }
4353 ScrollStrategy::Top => {
4354 scroll_offset.y = state.bounds.top() - bounds.top();
4355 }
4356 }
4357
4358 if state.overflow.x == Overflow::Scroll {
4359 let child_width = bounds.size.width;
4360 let viewport_width = state.bounds.size.width;
4361 if child_width > viewport_width {
4362 scroll_offset.x = state.bounds.left() - bounds.left();
4363 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4364 scroll_offset.x = state.bounds.left() - bounds.left();
4365 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4366 scroll_offset.x = state.bounds.right() - bounds.right();
4367 }
4368 }
4369 None
4370 }
4371 None => Some(active_item),
4372 };
4373 state.active_item = active_item;
4374 }
4375
4376 pub fn scroll_to_bottom(&self) {
4378 let mut state = self.0.borrow_mut();
4379 state.scroll_to_bottom = true;
4380 }
4381
4382 pub fn set_offset(&self, mut position: Point<Pixels>) {
4386 let state = self.0.borrow();
4387 *state.offset.borrow_mut() = position;
4388 }
4389
4390 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4392 let ix = self.top_item();
4393 let state = self.0.borrow();
4394
4395 if let Some(child_bounds) = state.child_bounds.get(ix) {
4396 (
4397 ix,
4398 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4399 )
4400 } else {
4401 (ix, px(0.))
4402 }
4403 }
4404
4405 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4407 let ix = self.bottom_item();
4408 let state = self.0.borrow();
4409
4410 if let Some(child_bounds) = state.child_bounds.get(ix) {
4411 (
4412 ix,
4413 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4414 )
4415 } else {
4416 (ix, px(0.))
4417 }
4418 }
4419
4420 pub fn children_count(&self) -> usize {
4422 self.0.borrow().child_bounds.len()
4423 }
4424}
4425
4426#[cfg(test)]
4427mod tests {
4428 use super::*;
4429 use crate::{
4430 AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, Keystroke,
4431 MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas, util::FluentBuilder as _,
4432 };
4433 use std::{cell::Cell, rc::Weak};
4434
4435 struct GroupHoverTestView {
4436 render_count: Rc<Cell<usize>>,
4437 anonymous_paint_count: Rc<Cell<usize>>,
4438 stateful_width: Rc<Cell<Pixels>>,
4439 }
4440
4441 impl Render for GroupHoverTestView {
4442 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4443 self.render_count.set(self.render_count.get() + 1);
4444 let anonymous_paint_count = self.anonymous_paint_count.clone();
4445 let stateful_width = self.stateful_width.clone();
4446 div().size_full().child(
4447 div()
4448 .ml(px(20.))
4449 .mt(px(20.))
4450 .size(px(50.))
4451 .relative()
4452 .group("hover-group")
4453 .child(
4454 div()
4455 .absolute()
4456 .size_full()
4457 .invisible()
4458 .group_hover("hover-group", |style| style.visible())
4459 .child(canvas(
4460 |_, _, _| {},
4461 move |_, _, _, _| {
4462 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4463 },
4464 )),
4465 )
4466 .child(
4467 div()
4468 .id("stateful-group-hover-target")
4469 .absolute()
4470 .top_0()
4471 .left_0()
4472 .size(px(10.))
4473 .group_hover("hover-group", |style| style.size(px(20.)))
4474 .child(canvas(
4475 move |bounds, _, _| stateful_width.set(bounds.size.width),
4476 |_, _, _, _| {},
4477 )),
4478 ),
4479 )
4480 }
4481 }
4482
4483 #[gpui::test]
4484 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4485 let render_count = Rc::new(Cell::new(0));
4486 let anonymous_paint_count = Rc::new(Cell::new(0));
4487 let stateful_width = Rc::new(Cell::new(px(0.)));
4488 let window = cx.add_window({
4489 let render_count = render_count.clone();
4490 let anonymous_paint_count = anonymous_paint_count.clone();
4491 let stateful_width = stateful_width.clone();
4492 move |_, _| GroupHoverTestView {
4493 render_count,
4494 anonymous_paint_count,
4495 stateful_width,
4496 }
4497 });
4498 let window = AnyWindowHandle::from(window);
4499
4500 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4501 .unwrap();
4502 assert_eq!(anonymous_paint_count.get(), 0);
4503 assert_eq!(stateful_width.get(), px(10.));
4504
4505 let move_mouse = |cx: &mut TestAppContext, position| {
4506 cx.update_window(window, |_, window, cx| {
4507 window.simulate_mouse_move(position, cx)
4508 })
4509 .unwrap();
4510 };
4511
4512 let initial_render_count = render_count.get();
4513 move_mouse(cx, point(px(25.), px(25.)));
4514 assert_eq!(render_count.get(), initial_render_count + 1);
4515 assert_eq!(anonymous_paint_count.get(), 1);
4516 assert_eq!(stateful_width.get(), px(20.));
4517
4518 move_mouse(cx, point(px(30.), px(30.)));
4519 assert_eq!(render_count.get(), initial_render_count + 1);
4520 assert_eq!(anonymous_paint_count.get(), 1);
4521 assert_eq!(stateful_width.get(), px(20.));
4522
4523 move_mouse(cx, point(px(5.), px(5.)));
4524 assert_eq!(render_count.get(), initial_render_count + 2);
4525 assert_eq!(anonymous_paint_count.get(), 1);
4526 assert_eq!(stateful_width.get(), px(10.));
4527
4528 move_mouse(cx, point(px(10.), px(10.)));
4529 assert_eq!(render_count.get(), initial_render_count + 2);
4530 assert_eq!(anonymous_paint_count.get(), 1);
4531 assert_eq!(stateful_width.get(), px(10.));
4532 }
4533
4534 struct HoverListenerLayoutTestView {
4535 target_left: Pixels,
4536 hover_transitions: Rc<RefCell<Vec<bool>>>,
4537 }
4538
4539 impl Render for HoverListenerLayoutTestView {
4540 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4541 let hover_transitions = self.hover_transitions.clone();
4542 div().relative().size_full().child(
4543 div()
4544 .id("hover-target")
4545 .absolute()
4546 .left(self.target_left)
4547 .top_0()
4548 .size(px(20.))
4549 .on_click(|_, _, _| {})
4550 .on_hover(move |is_hovered, _, _| {
4551 hover_transitions.borrow_mut().push(*is_hovered);
4552 }),
4553 )
4554 }
4555 }
4556
4557 #[gpui::test]
4558 fn default_hover_listener_updates_when_layout_changes_under_stationary_mouse(
4559 cx: &mut TestAppContext,
4560 ) {
4561 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4562 let window = cx.add_window({
4563 let hover_transitions = hover_transitions.clone();
4564 move |_, _| HoverListenerLayoutTestView {
4565 target_left: px(40.),
4566 hover_transitions,
4567 }
4568 });
4569 let any_window = AnyWindowHandle::from(window);
4570
4571 cx.update_window(any_window, |_, window, cx| {
4572 window.draw(cx).clear(cx);
4573 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4574 })
4575 .unwrap();
4576 assert!(hover_transitions.borrow().is_empty());
4577
4578 window
4579 .update(cx, |view, _, cx| {
4580 view.target_left = px(0.);
4581 cx.notify();
4582 })
4583 .unwrap();
4584 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4585 .unwrap();
4586 assert_eq!(*hover_transitions.borrow(), [true]);
4587
4588 window
4589 .update(cx, |view, _, cx| {
4590 view.target_left = px(40.);
4591 cx.notify();
4592 })
4593 .unwrap();
4594 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4595 .unwrap();
4596 assert_eq!(*hover_transitions.borrow(), [true, false]);
4597 }
4598
4599 #[gpui::test]
4600 fn default_hover_listener_ends_after_key_press(cx: &mut TestAppContext) {
4601 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4602 let window = cx.add_window({
4603 let hover_transitions = hover_transitions.clone();
4604 move |_, _| HoverListenerLayoutTestView {
4605 target_left: px(0.),
4606 hover_transitions,
4607 }
4608 });
4609 let any_window = AnyWindowHandle::from(window);
4610
4611 cx.update_window(any_window, |_, window, cx| {
4612 window.draw(cx).clear(cx);
4613 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4614 })
4615 .unwrap();
4616 assert_eq!(*hover_transitions.borrow(), [true]);
4617
4618 key_down(cx, any_window, "a");
4619 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4620 .unwrap();
4621 assert_eq!(*hover_transitions.borrow(), [true, false]);
4622 }
4623
4624 struct HoverListenerModeLayoutTestView {
4625 target_left: Pixels,
4626 hover_transitions: Rc<RefCell<Vec<bool>>>,
4627 }
4628
4629 impl Render for HoverListenerModeLayoutTestView {
4630 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4631 let hover_transitions = self.hover_transitions.clone();
4632 div().relative().size_full().child(
4633 div()
4634 .id("hover-target")
4635 .absolute()
4636 .left(self.target_left)
4637 .top_0()
4638 .size(px(20.))
4639 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
4640 .on_hover(move |is_hovered, _, _| {
4641 hover_transitions.borrow_mut().push(*is_hovered);
4642 }),
4643 )
4644 }
4645 }
4646
4647 #[gpui::test]
4648 fn input_modality_independent_hover_listener_updates_after_key_press(cx: &mut TestAppContext) {
4649 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4650 let window = cx.add_window({
4651 let hover_transitions = hover_transitions.clone();
4652 move |_, _| HoverListenerModeLayoutTestView {
4653 target_left: px(40.),
4654 hover_transitions,
4655 }
4656 });
4657 let any_window = AnyWindowHandle::from(window);
4658 let pointer_position = point(px(10.), px(10.));
4659
4660 cx.update_window(any_window, |_, window, cx| {
4661 window.draw(cx).clear(cx);
4662 window.simulate_mouse_move(pointer_position, cx);
4663 })
4664 .unwrap();
4665 assert!(hover_transitions.borrow().is_empty());
4666
4667 key_down(cx, any_window, "a");
4668 window
4669 .update(cx, |view, _, cx| {
4670 view.target_left = px(0.);
4671 cx.notify();
4672 })
4673 .unwrap();
4674 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4675 .unwrap();
4676 assert_eq!(*hover_transitions.borrow(), [true]);
4677
4678 key_down(cx, any_window, "b");
4679 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4680 .unwrap();
4681 assert_eq!(*hover_transitions.borrow(), [true]);
4682
4683 cx.update_window(any_window, |_, window, cx| {
4684 window.simulate_mouse_move(point(px(30.), px(10.)), cx);
4685 })
4686 .unwrap();
4687 assert_eq!(*hover_transitions.borrow(), [true, false]);
4688
4689 cx.update_window(any_window, |_, window, cx| {
4690 window.simulate_mouse_move(pointer_position, cx);
4691 window.dispatch_event(
4692 MouseExitEvent {
4693 position: pointer_position,
4694 ..Default::default()
4695 }
4696 .to_platform_input(),
4697 cx,
4698 );
4699 })
4700 .unwrap();
4701 assert_eq!(*hover_transitions.borrow(), [true, false, true, false]);
4702 }
4703
4704 #[gpui::test]
4705 fn default_hover_listener_remains_hovered_during_stationary_mouse_press(
4706 cx: &mut TestAppContext,
4707 ) {
4708 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4709 let window = cx.add_window({
4710 let hover_transitions = hover_transitions.clone();
4711 move |_, _| HoverListenerLayoutTestView {
4712 target_left: px(0.),
4713 hover_transitions,
4714 }
4715 });
4716 let any_window = AnyWindowHandle::from(window);
4717 let mouse_position = point(px(10.), px(10.));
4718
4719 cx.update_window(any_window, |_, window, cx| {
4720 window.draw(cx).clear(cx);
4721 window.simulate_mouse_move(mouse_position, cx);
4722 })
4723 .unwrap();
4724 assert_eq!(*hover_transitions.borrow(), [true]);
4725
4726 cx.update_window(any_window, |_, window, cx| {
4727 window.dispatch_event(
4728 MouseDownEvent {
4729 position: mouse_position,
4730 button: MouseButton::Left,
4731 modifiers: Default::default(),
4732 click_count: 1,
4733 first_mouse: false,
4734 }
4735 .to_platform_input(),
4736 cx,
4737 );
4738 window.draw(cx).clear(cx);
4739 })
4740 .unwrap();
4741 assert_eq!(*hover_transitions.borrow(), [true]);
4742
4743 cx.update_window(any_window, |_, window, cx| {
4744 window.dispatch_event(
4745 MouseUpEvent {
4746 position: mouse_position,
4747 button: MouseButton::Left,
4748 modifiers: Default::default(),
4749 click_count: 1,
4750 }
4751 .to_platform_input(),
4752 cx,
4753 );
4754 window.draw(cx).clear(cx);
4755 })
4756 .unwrap();
4757 assert_eq!(*hover_transitions.borrow(), [true]);
4758 }
4759
4760 struct TestTooltipView;
4761
4762 impl Render for TestTooltipView {
4763 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4764 div().w(px(20.)).h(px(20.)).child("tooltip")
4765 }
4766 }
4767
4768 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4769
4770 struct TooltipCaptureElement {
4771 child: AnyElement,
4772 captured_active_tooltip: CapturedActiveTooltip,
4773 }
4774
4775 impl IntoElement for TooltipCaptureElement {
4776 type Element = Self;
4777
4778 fn into_element(self) -> Self::Element {
4779 self
4780 }
4781 }
4782
4783 impl Element for TooltipCaptureElement {
4784 type RequestLayoutState = ();
4785 type PrepaintState = ();
4786
4787 fn id(&self) -> Option<ElementId> {
4788 None
4789 }
4790
4791 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4792 None
4793 }
4794
4795 fn request_layout(
4796 &mut self,
4797 _id: Option<&GlobalElementId>,
4798 window: &mut Window,
4799 cx: &mut App,
4800 ) -> (LayoutId, Self::RequestLayoutState) {
4801 (self.child.request_layout(window, cx), ())
4802 }
4803
4804 fn prepaint(
4805 &mut self,
4806 _id: Option<&GlobalElementId>,
4807 _bounds: Bounds<Pixels>,
4808 _request_layout: &mut Self::RequestLayoutState,
4809 window: &mut Window,
4810 cx: &mut App,
4811 ) -> Self::PrepaintState {
4812 self.child.prepaint(window, cx);
4813 }
4814
4815 fn paint(
4816 &mut self,
4817 _id: Option<&GlobalElementId>,
4818 _bounds: Bounds<Pixels>,
4819 _request_layout: &mut Self::RequestLayoutState,
4820 _prepaint: &mut Self::PrepaintState,
4821 window: &mut Window,
4822 cx: &mut App,
4823 ) {
4824 self.child.paint(window, cx);
4825 window.with_global_id("target".into(), |global_id, window| {
4826 window.with_element_state::<InteractiveElementState, _>(
4827 global_id,
4828 |state, _window| {
4829 let state = state.unwrap();
4830 *self.captured_active_tooltip.borrow_mut() =
4831 state.active_tooltip.as_ref().map(Rc::downgrade);
4832 ((), state)
4833 },
4834 )
4835 });
4836 }
4837 }
4838
4839 struct TooltipOwner {
4840 captured_active_tooltip: CapturedActiveTooltip,
4841 show_delay_override: Option<Duration>,
4842 }
4843
4844 impl Render for TooltipOwner {
4845 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4846 TooltipCaptureElement {
4847 child: div()
4848 .size_full()
4849 .child(
4850 div()
4851 .id("target")
4852 .w(px(50.))
4853 .h(px(50.))
4854 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4855 .when_some(self.show_delay_override, |this, delay| {
4856 this.tooltip_show_delay(delay)
4857 }),
4858 )
4859 .into_any_element(),
4860 captured_active_tooltip: self.captured_active_tooltip.clone(),
4861 }
4862 }
4863 }
4864
4865 #[test]
4866 fn scroll_handle_aligns_wide_children_to_left_edge() {
4867 let handle = ScrollHandle::new();
4868 {
4869 let mut state = handle.0.borrow_mut();
4870 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4871 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4872 state.overflow.x = Overflow::Scroll;
4873 state.active_item = Some(ScrollActiveItem {
4874 index: 0,
4875 strategy: ScrollStrategy::default(),
4876 });
4877 }
4878
4879 handle.scroll_to_active_item();
4880
4881 assert_eq!(handle.offset().x, px(-25.));
4882 }
4883
4884 #[test]
4885 fn scroll_handle_aligns_tall_children_to_top_edge() {
4886 let handle = ScrollHandle::new();
4887 {
4888 let mut state = handle.0.borrow_mut();
4889 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4890 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4891 state.overflow.y = Overflow::Scroll;
4892 state.active_item = Some(ScrollActiveItem {
4893 index: 0,
4894 strategy: ScrollStrategy::default(),
4895 });
4896 }
4897
4898 handle.scroll_to_active_item();
4899
4900 assert_eq!(handle.offset().y, px(-25.));
4901 }
4902
4903 #[test]
4904 fn long_press_shows_tooltip_until_touch_ends() {
4905 let (mut test_app, any_window, captured_active_tooltip) = create_tooltip_owner_test(None);
4906 let active_tooltip = captured_active_tooltip
4907 .borrow()
4908 .clone()
4909 .unwrap()
4910 .upgrade()
4911 .unwrap();
4912 let touch_id = TouchId(1);
4913 let touch_position = point(px(49.), px(10.));
4914
4915 test_app
4916 .update_window(any_window, |_, window, cx| {
4917 window.dispatch_event(
4918 TouchEvent {
4919 id: touch_id,
4920 phase: TouchPhase::Started,
4921 position: touch_position,
4922 predicted_position: None,
4923 force: None,
4924 }
4925 .to_platform_input(),
4926 cx,
4927 );
4928 })
4929 .unwrap();
4930 test_app
4931 .dispatcher
4932 .advance_clock(GestureTuning::default().long_press_duration + Duration::from_millis(1));
4933 test_app.run_until_parked();
4934
4935 assert!(matches!(
4936 active_tooltip.borrow().as_ref(),
4937 Some(ActiveTooltip::Visible { .. })
4938 ));
4939
4940 let moved_position = point(px(55.), px(10.));
4941 test_app
4942 .update_window(any_window, |_, window, cx| {
4943 window.dispatch_event(
4944 TouchEvent {
4945 id: touch_id,
4946 phase: TouchPhase::Moved,
4947 position: moved_position,
4948 predicted_position: None,
4949 force: None,
4950 }
4951 .to_platform_input(),
4952 cx,
4953 );
4954 window.draw(cx).clear(cx);
4955 })
4956 .unwrap();
4957 assert!(matches!(
4958 active_tooltip.borrow().as_ref(),
4959 Some(ActiveTooltip::Visible { .. })
4960 ));
4961
4962 test_app
4963 .update_window(any_window, |_, window, cx| {
4964 window.dispatch_event(
4965 TouchEvent {
4966 id: touch_id,
4967 phase: TouchPhase::Ended,
4968 position: moved_position,
4969 predicted_position: None,
4970 force: None,
4971 }
4972 .to_platform_input(),
4973 cx,
4974 );
4975 })
4976 .unwrap();
4977
4978 assert!(active_tooltip.borrow().is_none());
4979 }
4980
4981 fn setup_tooltip_owner_test(
4982 show_delay_override: Option<Duration>,
4983 ) -> (
4984 TestAppContext,
4985 crate::AnyWindowHandle,
4986 CapturedActiveTooltip,
4987 ) {
4988 let (mut test_app, any_window, captured_active_tooltip) =
4989 create_tooltip_owner_test(show_delay_override);
4990
4991 test_app
4992 .update_window(any_window, |_, window, cx| {
4993 window.dispatch_event(
4994 MouseMoveEvent {
4995 position: point(px(10.), px(10.)),
4996 modifiers: Default::default(),
4997 pressed_button: None,
4998 }
4999 .to_platform_input(),
5000 cx,
5001 );
5002 })
5003 .unwrap();
5004
5005 test_app
5006 .update_window(any_window, |_, window, cx| {
5007 window.draw(cx).clear(cx);
5008 })
5009 .unwrap();
5010
5011 (test_app, any_window, captured_active_tooltip)
5012 }
5013
5014 fn create_tooltip_owner_test(
5015 show_delay_override: Option<Duration>,
5016 ) -> (
5017 TestAppContext,
5018 crate::AnyWindowHandle,
5019 CapturedActiveTooltip,
5020 ) {
5021 let mut test_app = TestAppContext::single();
5022 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
5023 let window = test_app.add_window({
5024 let captured_active_tooltip = captured_active_tooltip.clone();
5025 move |_, _| TooltipOwner {
5026 captured_active_tooltip,
5027 show_delay_override,
5028 }
5029 });
5030 let any_window = window.into();
5031
5032 test_app
5033 .update_window(any_window, |_, window, cx| {
5034 window.draw(cx).clear(cx);
5035 })
5036 .unwrap();
5037
5038 (test_app, any_window, captured_active_tooltip)
5039 }
5040
5041 #[test]
5042 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
5043 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5044
5045 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5046 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5047 assert!(matches!(
5048 active_tooltip.borrow().as_ref(),
5049 Some(ActiveTooltip::WaitingForShow { .. })
5050 ));
5051
5052 test_app
5053 .update_window(any_window, |_, window, _| {
5054 window.remove_window();
5055 })
5056 .unwrap();
5057 test_app.run_until_parked();
5058 drop(active_tooltip);
5059
5060 assert!(weak_active_tooltip.upgrade().is_none());
5061 }
5062
5063 #[test]
5064 fn tooltip_respects_custom_show_delay() {
5065 let extra_delay = Duration::from_secs(1);
5066 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
5067 let (mut test_app, _any_window, captured_active_tooltip) =
5068 setup_tooltip_owner_test(Some(show_delay_override));
5069
5070 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5071 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5072
5073 test_app
5074 .dispatcher
5075 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5076 test_app.run_until_parked();
5077
5078 assert!(matches!(
5079 active_tooltip.borrow().as_ref(),
5080 Some(ActiveTooltip::WaitingForShow { .. })
5081 ));
5082
5083 test_app.dispatcher.advance_clock(extra_delay);
5084 test_app.run_until_parked();
5085
5086 assert!(matches!(
5087 active_tooltip.borrow().as_ref(),
5088 Some(ActiveTooltip::Visible { .. })
5089 ));
5090 }
5091
5092 #[test]
5093 fn tooltip_is_released_when_its_owner_disappears() {
5094 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5095
5096 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5097 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5098
5099 test_app
5100 .dispatcher
5101 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5102 test_app.run_until_parked();
5103
5104 assert!(matches!(
5105 active_tooltip.borrow().as_ref(),
5106 Some(ActiveTooltip::Visible { .. })
5107 ));
5108
5109 test_app
5110 .update_window(any_window, |_, window, _| {
5111 window.remove_window();
5112 })
5113 .unwrap();
5114 test_app.run_until_parked();
5115 drop(active_tooltip);
5116
5117 assert!(weak_active_tooltip.upgrade().is_none());
5118 }
5119
5120 #[test]
5121 fn tooltip_hides_after_mouse_leaves_origin() {
5122 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5123
5124 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5125 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5126
5127 test_app
5128 .dispatcher
5129 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5130 test_app.run_until_parked();
5131
5132 assert!(matches!(
5133 active_tooltip.borrow().as_ref(),
5134 Some(ActiveTooltip::Visible { .. })
5135 ));
5136
5137 test_app
5138 .update_window(any_window, |_, window, cx| {
5139 window.dispatch_event(
5140 MouseMoveEvent {
5141 position: point(px(75.), px(75.)),
5142 modifiers: Default::default(),
5143 pressed_button: None,
5144 }
5145 .to_platform_input(),
5146 cx,
5147 );
5148 })
5149 .unwrap();
5150
5151 assert!(active_tooltip.borrow().is_none());
5152 }
5153
5154 struct MouseDownOutOwner {
5155 mouse_down_out_count: Rc<RefCell<usize>>,
5156 }
5157
5158 impl Render for MouseDownOutOwner {
5159 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5160 let mouse_down_out_count = self.mouse_down_out_count.clone();
5161 div()
5162 .size_full()
5163 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
5164 move |_, _, _| {
5165 *mouse_down_out_count.borrow_mut() += 1;
5166 },
5167 ))
5168 }
5169 }
5170
5171 #[test]
5172 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
5173 let mut test_app = TestAppContext::single();
5174 let mouse_down_out_count = Rc::new(RefCell::new(0));
5175 let window = test_app.add_window({
5176 let mouse_down_out_count = mouse_down_out_count.clone();
5177 move |_, _| MouseDownOutOwner {
5178 mouse_down_out_count,
5179 }
5180 });
5181 let any_window: AnyWindowHandle = window.into();
5182
5183 fn dispatch_mouse_down_outside_target(
5184 test_app: &mut TestAppContext,
5185 any_window: AnyWindowHandle,
5186 ) {
5187 test_app
5188 .update_window(any_window, |_, window, cx| {
5189 window.dispatch_event(
5190 MouseDownEvent {
5191 position: point(px(75.), px(75.)),
5192 button: MouseButton::Left,
5193 modifiers: Default::default(),
5194 click_count: 1,
5195 first_mouse: false,
5196 }
5197 .to_platform_input(),
5198 cx,
5199 );
5200 })
5201 .unwrap();
5202 }
5203
5204 test_app
5205 .update_window(any_window, |_, window, cx| {
5206 window.draw(cx).clear(cx);
5207 })
5208 .unwrap();
5209
5210 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5211 assert_eq!(
5212 *mouse_down_out_count.borrow(),
5213 1,
5214 "mouse down outside the element should fire mouse-down-out listeners"
5215 );
5216
5217 test_app
5218 .update_window(any_window, |_, window, cx| {
5219 cx.set_prompt_builder(crate::fallback_prompt_renderer);
5220 let _receiver =
5221 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
5222 assert!(window.has_active_prompt());
5223 window.draw(cx).clear(cx);
5224 })
5225 .unwrap();
5226
5227 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5228 assert_eq!(
5229 *mouse_down_out_count.borrow(),
5230 1,
5231 "mouse down over an active prompt should not fire mouse-down-out listeners"
5232 );
5233 }
5234
5235 #[test]
5236 fn test_accessibility_id_builder_writes_author_id() {
5237 let mut element = div()
5238 .id("buffer-font-size")
5239 .accessibility_id("settings.buffer-font-size");
5240 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5241
5242 element.interactivity().write_a11y_info(&mut node);
5243
5244 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5245 }
5246
5247 #[test]
5248 fn test_write_a11y_info_string_and_numeric_properties() {
5249 let mut interactivity = Interactivity::default();
5250 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
5251 interactivity.aria.label = Some("Buffer Font Size".into());
5252 interactivity.aria.value = Some("15".into());
5253 interactivity.aria.placeholder = Some("Search".into());
5254 interactivity.aria.numeric_value = Some(15.0);
5255 interactivity.aria.min_numeric_value = Some(6.0);
5256 interactivity.aria.max_numeric_value = Some(72.0);
5257 interactivity.aria.numeric_value_step = Some(1.0);
5258
5259 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5260 interactivity.write_a11y_info(&mut node);
5261
5262 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5263 assert_eq!(node.label(), Some("Buffer Font Size"));
5264 assert_eq!(node.value(), Some("15"));
5265 assert_eq!(node.placeholder(), Some("Search"));
5266 assert_eq!(node.numeric_value(), Some(15.0));
5267 assert_eq!(node.min_numeric_value(), Some(6.0));
5268 assert_eq!(node.max_numeric_value(), Some(72.0));
5269 assert_eq!(node.numeric_value_step(), Some(1.0));
5270 }
5271
5272 struct KeyboardActivationTest {
5275 focus_a: FocusHandle,
5276 focus_b: FocusHandle,
5277 clicks: Rc<RefCell<Vec<&'static str>>>,
5278 }
5279
5280 impl Render for KeyboardActivationTest {
5281 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5282 let clicks_a = self.clicks.clone();
5283 let clicks_b = self.clicks.clone();
5284 div()
5285 .size_full()
5286 .child(
5287 div()
5288 .id("a")
5289 .w(px(50.))
5290 .h(px(50.))
5291 .track_focus(&self.focus_a)
5292 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
5293 )
5294 .child(
5295 div()
5296 .id("b")
5297 .w(px(50.))
5298 .h(px(50.))
5299 .track_focus(&self.focus_b)
5300 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
5301 )
5302 }
5303 }
5304
5305 fn setup_keyboard_activation_test() -> (
5306 TestAppContext,
5307 AnyWindowHandle,
5308 Rc<RefCell<Vec<&'static str>>>,
5309 FocusHandle,
5310 FocusHandle,
5311 ) {
5312 let mut cx = TestAppContext::single();
5313 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
5314 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
5315 let window = cx.add_window({
5316 let focus_a = focus_a.clone();
5317 let focus_b = focus_b.clone();
5318 let clicks = clicks.clone();
5319 move |_, _| KeyboardActivationTest {
5320 focus_a,
5321 focus_b,
5322 clicks,
5323 }
5324 });
5325 (cx, window.into(), clicks, focus_a, focus_b)
5326 }
5327
5328 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
5331 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
5332 .unwrap();
5333 cx.run_until_parked();
5334 cx.update_window(window, |_, window, cx| {
5335 window.draw(cx).clear(cx);
5336 })
5337 .unwrap();
5338 }
5339
5340 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5341 let keystroke = Keystroke::parse(key).unwrap();
5342 cx.update_window(window, |_, window, cx| {
5343 window.dispatch_event(
5344 KeyDownEvent {
5345 keystroke,
5346 is_held: false,
5347 prefer_character_input: false,
5348 }
5349 .to_platform_input(),
5350 cx,
5351 );
5352 })
5353 .unwrap();
5354 }
5355
5356 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5357 let keystroke = Keystroke::parse(key).unwrap();
5358 cx.update_window(window, |_, window, cx| {
5359 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
5360 })
5361 .unwrap();
5362 }
5363
5364 #[test]
5366 fn keyboard_activation_fires_click_on_same_element() {
5367 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5368
5369 focus_and_draw(&mut cx, window, &focus_a);
5370 key_down(&mut cx, window, "enter");
5371 key_up(&mut cx, window, "enter");
5372
5373 assert_eq!(*clicks.borrow(), vec!["a"]);
5374 }
5375
5376 #[test]
5381 fn keyboard_activation_does_not_leak_across_focus_change() {
5382 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5383
5384 focus_and_draw(&mut cx, window, &focus_a);
5386 key_down(&mut cx, window, "enter");
5387
5388 focus_and_draw(&mut cx, window, &focus_b);
5390 key_up(&mut cx, window, "enter");
5391
5392 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5395 }
5396
5397 #[test]
5402 fn keyboard_activation_does_not_leak_when_focus_returns() {
5403 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5404
5405 focus_and_draw(&mut cx, window, &focus_a);
5407 key_down(&mut cx, window, "enter");
5408
5409 focus_and_draw(&mut cx, window, &focus_b);
5412 focus_and_draw(&mut cx, window, &focus_a);
5413 key_up(&mut cx, window, "enter");
5414
5415 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5417 }
5418
5419 #[test]
5424 fn keyboard_activation_cleared_by_intervening_key_release() {
5425 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5426
5427 focus_and_draw(&mut cx, window, &focus_a);
5428 key_down(&mut cx, window, "escape");
5429 key_down(&mut cx, window, "space");
5430 key_up(&mut cx, window, "escape");
5431 key_up(&mut cx, window, "space");
5432
5433 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5434 }
5435
5436 #[test]
5440 fn keyboard_activation_does_not_distinguish_space_and_enter() {
5441 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5442
5443 focus_and_draw(&mut cx, window, &focus_a);
5444 key_down(&mut cx, window, "space");
5445 key_up(&mut cx, window, "enter");
5446
5447 assert_eq!(*clicks.borrow(), vec!["a"]);
5448 }
5449
5450 #[test]
5453 fn keyboard_activation_cleared_by_intervening_keydown() {
5454 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5455
5456 focus_and_draw(&mut cx, window, &focus_a);
5457 key_down(&mut cx, window, "enter");
5458 key_down(&mut cx, window, "a");
5459 key_up(&mut cx, window, "enter");
5460
5461 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5462 }
5463
5464 #[test]
5467 fn keyboard_activation_ignores_modified_keys() {
5468 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5469
5470 focus_and_draw(&mut cx, window, &focus_a);
5471 key_down(&mut cx, window, "cmd-enter");
5472 key_up(&mut cx, window, "cmd-enter");
5473
5474 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5475 }
5476
5477 struct TabGroupFocus {
5481 group_a: FocusHandle,
5482 item_a: FocusHandle,
5483 group_b: FocusHandle,
5484 item_b: FocusHandle,
5485 }
5486
5487 impl Render for TabGroupFocus {
5488 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5489 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
5490 div()
5491 .track_focus(container)
5492 .tab_group()
5493 .child(div().track_focus(item))
5494 }
5495 div()
5496 .child(group(&self.group_a, &self.item_a))
5497 .child(group(&self.group_b, &self.item_b))
5498 }
5499 }
5500
5501 #[test]
5505 fn focus_next_from_tab_group_container_enters_that_group() {
5506 let mut cx = TestAppContext::single();
5507 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
5508 (
5509 cx.focus_handle(),
5510 cx.focus_handle().tab_stop(true),
5511 cx.focus_handle(),
5512 cx.focus_handle().tab_stop(true),
5513 )
5514 });
5515 let window: AnyWindowHandle = cx
5516 .add_window({
5517 let (group_a, item_a, group_b, item_b) =
5518 (group_a, item_a, group_b.clone(), item_b.clone());
5519 move |_, _| TabGroupFocus {
5520 group_a,
5521 item_a,
5522 group_b,
5523 item_b,
5524 }
5525 })
5526 .into();
5527 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5528 .unwrap();
5529
5530 let focused = cx
5532 .update_window(window, |_, window, cx| {
5533 window.focus(&group_b, cx);
5534 window.focus_next(cx);
5535 window.focused(cx).map(|handle| handle.id)
5536 })
5537 .unwrap();
5538
5539 assert_eq!(focused, Some(item_b.id));
5540 }
5541
5542 #[gpui::test]
5543 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5544 cx: &mut TestAppContext,
5545 ) {
5546 struct PaddedContainer {
5547 scroll_handle: ScrollHandle,
5548 }
5549
5550 impl Render for PaddedContainer {
5551 fn render(
5552 &mut self,
5553 _window: &mut Window,
5554 _cx: &mut Context<Self>,
5555 ) -> impl IntoElement {
5556 div().size_full().child(
5559 div()
5560 .id("container")
5561 .h(px(50.))
5562 .w(px(100.))
5563 .py(px(4.25))
5564 .overflow_y_scroll()
5565 .track_scroll(&self.scroll_handle)
5566 .child(div().w_full().h(px(42.))),
5567 )
5568 }
5569 }
5570
5571 let scroll_handle = ScrollHandle::new();
5572 let window: AnyWindowHandle = cx
5573 .add_window({
5574 let scroll_handle = scroll_handle.clone();
5575 move |_, _| PaddedContainer { scroll_handle }
5576 })
5577 .into();
5578 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5579 .unwrap();
5580
5581 assert_eq!(scroll_handle.max_offset().y, px(0.));
5582 }
5583
5584 struct ContentSizedGrid;
5585
5586 impl Render for ContentSizedGrid {
5587 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5588 let widths = [px(100.), px(200.), px(50.)];
5589 div().size_full().child(
5590 div()
5591 .w_full()
5592 .grid()
5593 .grid_cols_max_content(widths.len() as u16)
5594 .children(widths.into_iter().enumerate().map(|(index, width)| {
5595 div()
5596 .debug_selector(move || format!("cell-{index}"))
5597 .w(width)
5598 .h(px(10.))
5599 })),
5600 )
5601 }
5602 }
5603
5604 #[gpui::test]
5605 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
5606 let window = cx.add_window(|_, _| ContentSizedGrid);
5607 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
5608 .unwrap();
5609
5610 let mut bounds = |selector: &'static str| {
5611 cx.update_window(window.into(), |_, window, _| {
5612 window
5613 .frame_state
5614 .rendered_frame
5615 .debug_bounds
5616 .get(selector)
5617 .copied()
5618 })
5619 .unwrap()
5620 .unwrap_or_else(|| panic!("{selector} was not rendered"))
5621 };
5622
5623 assert_eq!(bounds("cell-0").origin.x, px(0.));
5624 assert_eq!(bounds("cell-1").origin.x, px(100.));
5625 assert_eq!(bounds("cell-2").origin.x, px(300.));
5626 }
5627}