1use crate::{
19 Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent, DispatchPhase,
20 Display, Element, ElementId, Entity, EntityId, ExternalDragPayload, ExternalDragPayloadSource,
21 FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, HitboxId, InspectorElementId,
22 IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, KeyboardButton, KeyboardClickEvent,
23 LayoutId, ModifiersChangedEvent, MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent,
24 MouseMoveEvent, MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement,
25 PinchEvent, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style,
26 StyleRefinement, Styled, Task, TooltipId, Visibility, Window, WindowControlArea, point, px,
27 size,
28};
29use collections::HashMap;
30use gpui_util::ResultExt;
31use refineable::Refineable;
32use smallvec::SmallVec;
33use std::{
34 any::{Any, TypeId},
35 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_drag_move<T>(
339 &mut self,
340 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
341 ) where
342 T: 'static,
343 {
344 self.mouse_move_listeners
345 .push(Box::new(move |event, phase, hitbox, window, cx| {
346 if phase == DispatchPhase::Capture
347 && let Some(drag) = &cx.active_drag
348 && drag.value.as_ref().type_id() == TypeId::of::<T>()
349 {
350 (listener)(
351 &DragMoveEvent {
352 event: event.clone(),
353 bounds: hitbox.bounds,
354 drag: PhantomData,
355 dragged_item: Arc::clone(&drag.value),
356 },
357 window,
358 cx,
359 );
360 }
361 }));
362 }
363
364 pub fn on_scroll_wheel(
369 &mut self,
370 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
371 ) {
372 self.scroll_wheel_listeners
373 .push(Box::new(move |event, phase, hitbox, window, cx| {
374 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
375 (listener)(event, window, cx);
376 }
377 }));
378 }
379
380 pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
384 self.pinch_listeners
385 .push(Box::new(move |event, phase, hitbox, window, cx| {
386 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
387 (listener)(event, window, cx);
388 }
389 }));
390 }
391
392 pub fn capture_pinch(
396 &mut self,
397 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
398 ) {
399 self.pinch_listeners
400 .push(Box::new(move |event, phase, _hitbox, window, cx| {
401 if phase == DispatchPhase::Capture {
402 (listener)(event, window, cx);
403 } else {
404 cx.propagate();
405 }
406 }));
407 }
408
409 pub fn capture_action<A: Action>(
414 &mut self,
415 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
416 ) {
417 self.action_listeners.push((
418 TypeId::of::<A>(),
419 Box::new(move |action, phase, window, cx| {
420 let action = action.downcast_ref().unwrap();
421 if phase == DispatchPhase::Capture {
422 (listener)(action, window, cx)
423 } else {
424 cx.propagate();
425 }
426 }),
427 ));
428 }
429
430 #[track_caller]
435 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
436 self.action_listeners.push((
437 TypeId::of::<A>(),
438 Box::new(move |action, phase, window, cx| {
439 let action = action.downcast_ref().unwrap();
440 if phase == DispatchPhase::Bubble {
441 (listener)(action, window, cx)
442 }
443 }),
444 ));
445 }
446
447 pub fn on_boxed_action(
454 &mut self,
455 action: &dyn Action,
456 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
457 ) {
458 let action = action.boxed_clone();
459 self.action_listeners.push((
460 (*action).type_id(),
461 Box::new(move |_, phase, window, cx| {
462 if phase == DispatchPhase::Bubble {
463 (listener)(&*action, window, cx)
464 }
465 }),
466 ));
467 }
468
469 pub fn on_key_down(
474 &mut self,
475 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
476 ) {
477 self.key_down_listeners
478 .push(Box::new(move |event, phase, window, cx| {
479 if phase == DispatchPhase::Bubble {
480 (listener)(event, window, cx)
481 }
482 }));
483 }
484
485 pub fn capture_key_down(
490 &mut self,
491 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
492 ) {
493 self.key_down_listeners
494 .push(Box::new(move |event, phase, window, cx| {
495 if phase == DispatchPhase::Capture {
496 listener(event, window, cx)
497 }
498 }));
499 }
500
501 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
506 self.key_up_listeners
507 .push(Box::new(move |event, phase, window, cx| {
508 if phase == DispatchPhase::Bubble {
509 listener(event, window, cx)
510 }
511 }));
512 }
513
514 pub fn capture_key_up(
519 &mut self,
520 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
521 ) {
522 self.key_up_listeners
523 .push(Box::new(move |event, phase, window, cx| {
524 if phase == DispatchPhase::Capture {
525 listener(event, window, cx)
526 }
527 }));
528 }
529
530 pub fn on_modifiers_changed(
535 &mut self,
536 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
537 ) {
538 self.modifiers_changed_listeners
539 .push(Box::new(move |event, window, cx| {
540 listener(event, window, cx)
541 }));
542 }
543
544 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
549 self.drop_listeners.push((
550 TypeId::of::<T>(),
551 Box::new(move |dragged_value, window, cx| {
552 listener(dragged_value.downcast_ref().unwrap(), window, cx);
553 }),
554 ));
555 }
556
557 pub fn can_drop(
560 &mut self,
561 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
562 ) {
563 self.can_drop_predicate = Some(Box::new(predicate));
564 }
565
566 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
571 where
572 Self: Sized,
573 {
574 self.click_listeners.push(Rc::new(move |event, window, cx| {
575 listener(event, window, cx)
576 }));
577 }
578
579 pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
584 where
585 Self: Sized,
586 {
587 self.aux_click_listeners
588 .push(Rc::new(move |event, window, cx| {
589 listener(event, window, cx)
590 }));
591 }
592
593 pub fn on_drag<T, W>(
600 &mut self,
601 value: T,
602 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
603 ) where
604 Self: Sized,
605 T: 'static,
606 W: 'static + Render,
607 {
608 debug_assert!(
609 self.drag_listener.is_none(),
610 "calling on_drag more than once on the same element is not supported"
611 );
612 self.drag_listener = Some(DragListener {
613 value: Arc::new(value),
614 render: Box::new(move |value, offset, window, cx| {
615 constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
616 }),
617 external_payload: None,
618 });
619 }
620
621 pub fn external_drag_payload<T>(
626 &mut self,
627 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
628 ) where
629 Self: Sized,
630 T: 'static,
631 {
632 let Some(drag_listener) = self.drag_listener.as_mut() else {
633 debug_assert!(false, "external_drag_payload must be called after on_drag");
634 return;
635 };
636 debug_assert!(
637 drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
638 "external_drag_payload must use the same dragged value type as on_drag"
639 );
640 debug_assert!(
641 drag_listener.external_payload.is_none(),
642 "calling external_drag_payload more than once on the same element is not supported"
643 );
644 drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
645 resolver(value.downcast_ref::<T>()?, window, cx)
646 }));
647 }
648
649 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
656 where
657 Self: Sized,
658 {
659 debug_assert!(
660 self.hover_listener.is_none(),
661 "calling on_hover more than once on the same element is not supported"
662 );
663 self.hover_listener = Some(Box::new(listener));
664 }
665
666 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
669 where
670 Self: Sized,
671 {
672 debug_assert!(
673 self.tooltip_builder.is_none(),
674 "calling tooltip more than once on the same element is not supported"
675 );
676 self.tooltip_builder = Some(TooltipBuilder {
677 build: Rc::new(build_tooltip),
678 hoverable: false,
679 });
680 }
681
682 pub fn hoverable_tooltip(
686 &mut self,
687 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
688 ) where
689 Self: Sized,
690 {
691 debug_assert!(
692 self.tooltip_builder.is_none(),
693 "calling tooltip more than once on the same element is not supported"
694 );
695 self.tooltip_builder = Some(TooltipBuilder {
696 build: Rc::new(build_tooltip),
697 hoverable: true,
698 });
699 }
700
701 pub fn tooltip_show_delay(&mut self, delay: Duration) {
704 self.tooltip_show_delay = Some(delay);
705 }
706
707 pub fn occlude_mouse(&mut self) {
712 self.hitbox_behavior = HitboxBehavior::BlockMouse;
713 }
714
715 pub fn window_control_area(&mut self, area: WindowControlArea) {
718 self.window_control = Some(area);
719 }
720
721 pub fn block_mouse_except_scroll(&mut self) {
726 self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
727 }
728
729 fn has_pinch_listeners(&self) -> bool {
730 !self.pinch_listeners.is_empty()
731 }
732}
733
734pub trait InteractiveElement: Sized {
737 fn interactivity(&mut self) -> &mut Interactivity;
739
740 fn group(mut self, group: impl Into<SharedString>) -> Self {
742 self.interactivity().group = Some(group.into());
743 self
744 }
745
746 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
748 self.interactivity().element_id = Some(id.into());
749
750 Stateful { element: self }
751 }
752
753 fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
757 self.interactivity().focusable = true;
758 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
759 self
760 }
761
762 fn tab_stop(mut self, tab_stop: bool) -> Self {
769 self.interactivity().tab_stop = tab_stop;
770 self
771 }
772
773 fn tab_index(mut self, index: isize) -> Self {
778 self.interactivity().focusable = true;
779 self.interactivity().tab_index = Some(index);
780 self.interactivity().tab_stop = true;
781 self
782 }
783
784 fn tab_group(mut self) -> Self {
789 self.interactivity().tab_group = true;
790 if self.interactivity().tab_index.is_none() {
791 self.interactivity().tab_index = Some(0);
792 }
793 self
794 }
795
796 fn key_context<C, E>(mut self, key_context: C) -> Self
799 where
800 C: TryInto<KeyContext, Error = E>,
801 E: std::fmt::Display,
802 {
803 if let Some(key_context) = key_context.try_into().log_err() {
804 self.interactivity().key_context = Some(key_context);
805 }
806 self
807 }
808
809 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
811 debug_assert!(
812 self.interactivity().hover_style.is_none(),
813 "hover style already set"
814 );
815 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
816 self
817 }
818
819 fn group_hover(
821 mut self,
822 group_name: impl Into<SharedString>,
823 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
824 ) -> Self {
825 self.interactivity().group_hover_style = Some(GroupStyle {
826 group: group_name.into(),
827 style: Box::new(f(StyleRefinement::default())),
828 });
829 self
830 }
831
832 fn on_mouse_down(
837 mut self,
838 button: MouseButton,
839 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
840 ) -> Self {
841 self.interactivity().on_mouse_down(button, listener);
842 self
843 }
844
845 #[cfg(any(test, feature = "test-support"))]
846 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
850 self.interactivity().debug_selector = Some(f());
851 self
852 }
853
854 #[cfg(not(any(test, feature = "test-support")))]
855 #[inline]
859 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
860 self
861 }
862
863 fn capture_any_mouse_down(
868 mut self,
869 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
870 ) -> Self {
871 self.interactivity().capture_any_mouse_down(listener);
872 self
873 }
874
875 fn on_any_mouse_down(
880 mut self,
881 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
882 ) -> Self {
883 self.interactivity().on_any_mouse_down(listener);
884 self
885 }
886
887 fn on_mouse_up(
892 mut self,
893 button: MouseButton,
894 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
895 ) -> Self {
896 self.interactivity().on_mouse_up(button, listener);
897 self
898 }
899
900 fn capture_any_mouse_up(
905 mut self,
906 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
907 ) -> Self {
908 self.interactivity().capture_any_mouse_up(listener);
909 self
910 }
911
912 fn on_mouse_pressure(
917 mut self,
918 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
919 ) -> Self {
920 self.interactivity().on_mouse_pressure(listener);
921 self
922 }
923
924 fn capture_mouse_pressure(
929 mut self,
930 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
931 ) -> Self {
932 self.interactivity().capture_mouse_pressure(listener);
933 self
934 }
935
936 fn on_mouse_down_out(
942 mut self,
943 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
944 ) -> Self {
945 self.interactivity().on_mouse_down_out(listener);
946 self
947 }
948
949 fn on_mouse_up_out(
955 mut self,
956 button: MouseButton,
957 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
958 ) -> Self {
959 self.interactivity().on_mouse_up_out(button, listener);
960 self
961 }
962
963 fn on_mouse_move(
968 mut self,
969 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
970 ) -> Self {
971 self.interactivity().on_mouse_move(listener);
972 self
973 }
974
975 fn on_mouse_exit(
980 mut self,
981 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
982 ) -> Self {
983 self.interactivity().on_mouse_exit(listener);
984 self
985 }
986
987 fn on_drag_move<T: 'static>(
995 mut self,
996 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
997 ) -> Self {
998 self.interactivity().on_drag_move(listener);
999 self
1000 }
1001
1002 fn on_scroll_wheel(
1007 mut self,
1008 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
1009 ) -> Self {
1010 self.interactivity().on_scroll_wheel(listener);
1011 self
1012 }
1013
1014 fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
1019 self.interactivity().on_pinch(listener);
1020 self
1021 }
1022
1023 fn capture_pinch(
1028 mut self,
1029 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
1030 ) -> Self {
1031 self.interactivity().capture_pinch(listener);
1032 self
1033 }
1034 fn capture_action<A: Action>(
1039 mut self,
1040 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1041 ) -> Self {
1042 self.interactivity().capture_action(listener);
1043 self
1044 }
1045
1046 #[track_caller]
1051 fn on_action<A: Action>(
1052 mut self,
1053 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1054 ) -> Self {
1055 self.interactivity().on_action(listener);
1056 self
1057 }
1058
1059 fn on_boxed_action(
1066 mut self,
1067 action: &dyn Action,
1068 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1069 ) -> Self {
1070 self.interactivity().on_boxed_action(action, listener);
1071 self
1072 }
1073
1074 fn on_key_down(
1079 mut self,
1080 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1081 ) -> Self {
1082 self.interactivity().on_key_down(listener);
1083 self
1084 }
1085
1086 fn capture_key_down(
1091 mut self,
1092 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1093 ) -> Self {
1094 self.interactivity().capture_key_down(listener);
1095 self
1096 }
1097
1098 fn on_key_up(
1103 mut self,
1104 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1105 ) -> Self {
1106 self.interactivity().on_key_up(listener);
1107 self
1108 }
1109
1110 fn capture_key_up(
1115 mut self,
1116 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1117 ) -> Self {
1118 self.interactivity().capture_key_up(listener);
1119 self
1120 }
1121
1122 fn on_modifiers_changed(
1127 mut self,
1128 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1129 ) -> Self {
1130 self.interactivity().on_modifiers_changed(listener);
1131 self
1132 }
1133
1134 fn drag_over<S: 'static>(
1136 mut self,
1137 f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1138 ) -> Self {
1139 self.interactivity().drag_over_styles.push((
1140 TypeId::of::<S>(),
1141 Box::new(move |currently_dragged: &dyn Any, window, cx| {
1142 f(
1143 StyleRefinement::default(),
1144 currently_dragged.downcast_ref::<S>().unwrap(),
1145 window,
1146 cx,
1147 )
1148 }),
1149 ));
1150 self
1151 }
1152
1153 fn group_drag_over<S: 'static>(
1155 mut self,
1156 group_name: impl Into<SharedString>,
1157 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1158 ) -> Self {
1159 self.interactivity().group_drag_over_styles.push((
1160 TypeId::of::<S>(),
1161 GroupStyle {
1162 group: group_name.into(),
1163 style: Box::new(f(StyleRefinement::default())),
1164 },
1165 ));
1166 self
1167 }
1168
1169 fn on_drop<T: 'static>(
1174 mut self,
1175 listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1176 ) -> Self {
1177 self.interactivity().on_drop(listener);
1178 self
1179 }
1180
1181 fn can_drop(
1184 mut self,
1185 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1186 ) -> Self {
1187 self.interactivity().can_drop(predicate);
1188 self
1189 }
1190
1191 fn occlude(mut self) -> Self {
1195 self.interactivity().occlude_mouse();
1196 self
1197 }
1198
1199 fn window_control_area(mut self, area: WindowControlArea) -> Self {
1202 self.interactivity().window_control_area(area);
1203 self
1204 }
1205
1206 fn block_mouse_except_scroll(mut self) -> Self {
1211 self.interactivity().block_mouse_except_scroll();
1212 self
1213 }
1214
1215 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1218 where
1219 Self: Sized,
1220 {
1221 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1222 self
1223 }
1224
1225 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1228 where
1229 Self: Sized,
1230 {
1231 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1232 self
1233 }
1234
1235 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1240 where
1241 Self: Sized,
1242 {
1243 self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1244 self
1245 }
1246}
1247
1248pub trait StatefulInteractiveElement: InteractiveElement {
1251 fn role(mut self, role: accesskit::Role) -> Self {
1255 debug_assert!(
1256 role != accesskit::Role::GenericContainer,
1257 "GenericContainer is filtered out of the a11y tree and has no effect"
1258 );
1259 self.interactivity().override_role = Some(role);
1260 self
1261 }
1262
1263 fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self {
1271 self.interactivity().aria.author_id = Some(id.into());
1272 self
1273 }
1274
1275 fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1277 self.interactivity().aria.label = Some(label.into());
1278 self
1279 }
1280
1281 fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
1286 self.interactivity().aria.description = Some(description.into());
1287 self
1288 }
1289
1290 fn aria_keyshortcuts(mut self, keyshortcuts: impl Into<SharedString>) -> Self {
1296 self.interactivity().aria.keyshortcuts = Some(keyshortcuts.into());
1297 self
1298 }
1299
1300 fn aria_active_descendant(mut self) -> Self {
1316 self.interactivity().report_active_descendant_focus = true;
1317 self
1318 }
1319
1320 fn a11y_synthetic_children(
1330 mut self,
1331 f: impl FnOnce(&mut crate::A11ySubtreeBuilder) + 'static,
1332 ) -> Self {
1333 self.interactivity().a11y_synthetic_children = Some(Box::new(f));
1334 self
1335 }
1336
1337 fn aria_selected(mut self, selected: bool) -> Self {
1339 self.interactivity().aria.selected = Some(selected);
1340 self
1341 }
1342
1343 fn aria_expanded(mut self, expanded: bool) -> Self {
1345 self.interactivity().aria.expanded = Some(expanded);
1346 self
1347 }
1348
1349 fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1351 self.interactivity().aria.toggled = Some(toggled);
1352 self
1353 }
1354
1355 fn aria_numeric_value(mut self, value: f64) -> Self {
1357 self.interactivity().aria.numeric_value = Some(value);
1358 self
1359 }
1360
1361 fn aria_numeric_value_step(mut self, step: f64) -> Self {
1364 self.interactivity().aria.numeric_value_step = Some(step);
1365 self
1366 }
1367
1368 fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
1371 self.interactivity().aria.value = Some(value.into());
1372 self
1373 }
1374
1375 fn aria_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1378 self.interactivity().aria.placeholder = Some(placeholder.into());
1379 self
1380 }
1381
1382 fn aria_min_numeric_value(mut self, value: f64) -> Self {
1384 self.interactivity().aria.min_numeric_value = Some(value);
1385 self
1386 }
1387
1388 fn aria_max_numeric_value(mut self, value: f64) -> Self {
1390 self.interactivity().aria.max_numeric_value = Some(value);
1391 self
1392 }
1393
1394 fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1396 self.interactivity().aria.orientation = Some(orientation);
1397 self
1398 }
1399
1400 fn aria_level(mut self, level: usize) -> Self {
1402 self.interactivity().aria.level = Some(level);
1403 self
1404 }
1405
1406 fn aria_position_in_set(mut self, position: usize) -> Self {
1408 self.interactivity().aria.position_in_set = Some(position);
1409 self
1410 }
1411
1412 fn aria_size_of_set(mut self, size: usize) -> Self {
1414 self.interactivity().aria.size_of_set = Some(size);
1415 self
1416 }
1417
1418 fn aria_row_index(mut self, index: usize) -> Self {
1420 self.interactivity().aria.row_index = Some(index);
1421 self
1422 }
1423
1424 fn aria_column_index(mut self, index: usize) -> Self {
1426 self.interactivity().aria.column_index = Some(index);
1427 self
1428 }
1429
1430 fn aria_row_count(mut self, count: usize) -> Self {
1432 self.interactivity().aria.row_count = Some(count);
1433 self
1434 }
1435
1436 fn aria_column_count(mut self, count: usize) -> Self {
1438 self.interactivity().aria.column_count = Some(count);
1439 self
1440 }
1441
1442 fn on_a11y_action(
1447 mut self,
1448 action: accesskit::Action,
1449 listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1450 + 'static,
1451 ) -> Self {
1452 self.interactivity()
1453 .a11y_action_listeners
1454 .push((action, Box::new(listener)));
1455 self
1456 }
1457
1458 fn focusable(mut self) -> Self {
1460 self.interactivity().focusable = true;
1461 self
1462 }
1463
1464 fn overflow_scroll(mut self) -> Self {
1466 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1467 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1468 self
1469 }
1470
1471 fn overflow_x_scroll(mut self) -> Self {
1473 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1474 self
1475 }
1476
1477 fn overflow_y_scroll(mut self) -> Self {
1479 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1480 self
1481 }
1482
1483 fn restrict_scroll_to_axis(mut self) -> Self {
1487 self.interactivity().base_style.restrict_scroll_to_axis = Some(true);
1488 self
1489 }
1490
1491 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1493 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1494 self
1495 }
1496
1497 fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1499 self.interactivity().scroll_anchor = scroll_anchor;
1500 self
1501 }
1502
1503 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1505 where
1506 Self: Sized,
1507 {
1508 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1509 self
1510 }
1511
1512 fn group_active(
1514 mut self,
1515 group_name: impl Into<SharedString>,
1516 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1517 ) -> Self
1518 where
1519 Self: Sized,
1520 {
1521 self.interactivity().group_active_style = Some(GroupStyle {
1522 group: group_name.into(),
1523 style: Box::new(f(StyleRefinement::default())),
1524 });
1525 self
1526 }
1527
1528 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1533 where
1534 Self: Sized,
1535 {
1536 self.interactivity().on_click(listener);
1537 self
1538 }
1539
1540 fn on_aux_click(
1545 mut self,
1546 listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1547 ) -> Self
1548 where
1549 Self: Sized,
1550 {
1551 self.interactivity().on_aux_click(listener);
1552 self
1553 }
1554
1555 fn on_drag<T, W>(
1563 mut self,
1564 value: T,
1565 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1566 ) -> Self
1567 where
1568 Self: Sized,
1569 T: 'static,
1570 W: 'static + Render,
1571 {
1572 self.interactivity().on_drag(value, constructor);
1573 self
1574 }
1575
1576 fn external_drag_payload<T>(
1582 mut self,
1583 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
1584 ) -> Self
1585 where
1586 Self: Sized,
1587 T: 'static,
1588 {
1589 self.interactivity().external_drag_payload(resolver);
1590 self
1591 }
1592
1593 fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1600 where
1601 Self: Sized,
1602 {
1603 self.interactivity().on_hover(listener);
1604 self
1605 }
1606
1607 fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1610 where
1611 Self: Sized,
1612 {
1613 self.interactivity().tooltip(build_tooltip);
1614 self
1615 }
1616
1617 fn hoverable_tooltip(
1621 mut self,
1622 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1623 ) -> Self
1624 where
1625 Self: Sized,
1626 {
1627 self.interactivity().hoverable_tooltip(build_tooltip);
1628 self
1629 }
1630
1631 fn tooltip_show_delay(mut self, delay: Duration) -> Self
1634 where
1635 Self: Sized,
1636 {
1637 self.interactivity().tooltip_show_delay(delay);
1638 self
1639 }
1640}
1641
1642pub(crate) type MouseDownListener =
1643 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1644pub(crate) type MouseUpListener =
1645 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1646pub(crate) type MousePressureListener =
1647 Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1648pub(crate) type MouseMoveListener =
1649 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1650pub(crate) type MouseExitListener =
1651 Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1652
1653pub(crate) type ScrollWheelListener =
1654 Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1655
1656pub(crate) type PinchListener =
1657 Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1658
1659pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1660
1661pub(crate) struct DragListener {
1662 value: Arc<dyn Any>,
1663 render: Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>,
1664 external_payload: Option<ExternalDragPayloadResolver>,
1665}
1666
1667type ExternalDragPayloadResolver =
1668 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
1669
1670type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1671
1672type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1673
1674pub(crate) struct TooltipBuilder {
1675 build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1676 hoverable: bool,
1677}
1678
1679pub(crate) type KeyDownListener =
1680 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1681
1682pub(crate) type KeyUpListener =
1683 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1684
1685pub(crate) type ModifiersChangedListener =
1686 Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1687
1688pub(crate) type ActionListener =
1689 Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1690
1691#[track_caller]
1693pub fn div() -> Div {
1694 Div {
1695 interactivity: Interactivity::new(),
1696 children: SmallVec::default(),
1697 prepaint_listener: None,
1698 image_cache: None,
1699 prepaint_order_fn: None,
1700 }
1701}
1702
1703pub struct Div {
1705 interactivity: Interactivity,
1706 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1707 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1708 image_cache: Option<Box<dyn ImageCacheProvider>>,
1709 prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1710}
1711
1712impl Div {
1713 pub fn on_children_prepainted(
1716 mut self,
1717 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1718 ) -> Self {
1719 self.prepaint_listener = Some(Box::new(listener));
1720 self
1721 }
1722
1723 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1725 self.image_cache = Some(Box::new(cache));
1726 self
1727 }
1728
1729 pub fn with_dynamic_prepaint_order(
1738 mut self,
1739 order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1740 ) -> Self {
1741 self.prepaint_order_fn = Some(Box::new(order_fn));
1742 self
1743 }
1744}
1745
1746pub struct DivFrameState {
1753 child_layout_ids: SmallVec<[LayoutId; 2]>,
1754}
1755
1756#[derive(Clone)]
1758pub struct DivInspectorState {
1759 #[cfg(any(feature = "inspector", debug_assertions))]
1763 pub base_style: Box<StyleRefinement>,
1764 pub bounds: Bounds<Pixels>,
1766 pub content_size: Size<Pixels>,
1768}
1769
1770impl Styled for Div {
1771 fn style(&mut self) -> &mut StyleRefinement {
1772 &mut self.interactivity.base_style
1773 }
1774}
1775
1776impl InteractiveElement for Div {
1777 fn interactivity(&mut self) -> &mut Interactivity {
1778 &mut self.interactivity
1779 }
1780}
1781
1782impl ParentElement for Div {
1783 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1784 #[cfg(feature = "stacker")]
1785 self.children
1786 .extend(elements.into_iter().map(StackSafe::new));
1787 #[cfg(not(feature = "stacker"))]
1788 self.children.extend(elements);
1789 }
1790}
1791
1792impl Element for Div {
1793 type RequestLayoutState = DivFrameState;
1794 type PrepaintState = Option<Hitbox>;
1795
1796 fn id(&self) -> Option<ElementId> {
1797 self.interactivity.element_id.clone()
1798 }
1799
1800 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1801 self.interactivity.source_location()
1802 }
1803
1804 fn a11y_role(&self) -> Option<accesskit::Role> {
1805 self.interactivity
1808 .override_role
1809 .filter(|role| *role != accesskit::Role::GenericContainer)
1810 }
1811
1812 fn write_a11y_info(&self, node: &mut accesskit::Node) {
1813 self.interactivity.write_a11y_info(node);
1814 }
1815
1816 fn a11y_synthetic_children(
1817 &mut self,
1818 _prepaint: &mut Self::PrepaintState,
1819 builder: &mut crate::A11ySubtreeBuilder,
1820 ) {
1821 if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
1822 f(builder);
1823 }
1824 }
1825
1826 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
1827 fn request_layout(
1828 &mut self,
1829 global_id: Option<&GlobalElementId>,
1830 inspector_id: Option<&InspectorElementId>,
1831 window: &mut Window,
1832 cx: &mut App,
1833 ) -> (LayoutId, Self::RequestLayoutState) {
1834 let mut child_layout_ids = SmallVec::new();
1835 let image_cache = self
1836 .image_cache
1837 .as_mut()
1838 .map(|provider| provider.provide(window, cx));
1839
1840 let layout_id = window.with_image_cache(image_cache, |window| {
1841 self.interactivity.request_layout(
1842 global_id,
1843 inspector_id,
1844 window,
1845 cx,
1846 |style, window, cx| {
1847 window.with_text_style(style.text_style().cloned(), |window| {
1848 child_layout_ids = self
1849 .children
1850 .iter_mut()
1851 .map(|child| child.request_layout(window, cx))
1852 .collect::<SmallVec<_>>();
1853 window.request_layout(style, child_layout_ids.iter().copied(), cx)
1854 })
1855 },
1856 )
1857 });
1858
1859 (layout_id, DivFrameState { child_layout_ids })
1860 }
1861
1862 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
1863 fn prepaint(
1864 &mut self,
1865 global_id: Option<&GlobalElementId>,
1866 inspector_id: Option<&InspectorElementId>,
1867 bounds: Bounds<Pixels>,
1868 request_layout: &mut Self::RequestLayoutState,
1869 window: &mut Window,
1870 cx: &mut App,
1871 ) -> Option<Hitbox> {
1872 let image_cache = self
1873 .image_cache
1874 .as_mut()
1875 .map(|provider| provider.provide(window, cx));
1876
1877 let has_prepaint_listener = self.prepaint_listener.is_some();
1878 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1879 request_layout.child_layout_ids.len()
1880 } else {
1881 0
1882 });
1883
1884 let mut child_min = point(Pixels::MAX, Pixels::MAX);
1885 let mut child_max = Point::default();
1886 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1887 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1888 }
1889 let content_size = if request_layout.child_layout_ids.is_empty() {
1890 bounds.size
1891 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1892 let mut state = scroll_handle.0.borrow_mut();
1893 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1894 for child_layout_id in &request_layout.child_layout_ids {
1895 let child_bounds = window.layout_bounds(*child_layout_id);
1896 child_min = child_min.min(&child_bounds.origin);
1897 child_max = child_max.max(&child_bounds.bottom_right());
1898 state.child_bounds.push(child_bounds);
1899 }
1900 (child_max - child_min).into()
1901 } else {
1902 for child_layout_id in &request_layout.child_layout_ids {
1903 let child_bounds = window.layout_bounds(*child_layout_id);
1904 child_min = child_min.min(&child_bounds.origin);
1905 child_max = child_max.max(&child_bounds.bottom_right());
1906
1907 if has_prepaint_listener {
1908 children_bounds.push(child_bounds);
1909 }
1910 }
1911 (child_max - child_min).into()
1912 };
1913
1914 if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1915 scroll_handle.scroll_to_active_item();
1916 }
1917
1918 self.interactivity.prepaint(
1919 global_id,
1920 inspector_id,
1921 bounds,
1922 content_size,
1923 window,
1924 cx,
1925 |style, scroll_offset, hitbox, window, cx| {
1926 if style.display == Display::None {
1928 return hitbox;
1929 }
1930
1931 window.with_image_cache(image_cache, |window| {
1932 window.with_element_offset(scroll_offset, |window| {
1933 if let Some(order_fn) = &self.prepaint_order_fn {
1934 let order = order_fn(window, cx);
1935 for idx in order {
1936 if let Some(child) = self.children.get_mut(idx) {
1937 child.prepaint(window, cx);
1938 }
1939 }
1940 } else {
1941 for child in &mut self.children {
1942 child.prepaint(window, cx);
1943 }
1944 }
1945 });
1946
1947 if let Some(listener) = self.prepaint_listener.as_ref() {
1948 listener(children_bounds, window, cx);
1949 }
1950 });
1951
1952 hitbox
1953 },
1954 )
1955 }
1956
1957 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
1958 fn paint(
1959 &mut self,
1960 global_id: Option<&GlobalElementId>,
1961 inspector_id: Option<&InspectorElementId>,
1962 bounds: Bounds<Pixels>,
1963 _request_layout: &mut Self::RequestLayoutState,
1964 hitbox: &mut Option<Hitbox>,
1965 window: &mut Window,
1966 cx: &mut App,
1967 ) {
1968 let image_cache = self
1969 .image_cache
1970 .as_mut()
1971 .map(|provider| provider.provide(window, cx));
1972
1973 window.with_image_cache(image_cache, |window| {
1974 self.interactivity.paint(
1975 global_id,
1976 inspector_id,
1977 bounds,
1978 hitbox.as_ref(),
1979 window,
1980 cx,
1981 |style, window, cx| {
1982 if style.display == Display::None {
1984 return;
1985 }
1986
1987 for child in &mut self.children {
1988 child.paint(window, cx);
1989 }
1990 },
1991 )
1992 });
1993 }
1994}
1995
1996impl IntoElement for Div {
1997 type Element = Self;
1998
1999 fn into_element(self) -> Self::Element {
2000 self
2001 }
2002}
2003
2004#[derive(Default)]
2005pub(crate) struct AriaProperties {
2006 pub(crate) author_id: Option<SharedString>,
2007 pub(crate) label: Option<SharedString>,
2008 pub(crate) description: Option<SharedString>,
2009 pub(crate) keyshortcuts: Option<SharedString>,
2010 pub(crate) selected: Option<bool>,
2011 pub(crate) expanded: Option<bool>,
2012 pub(crate) toggled: Option<accesskit::Toggled>,
2013 pub(crate) numeric_value: Option<f64>,
2014 pub(crate) min_numeric_value: Option<f64>,
2015 pub(crate) max_numeric_value: Option<f64>,
2016 pub(crate) numeric_value_step: Option<f64>,
2017 pub(crate) value: Option<SharedString>,
2018 pub(crate) placeholder: Option<SharedString>,
2019 pub(crate) orientation: Option<accesskit::Orientation>,
2020 pub(crate) level: Option<usize>,
2021 pub(crate) position_in_set: Option<usize>,
2022 pub(crate) size_of_set: Option<usize>,
2023 pub(crate) row_index: Option<usize>,
2024 pub(crate) column_index: Option<usize>,
2025 pub(crate) row_count: Option<usize>,
2026 pub(crate) column_count: Option<usize>,
2027}
2028
2029#[derive(Default)]
2032pub struct Interactivity {
2033 pub element_id: Option<ElementId>,
2035 pub active: Option<bool>,
2037 pub hovered: Option<bool>,
2040 pub(crate) tooltip_id: Option<TooltipId>,
2041 pub(crate) content_size: Size<Pixels>,
2042 pub(crate) key_context: Option<KeyContext>,
2043 pub(crate) focusable: bool,
2044 pub(crate) tracked_focus_handle: Option<FocusHandle>,
2045 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2046 pub(crate) scroll_anchor: Option<ScrollAnchor>,
2047 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2048 pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2049 pub(crate) group: Option<SharedString>,
2050 pub base_style: Box<StyleRefinement>,
2053 pub(crate) focus_style: Option<Box<StyleRefinement>>,
2054 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2055 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2056 pub(crate) hover_style: Option<Box<StyleRefinement>>,
2057 pub(crate) group_hover_style: Option<GroupStyle>,
2058 pub(crate) active_style: Option<Box<StyleRefinement>>,
2059 pub(crate) group_active_style: Option<GroupStyle>,
2060 pub(crate) drag_over_styles: Vec<(
2061 TypeId,
2062 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2063 )>,
2064 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
2065 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
2066 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
2067 pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
2068 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
2069 pub(crate) mouse_exit_listeners: Vec<MouseExitListener>,
2070 pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
2071 pub(crate) pinch_listeners: Vec<PinchListener>,
2072 pub(crate) key_down_listeners: Vec<KeyDownListener>,
2073 pub(crate) key_up_listeners: Vec<KeyUpListener>,
2074 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
2075 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
2076 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
2077 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
2078 pub(crate) click_listeners: Vec<ClickListener>,
2079 pub(crate) aux_click_listeners: Vec<ClickListener>,
2080 pub(crate) drag_listener: Option<DragListener>,
2081 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2082 pub(crate) tooltip_builder: Option<TooltipBuilder>,
2083 pub(crate) tooltip_show_delay: Option<Duration>,
2084 pub(crate) window_control: Option<WindowControlArea>,
2085 pub(crate) hitbox_behavior: HitboxBehavior,
2086 pub(crate) tab_index: Option<isize>,
2087 pub(crate) tab_group: bool,
2088 pub(crate) tab_stop: bool,
2089
2090 pub(crate) a11y_action_listeners:
2091 Vec<(accesskit::Action, crate::window::a11y::A11yActionListener)>,
2092 pub(crate) a11y_synthetic_children: Option<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2093 pub(crate) report_active_descendant_focus: bool,
2094 pub(crate) override_role: Option<accesskit::Role>,
2095 pub(crate) aria: AriaProperties,
2096
2097 #[cfg(any(feature = "inspector", debug_assertions))]
2098 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2099
2100 #[cfg(any(test, feature = "test-support"))]
2101 pub(crate) debug_selector: Option<String>,
2102}
2103
2104impl Interactivity {
2105 pub fn request_layout(
2107 &mut self,
2108 global_id: Option<&GlobalElementId>,
2109 _inspector_id: Option<&InspectorElementId>,
2110 window: &mut Window,
2111 cx: &mut App,
2112 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2113 ) -> LayoutId {
2114 #[cfg(any(feature = "inspector", debug_assertions))]
2115 window.with_inspector_state(
2116 _inspector_id,
2117 cx,
2118 |inspector_state: &mut Option<DivInspectorState>, _window| {
2119 if let Some(inspector_state) = inspector_state {
2120 self.base_style = inspector_state.base_style.clone();
2121 } else {
2122 *inspector_state = Some(DivInspectorState {
2123 base_style: self.base_style.clone(),
2124 bounds: Default::default(),
2125 content_size: Default::default(),
2126 })
2127 }
2128 },
2129 );
2130
2131 window.with_optional_element_state::<InteractiveElementState, _>(
2132 global_id,
2133 |element_state, window| {
2134 let mut element_state =
2135 element_state.map(|element_state| element_state.unwrap_or_default());
2136
2137 if let Some(element_state) = element_state.as_ref()
2138 && cx.has_active_drag()
2139 {
2140 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2141 *pending_mouse_down.borrow_mut() = None;
2142 }
2143 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2144 *clicked_state.borrow_mut() = ElementClickedState::default();
2145 }
2146 }
2147
2148 if self.focusable
2153 && self.tracked_focus_handle.is_none()
2154 && let Some(element_state) = element_state.as_mut()
2155 {
2156 let mut handle = element_state
2157 .focus_handle
2158 .get_or_insert_with(|| cx.focus_handle())
2159 .clone()
2160 .tab_stop(self.tab_stop);
2161
2162 if let Some(index) = self.tab_index {
2163 handle = handle.tab_index(index);
2164 }
2165
2166 self.tracked_focus_handle = Some(handle);
2167 }
2168
2169 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2170 let scroll_handle_state = scroll_handle.0.borrow();
2171 self.scroll_offset = Some(scroll_handle_state.offset.clone());
2172 self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2173 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2174 || self.base_style.overflow.y == Some(Overflow::Scroll))
2175 && let Some(element_state) = element_state.as_mut()
2176 {
2177 self.scroll_offset = Some(
2178 element_state
2179 .scroll_offset
2180 .get_or_insert_with(Rc::default)
2181 .clone(),
2182 );
2183 self.ongoing_scroll = Some(
2184 element_state
2185 .ongoing_scroll
2186 .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2187 .clone(),
2188 );
2189 }
2190
2191 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2192 let layout_id = f(style, window, cx);
2193 (layout_id, element_state)
2194 },
2195 )
2196 }
2197
2198 pub fn prepaint<R>(
2200 &mut self,
2201 global_id: Option<&GlobalElementId>,
2202 _inspector_id: Option<&InspectorElementId>,
2203 bounds: Bounds<Pixels>,
2204 content_size: Size<Pixels>,
2205 window: &mut Window,
2206 cx: &mut App,
2207 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2208 ) -> R {
2209 self.content_size = content_size;
2210
2211 #[cfg(any(feature = "inspector", debug_assertions))]
2212 window.with_inspector_state(
2213 _inspector_id,
2214 cx,
2215 |inspector_state: &mut Option<DivInspectorState>, _window| {
2216 if let Some(inspector_state) = inspector_state {
2217 inspector_state.bounds = bounds;
2218 inspector_state.content_size = content_size;
2219 }
2220 },
2221 );
2222
2223 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2224 window.set_focus_handle(focus_handle, cx);
2225
2226 if window.a11y.is_active() {
2227 if let Some(global_id) = global_id {
2228 let node_id = global_id.accesskit_node_id();
2229 window.a11y.set_focusable(node_id, focus_handle.id);
2230 if focus_handle.is_focused(window) {
2231 window.a11y.set_focus(node_id);
2232 }
2233 } else if focus_handle.is_focused(window) {
2234 window
2238 .a11y
2239 .note_focus_without_node(focus_handle.id, "it has no element id");
2240 }
2241 }
2242 }
2243
2244 if self.report_active_descendant_focus && window.a11y.is_active() {
2245 if let Some(global_id) = global_id {
2246 window
2247 .a11y
2248 .set_active_descendant(global_id.accesskit_node_id());
2249 }
2250 }
2251 window.with_optional_element_state::<InteractiveElementState, _>(
2252 global_id,
2253 |element_state, window| {
2254 let mut element_state =
2255 element_state.map(|element_state| element_state.unwrap_or_default());
2256 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2257
2258 if let Some(element_state) = element_state.as_mut() {
2259 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2260 let clicked_state = clicked_state.borrow();
2261 self.active = Some(clicked_state.element);
2262 }
2263 if self.hover_style.is_some() || self.group_hover_style.is_some() {
2264 element_state
2265 .hover_state
2266 .get_or_insert_with(Default::default);
2267 }
2268 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2269 if self.tooltip_builder.is_some() {
2270 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2271 } else {
2272 element_state.active_tooltip.take();
2274 }
2275 }
2276 }
2277
2278 window.with_text_style(style.text_style().cloned(), |window| {
2279 window.with_content_mask(
2280 style.overflow_mask(bounds, window.rem_size()),
2281 |window| {
2282 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2283 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2284 } else {
2285 None
2286 };
2287
2288 let scroll_offset =
2289 self.clamp_scroll_position(bounds, &style, window, cx);
2290 let result = f(&style, scroll_offset, hitbox, window, cx);
2291 (result, element_state)
2292 },
2293 )
2294 })
2295 },
2296 )
2297 }
2298
2299 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2300 self.hitbox_behavior != HitboxBehavior::Normal
2301 || self.window_control.is_some()
2302 || style.mouse_cursor.is_some()
2303 || self.group.is_some()
2304 || self.scroll_offset.is_some()
2305 || self.tracked_focus_handle.is_some()
2306 || self.hover_style.is_some()
2307 || self.group_hover_style.is_some()
2308 || self.hover_listener.is_some()
2309 || !self.mouse_up_listeners.is_empty()
2310 || !self.mouse_pressure_listeners.is_empty()
2311 || !self.mouse_down_listeners.is_empty()
2312 || !self.mouse_move_listeners.is_empty()
2313 || !self.mouse_exit_listeners.is_empty()
2314 || !self.click_listeners.is_empty()
2315 || !self.aux_click_listeners.is_empty()
2316 || !self.scroll_wheel_listeners.is_empty()
2317 || self.has_pinch_listeners()
2318 || self.drag_listener.is_some()
2319 || !self.drop_listeners.is_empty()
2320 || !self.drag_over_styles.is_empty()
2321 || self.tooltip_builder.is_some()
2322 || window.is_inspector_picking(cx)
2323 }
2324
2325 fn clamp_scroll_position(
2326 &self,
2327 bounds: Bounds<Pixels>,
2328 style: &Style,
2329 window: &mut Window,
2330 _cx: &mut App,
2331 ) -> Point<Pixels> {
2332 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2333 const ROUNDING_FACTOR: f32 = 100.0;
2334 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2335 }
2336
2337 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2338 let mut scroll_to_bottom = false;
2339 let mut tracked_scroll_handle = self
2340 .tracked_scroll_handle
2341 .as_ref()
2342 .map(|handle| handle.0.borrow_mut());
2343 if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2344 scroll_handle_state.overflow = style.overflow;
2345 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2346 }
2347
2348 let rem_size = window.rem_size();
2349 let padding = style
2354 .padding
2355 .to_pixels(bounds.size.into(), rem_size)
2356 .map(|edge| window.pixel_snap(*edge));
2357 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2358 let padded_content_size = self.content_size + padding_size;
2365 let scroll_max = Point::from(padded_content_size - bounds.size)
2366 .map(round_to_two_decimals)
2367 .max(&Default::default());
2368 let mut scroll_offset = scroll_offset.borrow_mut();
2371
2372 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2373 if scroll_to_bottom {
2374 scroll_offset.y = -scroll_max.y;
2375 } else {
2376 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2377 }
2378
2379 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2380 scroll_handle_state.max_offset = scroll_max;
2381 scroll_handle_state.bounds = bounds;
2382 }
2383
2384 *scroll_offset
2385 } else {
2386 Point::default()
2387 }
2388 }
2389
2390 pub fn paint(
2399 &mut self,
2400 global_id: Option<&GlobalElementId>,
2401 _inspector_id: Option<&InspectorElementId>,
2402 bounds: Bounds<Pixels>,
2403 hitbox: Option<&Hitbox>,
2404 window: &mut Window,
2405 cx: &mut App,
2406 f: impl FnOnce(&Style, &mut Window, &mut App),
2407 ) {
2408 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2409 window.with_optional_element_state::<InteractiveElementState, _>(
2410 global_id,
2411 |element_state, window| {
2412 let mut element_state =
2413 element_state.map(|element_state| element_state.unwrap_or_default());
2414
2415 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2416
2417 #[cfg(any(feature = "test-support", test))]
2418 if let Some(debug_selector) = &self.debug_selector {
2419 window
2420 .next_frame
2421 .debug_bounds
2422 .insert(debug_selector.clone(), bounds);
2423 }
2424
2425 self.paint_hover_group_handler(window, cx);
2426
2427 if style.visibility == Visibility::Hidden {
2428 return ((), element_state);
2429 }
2430
2431 let mut tab_group = None;
2432 if self.tab_group {
2433 tab_group = self.tab_index;
2434 }
2435
2436 window.with_element_opacity(style.opacity, |window| {
2437 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2438 window.with_text_style(style.text_style().cloned(), |window| {
2439 window.with_content_mask(
2440 style.overflow_mask(bounds, window.rem_size()),
2441 |window| {
2442 window.with_tab_group(tab_group, |window| {
2443 if let Some(focus_handle) = &self.tracked_focus_handle {
2452 window.next_frame.tab_stops.insert(focus_handle);
2453 }
2454 if let Some(hitbox) = hitbox {
2455 #[cfg(debug_assertions)]
2456 self.paint_debug_info(
2457 global_id, hitbox, &style, window, cx,
2458 );
2459
2460 if let Some(drag) = cx.active_drag.as_ref() {
2461 if let Some(mouse_cursor) = drag.cursor_style {
2462 window.set_window_cursor_style(mouse_cursor);
2463 }
2464 } else {
2465 if let Some(mouse_cursor) = style.mouse_cursor {
2466 window.set_cursor_style(mouse_cursor, hitbox);
2467 }
2468 }
2469
2470 if let Some(group) = self.group.clone() {
2471 GroupHitboxes::push(group, hitbox.id, cx);
2472 }
2473
2474 if let Some(area) = self.window_control {
2475 window.insert_window_control_hitbox(
2476 area,
2477 hitbox.clone(),
2478 );
2479 }
2480
2481 self.paint_mouse_listeners(
2482 hitbox,
2483 element_state.as_mut(),
2484 window,
2485 cx,
2486 );
2487 self.paint_scroll_listener(hitbox, &style, window, cx);
2488 }
2489
2490 self.paint_keyboard_listeners(window, cx);
2491
2492 if window.a11y.is_active() {
2493 if let Some(global_id) = global_id {
2494 if !self.a11y_action_listeners.is_empty() {
2495 let node_id = global_id.accesskit_node_id();
2496 for (action, listener) in
2497 self.a11y_action_listeners.drain(..)
2498 {
2499 window.on_a11y_action(
2500 node_id, action, listener,
2501 );
2502 }
2503 }
2504 }
2505 }
2506
2507 f(&style, window, cx);
2508
2509 if let Some(_hitbox) = hitbox {
2510 #[cfg(any(feature = "inspector", debug_assertions))]
2511 window.insert_inspector_hitbox(
2512 _hitbox.id,
2513 _inspector_id,
2514 cx,
2515 );
2516
2517 if let Some(group) = self.group.as_ref() {
2518 GroupHitboxes::pop(group, cx);
2519 }
2520 }
2521 })
2522 },
2523 );
2524 });
2525 });
2526 });
2527
2528 ((), element_state)
2529 },
2530 );
2531 }
2532
2533 #[cfg(debug_assertions)]
2534 fn paint_debug_info(
2535 &self,
2536 global_id: Option<&GlobalElementId>,
2537 hitbox: &Hitbox,
2538 style: &Style,
2539 window: &mut Window,
2540 cx: &mut App,
2541 ) {
2542 use crate::{BorderStyle, TextAlign};
2543
2544 if let Some(global_id) = global_id
2545 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2546 && hitbox.is_hovered(window)
2547 {
2548 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2549 let element_id = format!("{global_id:?}");
2550 let str_len = element_id.len();
2551
2552 let render_debug_text = |window: &mut Window| {
2553 if let Some(text) = window
2554 .text_system()
2555 .shape_text(
2556 element_id.into(),
2557 FONT_SIZE,
2558 &[window.text_style().to_run(str_len)],
2559 None,
2560 None,
2561 )
2562 .ok()
2563 .and_then(|mut text| text.pop())
2564 {
2565 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2566 .ok();
2567
2568 let text_bounds = crate::Bounds {
2569 origin: hitbox.origin,
2570 size: text.size(FONT_SIZE),
2571 };
2572 if let Some(source_location) = self.source_location
2573 && text_bounds.contains(&window.mouse_position())
2574 && window.modifiers().secondary()
2575 {
2576 let secondary_held = window.modifiers().secondary();
2577 window.on_key_event({
2578 move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2579 if e.modifiers.secondary() != secondary_held
2580 && text_bounds.contains(&window.mouse_position())
2581 {
2582 window.refresh();
2583 }
2584 }
2585 });
2586
2587 let was_hovered = hitbox.is_hovered(window);
2588 let current_view = window.current_view();
2589 window.on_mouse_event({
2590 let hitbox = hitbox.clone();
2591 move |_: &MouseMoveEvent, phase, window, cx| {
2592 if phase == DispatchPhase::Capture {
2593 let hovered = hitbox.is_hovered(window);
2594 if hovered != was_hovered {
2595 cx.notify(current_view)
2596 }
2597 }
2598 }
2599 });
2600
2601 window.on_mouse_event({
2602 let hitbox = hitbox.clone();
2603 move |e: &crate::MouseDownEvent, phase, window, cx| {
2604 if text_bounds.contains(&e.position)
2605 && phase.capture()
2606 && hitbox.is_hovered(window)
2607 {
2608 cx.stop_propagation();
2609 let Ok(dir) = std::env::current_dir() else {
2610 return;
2611 };
2612
2613 eprintln!(
2614 "This element was created at:\n{}:{}:{}",
2615 dir.join(source_location.file()).to_string_lossy(),
2616 source_location.line(),
2617 source_location.column()
2618 );
2619 }
2620 }
2621 });
2622 window.paint_quad(crate::outline(
2623 crate::Bounds {
2624 origin: hitbox.origin
2625 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2626 size: crate::Size {
2627 width: text_bounds.size.width,
2628 height: crate::px(1.),
2629 },
2630 },
2631 crate::red(),
2632 BorderStyle::default(),
2633 ))
2634 }
2635 }
2636 };
2637
2638 window.with_text_style(
2639 Some(crate::TextStyleRefinement {
2640 color: Some(crate::red()),
2641 line_height: Some(FONT_SIZE.into()),
2642 background_color: Some(crate::white()),
2643 ..Default::default()
2644 }),
2645 render_debug_text,
2646 )
2647 }
2648 }
2649
2650 fn paint_mouse_listeners(
2651 &mut self,
2652 hitbox: &Hitbox,
2653 element_state: Option<&mut InteractiveElementState>,
2654 window: &mut Window,
2655 cx: &mut App,
2656 ) {
2657 let is_focused = self
2658 .tracked_focus_handle
2659 .as_ref()
2660 .map(|handle| handle.is_focused(window))
2661 .unwrap_or(false);
2662
2663 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2667 let hitbox = hitbox.clone();
2668 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2669 if phase == DispatchPhase::Bubble
2670 && hitbox.is_hovered(window)
2671 && !window.default_prevented()
2672 {
2673 window.focus(&focus_handle, cx);
2674 window.prevent_default();
2677 }
2678 });
2679 }
2680
2681 for listener in self.mouse_down_listeners.drain(..) {
2682 let hitbox = hitbox.clone();
2683 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2684 listener(event, phase, &hitbox, window, cx);
2685 })
2686 }
2687
2688 for listener in self.mouse_up_listeners.drain(..) {
2689 let hitbox = hitbox.clone();
2690 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2691 listener(event, phase, &hitbox, window, cx);
2692 })
2693 }
2694
2695 for listener in self.mouse_pressure_listeners.drain(..) {
2696 let hitbox = hitbox.clone();
2697 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2698 listener(event, phase, &hitbox, window, cx);
2699 })
2700 }
2701
2702 for listener in self.mouse_move_listeners.drain(..) {
2703 let hitbox = hitbox.clone();
2704 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2705 listener(event, phase, &hitbox, window, cx);
2706 })
2707 }
2708
2709 for listener in self.mouse_exit_listeners.drain(..) {
2710 let hitbox = hitbox.clone();
2711 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2712 listener(event, phase, &hitbox, window, cx);
2713 })
2714 }
2715
2716 for listener in self.scroll_wheel_listeners.drain(..) {
2717 let hitbox = hitbox.clone();
2718 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2719 listener(event, phase, &hitbox, window, cx);
2720 })
2721 }
2722
2723 for listener in self.pinch_listeners.drain(..) {
2724 let hitbox = hitbox.clone();
2725 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2726 listener(event, phase, &hitbox, window, cx);
2727 })
2728 }
2729
2730 if self.hover_style.is_some()
2731 || self.base_style.mouse_cursor.is_some()
2732 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2733 {
2734 let hitbox = hitbox.clone();
2735 let hover_state = self.hover_style.as_ref().and_then(|_| {
2736 element_state
2737 .as_ref()
2738 .and_then(|state| state.hover_state.as_ref())
2739 .cloned()
2740 });
2741 let current_view = window.current_view();
2742
2743 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2744 let hovered = hitbox.is_hovered(window);
2745 let was_hovered = hover_state
2746 .as_ref()
2747 .is_some_and(|state| state.borrow().element);
2748 if phase == DispatchPhase::Capture && hovered != was_hovered {
2749 if let Some(hover_state) = &hover_state {
2750 hover_state.borrow_mut().element = hovered;
2751 cx.notify(current_view);
2752 }
2753 }
2754 });
2755 }
2756
2757 if let Some(group_hover) = self.group_hover_style.as_ref() {
2758 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2759 let hover_state = element_state
2760 .as_ref()
2761 .and_then(|element| element.hover_state.as_ref())
2762 .cloned();
2763 let current_view = window.current_view();
2764
2765 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2766 let group_hovered = group_hitbox_id.is_hovered(window);
2767 let was_group_hovered = hover_state
2768 .as_ref()
2769 .is_some_and(|state| state.borrow().group);
2770 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2771 if let Some(hover_state) = &hover_state {
2772 hover_state.borrow_mut().group = group_hovered;
2773 cx.notify(current_view);
2774 }
2775 }
2776 });
2777 }
2778 }
2779
2780 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2781
2782 let mut drag_listener = mem::take(&mut self.drag_listener);
2783 let drop_listeners = mem::take(&mut self.drop_listeners);
2784 let click_listeners = mem::take(&mut self.click_listeners);
2785 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2786 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2787
2788 if !drop_listeners.is_empty() {
2789 let hitbox = hitbox.clone();
2790 window.on_mouse_event({
2791 move |_: &MouseUpEvent, phase, window, cx| {
2792 if let Some(drag) = &cx.active_drag
2793 && phase == DispatchPhase::Bubble
2794 && hitbox.is_hovered(window)
2795 {
2796 let drag_state_type = drag.value.as_ref().type_id();
2797 for (drop_state_type, listener) in &drop_listeners {
2798 if *drop_state_type == drag_state_type {
2799 let drag = cx
2800 .active_drag
2801 .take()
2802 .expect("checked for type drag state type above");
2803
2804 let mut can_drop = true;
2805 if let Some(predicate) = &can_drop_predicate {
2806 can_drop = predicate(drag.value.as_ref(), window, cx);
2807 }
2808
2809 if can_drop {
2810 listener(drag.value.as_ref(), window, cx);
2811 window.refresh();
2812 cx.stop_propagation();
2813 }
2814 }
2815 }
2816 }
2817 }
2818 });
2819 }
2820
2821 if let Some(element_state) = element_state {
2822 if !click_listeners.is_empty()
2823 || !aux_click_listeners.is_empty()
2824 || drag_listener.is_some()
2825 {
2826 let pending_mouse_down = element_state
2827 .pending_mouse_down
2828 .get_or_insert_with(Default::default)
2829 .clone();
2830
2831 let pending_keyboard_down = element_state
2832 .pending_keyboard_down
2833 .get_or_insert_with(Default::default)
2834 .clone();
2835
2836 let clicked_state = element_state
2837 .clicked_state
2838 .get_or_insert_with(Default::default)
2839 .clone();
2840
2841 window.on_mouse_event({
2842 let pending_mouse_down = pending_mouse_down.clone();
2843 let hitbox = hitbox.clone();
2844 let has_aux_click_listeners = !aux_click_listeners.is_empty();
2845 move |event: &MouseDownEvent, phase, window, _cx| {
2846 if phase == DispatchPhase::Bubble
2847 && (event.button == MouseButton::Left || has_aux_click_listeners)
2848 && hitbox.is_hovered(window)
2849 {
2850 *pending_mouse_down.borrow_mut() = Some(event.clone());
2851 window.refresh();
2852 }
2853 }
2854 });
2855
2856 window.on_mouse_event({
2857 let pending_mouse_down = pending_mouse_down.clone();
2858 let hitbox = hitbox.clone();
2859 move |event: &MouseMoveEvent, phase, window, cx| {
2860 if phase == DispatchPhase::Capture {
2861 return;
2862 }
2863
2864 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2865 if let Some(mouse_down) = pending_mouse_down.clone()
2866 && !cx.has_active_drag()
2867 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2868 && let Some(listener) = drag_listener.take()
2869 && mouse_down.button == MouseButton::Left
2870 {
2871 *clicked_state.borrow_mut() = ElementClickedState::default();
2872 let cursor_offset = event.position - hitbox.origin;
2873 let drag = (listener.render)(
2874 listener.value.as_ref(),
2875 cursor_offset,
2876 window,
2877 cx,
2878 );
2879 let external_payload_source =
2880 listener.external_payload.map(|external_payload| {
2881 let value = listener.value.clone();
2882 Box::new(move |window: &mut Window, cx: &mut App| {
2883 external_payload(value.as_ref(), window, cx)
2884 })
2885 as ExternalDragPayloadSource
2886 });
2887 cx.active_drag = Some(AnyDrag {
2888 view: drag,
2889 value: listener.value,
2890 cursor_offset,
2891 cursor_style: drag_cursor_style,
2892 external_payload_source,
2893 });
2894 pending_mouse_down.take();
2895 window.refresh();
2896 cx.stop_propagation();
2897 }
2898 }
2899 });
2900
2901 if is_focused {
2902 window.on_key_event({
2912 let pending_keyboard_down = pending_keyboard_down.clone();
2913 move |event: &KeyDownEvent, phase, window, _cx| {
2914 if phase.bubble() && !window.default_prevented() {
2915 let stroke = &event.keystroke;
2916 let is_activation_key = (stroke.key.eq("enter")
2917 || stroke.key.eq("space"))
2918 && !stroke.modifiers.modified();
2919 *pending_keyboard_down.borrow_mut() =
2920 is_activation_key.then_some(window.focus_generation);
2921 }
2922 }
2923 });
2924
2925 window.on_key_event({
2927 let click_listeners = click_listeners.clone();
2928 let hitbox = hitbox.clone();
2929 move |event: &KeyUpEvent, phase, window, cx| {
2930 if phase.bubble() && !window.default_prevented() {
2931 let stroke = &event.keystroke;
2932 let keyboard_button = if stroke.key.eq("enter") {
2933 Some(KeyboardButton::Enter)
2934 } else if stroke.key.eq("space") {
2935 Some(KeyboardButton::Space)
2936 } else {
2937 None
2938 };
2939
2940 if let Some(button) = keyboard_button
2941 && !stroke.modifiers.modified()
2942 {
2943 let pending =
2944 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
2945 if pending != Some(window.focus_generation) {
2946 return;
2947 }
2948
2949 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2950 button,
2951 bounds: hitbox.bounds,
2952 });
2953
2954 for listener in &click_listeners {
2955 listener(&click_event, window, cx);
2956 }
2957 } else {
2958 *pending_keyboard_down.borrow_mut() = None;
2962 }
2963 }
2964 }
2965 });
2966 }
2967
2968 window.on_mouse_event({
2969 let mut captured_mouse_down = None;
2970 let hitbox = hitbox.clone();
2971 move |event: &MouseUpEvent, phase, window, cx| match phase {
2972 DispatchPhase::Capture => {
2976 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2977 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2978 captured_mouse_down = pending_mouse_down.take();
2979 window.refresh();
2980 } else if pending_mouse_down.is_some() {
2981 pending_mouse_down.take();
2987 window.refresh();
2988 }
2989 }
2990 DispatchPhase::Bubble => {
2992 if let Some(mouse_down) = captured_mouse_down.take() {
2993 let btn = mouse_down.button;
2994
2995 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2996 down: mouse_down,
2997 up: event.clone(),
2998 });
2999
3000 match btn {
3001 MouseButton::Left => {
3002 for listener in &click_listeners {
3003 listener(&mouse_click, window, cx);
3004 }
3005 }
3006 _ => {
3007 for listener in &aux_click_listeners {
3008 listener(&mouse_click, window, cx);
3009 }
3010 }
3011 }
3012 }
3013 }
3014 }
3015 });
3016 }
3017
3018 if let Some(hover_listener) = self.hover_listener.take() {
3019 let was_hovered = element_state
3020 .hover_listener_state
3021 .get_or_insert_with(Default::default)
3022 .clone();
3023 let has_mouse_down = element_state
3024 .pending_mouse_down
3025 .get_or_insert_with(Default::default)
3026 .clone();
3027 let hover_listener = Rc::new(hover_listener);
3028 let hover_listener_state = was_hovered.clone();
3029 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3030 let mut was_hovered = hover_listener_state.borrow_mut();
3031 if is_hovered != *was_hovered {
3032 *was_hovered = is_hovered;
3033 drop(was_hovered);
3034 hover_listener(&is_hovered, window, cx);
3035 }
3036 };
3037
3038 if has_mouse_down.borrow().is_none() {
3039 let is_hovered = !cx.has_active_drag() && hitbox.is_hovered(window);
3040 if is_hovered != *was_hovered.borrow() {
3041 let update_hover = update_hover.clone();
3042 window.defer(cx, move |window, cx| {
3043 update_hover(is_hovered, window, cx);
3044 });
3045 }
3046 }
3047
3048 window.on_mouse_event({
3049 let update_hover = update_hover.clone();
3050 let hitbox = hitbox.clone();
3051 move |_: &MouseMoveEvent, phase, window, cx| {
3052 if phase == DispatchPhase::Bubble {
3053 let is_hovered = has_mouse_down.borrow().is_none()
3054 && !cx.has_active_drag()
3055 && hitbox.is_hovered(window);
3056 update_hover(is_hovered, window, cx);
3057 }
3058 }
3059 });
3060
3061 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3064 if phase == DispatchPhase::Bubble {
3065 update_hover(false, window, cx);
3066 }
3067 });
3068 }
3069
3070 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3071 let active_tooltip = element_state
3072 .active_tooltip
3073 .get_or_insert_with(Default::default)
3074 .clone();
3075 let pending_mouse_down = element_state
3076 .pending_mouse_down
3077 .get_or_insert_with(Default::default)
3078 .clone();
3079
3080 let tooltip_is_hoverable = tooltip_builder.hoverable;
3081 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3082 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3083 });
3084 let check_is_hovered_during_prepaint = Rc::new({
3086 let pending_mouse_down = pending_mouse_down.clone();
3087 let source_bounds = hitbox.bounds;
3088 move |window: &Window| {
3089 !window.last_input_was_keyboard()
3090 && pending_mouse_down.borrow().is_none()
3091 && source_bounds.contains(&window.mouse_position())
3092 }
3093 });
3094 let check_is_hovered = Rc::new({
3095 let hitbox = hitbox.clone();
3096 move |window: &Window| {
3097 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3098 }
3099 });
3100 register_tooltip_mouse_handlers(
3101 &active_tooltip,
3102 self.tooltip_id,
3103 build_tooltip,
3104 check_is_hovered,
3105 check_is_hovered_during_prepaint,
3106 self.tooltip_show_delay,
3107 window,
3108 );
3109 }
3110
3111 let active_state = element_state
3114 .clicked_state
3115 .get_or_insert_with(Default::default)
3116 .clone();
3117
3118 {
3119 let active_state = active_state.clone();
3120 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3121 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3122 *active_state.borrow_mut() = ElementClickedState::default();
3123 window.refresh();
3124 }
3125 });
3126 }
3127
3128 {
3129 let active_group_hitbox = self
3130 .group_active_style
3131 .as_ref()
3132 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3133 let hitbox = hitbox.clone();
3134 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3135 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3136 let group_hovered = active_group_hitbox
3137 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3138 let element_hovered = hitbox.is_hovered(window);
3139 if group_hovered || element_hovered {
3140 *active_state.borrow_mut() = ElementClickedState {
3141 group: group_hovered,
3142 element: element_hovered,
3143 };
3144 window.refresh();
3145 }
3146 }
3147 });
3148 }
3149 }
3150 }
3151
3152 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3153 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3154 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3155 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3156 let action_listeners = mem::take(&mut self.action_listeners);
3157 if let Some(context) = self.key_context.clone() {
3158 window.set_key_context(context);
3159 }
3160
3161 for listener in key_down_listeners {
3162 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3163 listener(event, phase, window, cx);
3164 })
3165 }
3166
3167 for listener in key_up_listeners {
3168 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3169 listener(event, phase, window, cx);
3170 })
3171 }
3172
3173 for listener in modifiers_changed_listeners {
3174 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3175 listener(event, window, cx);
3176 })
3177 }
3178
3179 for (action_type, listener) in action_listeners {
3180 window.on_action(action_type, listener)
3181 }
3182 }
3183
3184 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3185 let group_hitbox = self
3186 .group_hover_style
3187 .as_ref()
3188 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3189
3190 if let Some(group_hitbox) = group_hitbox {
3191 let was_hovered = group_hitbox.is_hovered(window);
3192 let current_view = window.current_view();
3193 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3194 let hovered = group_hitbox.is_hovered(window);
3195 if phase == DispatchPhase::Capture && hovered != was_hovered {
3196 cx.notify(current_view);
3197 }
3198 });
3199 }
3200 }
3201
3202 fn paint_scroll_listener(
3203 &self,
3204 hitbox: &Hitbox,
3205 style: &Style,
3206 window: &mut Window,
3207 _cx: &mut App,
3208 ) {
3209 if let Some(scroll_offset) = self.scroll_offset.clone() {
3210 let ongoing_scroll = self.ongoing_scroll.clone();
3211 let overflow = style.overflow;
3212 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3213 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3214 let line_height = window.line_height();
3215 let hitbox = hitbox.clone();
3216 let current_view = window.current_view();
3217 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
3218 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3219 let mut scroll_offset = scroll_offset.borrow_mut();
3220 let old_scroll_offset = *scroll_offset;
3221 let mut delta = event.delta.pixel_delta(line_height);
3222
3223 if restrict_scroll_to_axis
3224 && event.delta.precise()
3225 && let Some(ongoing_scroll) = &ongoing_scroll
3226 {
3227 ongoing_scroll
3228 .borrow_mut()
3229 .filter(&mut delta, event.touch_phase);
3230 }
3231
3232 let mut delta_x = match overflow.x {
3233 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3234 Overflow::Scroll
3235 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3236 {
3237 delta.y
3238 }
3239 _ => Pixels::ZERO,
3240 };
3241 let mut delta_y = match overflow.y {
3242 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3243 Overflow::Scroll
3244 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3245 {
3246 delta.x
3247 }
3248 _ => Pixels::ZERO,
3249 };
3250 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3251 if delta_x.abs() > delta_y.abs() {
3252 delta_y = Pixels::ZERO;
3253 } else {
3254 delta_x = Pixels::ZERO;
3255 }
3256 }
3257 scroll_offset.y += delta_y;
3258 scroll_offset.x += delta_x;
3259 if *scroll_offset != old_scroll_offset {
3260 cx.notify(current_view);
3261 }
3262 }
3263 });
3264 }
3265 }
3266
3267 pub fn compute_style(
3269 &self,
3270 global_id: Option<&GlobalElementId>,
3271 hitbox: Option<&Hitbox>,
3272 window: &mut Window,
3273 cx: &mut App,
3274 ) -> Style {
3275 window.with_optional_element_state(global_id, |element_state, window| {
3276 let mut element_state =
3277 element_state.map(|element_state| element_state.unwrap_or_default());
3278 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3279 (style, element_state)
3280 })
3281 }
3282
3283 fn compute_style_internal(
3285 &self,
3286 hitbox: Option<&Hitbox>,
3287 element_state: Option<&mut InteractiveElementState>,
3288 window: &mut Window,
3289 cx: &mut App,
3290 ) -> Style {
3291 let mut style = Style::default();
3292 style.refine(&self.base_style);
3293
3294 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3295 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3296 && focus_handle.within_focused(window, cx)
3297 {
3298 style.refine(in_focus_style);
3299 }
3300
3301 if let Some(focus_style) = self.focus_style.as_ref()
3302 && focus_handle.is_focused(window)
3303 {
3304 style.refine(focus_style);
3305 }
3306
3307 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3308 && focus_handle.is_focused(window)
3309 && window.last_input_was_keyboard()
3310 {
3311 style.refine(focus_visible_style);
3312 }
3313 }
3314
3315 if !cx.has_active_drag() {
3316 if let Some(group_hover) = self.group_hover_style.as_ref() {
3317 let is_group_hovered =
3318 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3319 !window.last_input_was_touch() && group_hitbox_id.is_hovered(window)
3320 } else if let Some(element_state) = element_state.as_ref() {
3321 !window.last_input_was_touch()
3322 && element_state
3323 .hover_state
3324 .as_ref()
3325 .map(|state| state.borrow().group)
3326 .unwrap_or(false)
3327 } else {
3328 false
3329 };
3330
3331 if is_group_hovered {
3332 style.refine(&group_hover.style);
3333 }
3334 }
3335
3336 if let Some(hover_style) = self.hover_style.as_ref() {
3337 let is_hovered = if let Some(hitbox) = hitbox {
3338 !window.last_input_was_touch() && hitbox.is_hovered(window)
3339 } else if let Some(element_state) = element_state.as_ref() {
3340 !window.last_input_was_touch()
3341 && element_state
3342 .hover_state
3343 .as_ref()
3344 .map(|state| state.borrow().element)
3345 .unwrap_or(false)
3346 } else {
3347 false
3348 };
3349
3350 if is_hovered {
3351 style.refine(hover_style);
3352 }
3353 }
3354 }
3355
3356 if let Some(hitbox) = hitbox {
3357 if let Some(drag) = cx.active_drag.take() {
3358 let mut can_drop = true;
3359 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3360 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3361 }
3362
3363 if can_drop {
3364 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3365 if let Some(group_hitbox_id) =
3366 GroupHitboxes::get(&group_drag_style.group, cx)
3367 && *state_type == drag.value.as_ref().type_id()
3368 && group_hitbox_id.is_hovered(window)
3369 {
3370 style.refine(&group_drag_style.style);
3371 }
3372 }
3373
3374 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3375 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3376 {
3377 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3378 }
3379 }
3380 }
3381
3382 style.mouse_cursor = drag.cursor_style;
3383 cx.active_drag = Some(drag);
3384 }
3385 }
3386
3387 if let Some(element_state) = element_state {
3388 let clicked_state = element_state
3389 .clicked_state
3390 .get_or_insert_with(Default::default)
3391 .borrow();
3392 if clicked_state.group
3393 && let Some(group) = self.group_active_style.as_ref()
3394 {
3395 style.refine(&group.style)
3396 }
3397
3398 if let Some(active_style) = self.active_style.as_ref()
3399 && clicked_state.element
3400 {
3401 style.refine(active_style)
3402 }
3403 }
3404
3405 style
3406 }
3407
3408 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3409 if let Some(id) = &self.aria.author_id {
3410 node.set_author_id(id.to_string());
3411 }
3412 if let Some(label) = &self.aria.label {
3413 node.set_label(label.to_string());
3414 }
3415 if let Some(description) = &self.aria.description {
3416 node.set_description(description.to_string());
3417 }
3418 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3419 node.set_keyboard_shortcut(keyshortcuts.to_string());
3420 }
3421 if let Some(selected) = self.aria.selected {
3422 node.set_selected(selected);
3423 }
3424 if let Some(expanded) = self.aria.expanded {
3425 node.set_expanded(expanded);
3426 }
3427 if let Some(toggled) = self.aria.toggled {
3428 node.set_toggled(toggled);
3429 }
3430 if let Some(value) = self.aria.numeric_value {
3431 node.set_numeric_value(value);
3432 }
3433 if let Some(value) = self.aria.min_numeric_value {
3434 node.set_min_numeric_value(value);
3435 }
3436 if let Some(value) = self.aria.max_numeric_value {
3437 node.set_max_numeric_value(value);
3438 }
3439 if let Some(step) = self.aria.numeric_value_step {
3440 node.set_numeric_value_step(step);
3441 }
3442 if let Some(value) = &self.aria.value {
3443 node.set_value(value.to_string());
3444 }
3445 if let Some(placeholder) = &self.aria.placeholder {
3446 node.set_placeholder(placeholder.to_string());
3447 }
3448 if let Some(orientation) = self.aria.orientation {
3449 node.set_orientation(orientation);
3450 }
3451 if let Some(level) = self.aria.level {
3452 node.set_level(level);
3453 }
3454 if let Some(position) = self.aria.position_in_set {
3455 node.set_position_in_set(position);
3456 }
3457 if let Some(size) = self.aria.size_of_set {
3458 node.set_size_of_set(size);
3459 }
3460 if let Some(index) = self.aria.row_index {
3461 node.set_row_index(index);
3462 }
3463 if let Some(index) = self.aria.column_index {
3464 node.set_column_index(index);
3465 }
3466 if let Some(count) = self.aria.row_count {
3467 node.set_row_count(count);
3468 }
3469 if let Some(count) = self.aria.column_count {
3470 node.set_column_count(count);
3471 }
3472 if !self.click_listeners.is_empty() {
3473 node.add_action(accesskit::Action::Click);
3474 }
3475 if self.tracked_focus_handle.is_some() || self.focusable {
3476 node.add_action(accesskit::Action::Focus);
3477 }
3478 for (action, _) in &self.a11y_action_listeners {
3479 node.add_action(*action);
3480 }
3481 }
3482}
3483
3484#[derive(Default)]
3487pub struct InteractiveElementState {
3488 pub(crate) focus_handle: Option<FocusHandle>,
3489 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3490 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3491 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3492 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3493 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3501 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3502 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3503 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3504}
3505
3506#[derive(Copy, Clone, Default, Eq, PartialEq)]
3508pub struct ElementClickedState {
3509 pub group: bool,
3511
3512 pub element: bool,
3514}
3515
3516impl ElementClickedState {
3517 fn is_clicked(&self) -> bool {
3518 self.group || self.element
3519 }
3520}
3521
3522#[derive(Copy, Clone, Default, Eq, PartialEq)]
3524pub struct ElementHoverState {
3525 pub group: bool,
3527
3528 pub element: bool,
3530}
3531
3532pub(crate) enum ActiveTooltip {
3533 WaitingForShow { _task: Task<()> },
3535 Visible {
3537 tooltip: AnyTooltip,
3538 is_hoverable: bool,
3539 },
3540 WaitingForHide {
3543 tooltip: AnyTooltip,
3544 _task: Task<()>,
3545 },
3546}
3547
3548pub(crate) fn clear_active_tooltip(
3549 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3550 window: &mut Window,
3551) {
3552 match active_tooltip.borrow_mut().take() {
3553 None => {}
3554 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3555 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3556 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3557 }
3558}
3559
3560pub(crate) fn clear_active_tooltip_if_not_hoverable(
3561 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3562 window: &mut Window,
3563) {
3564 let should_clear = match active_tooltip.borrow().as_ref() {
3565 None => false,
3566 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3567 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3568 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3569 };
3570 if should_clear {
3571 active_tooltip.borrow_mut().take();
3572 window.refresh();
3573 }
3574}
3575
3576pub(crate) fn set_tooltip_on_window(
3577 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3578 window: &mut Window,
3579) -> Option<TooltipId> {
3580 let tooltip = match active_tooltip.borrow().as_ref() {
3581 None => return None,
3582 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3583 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3584 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3585 };
3586 Some(window.set_tooltip(tooltip))
3587}
3588
3589pub(crate) fn register_tooltip_mouse_handlers(
3590 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3591 tooltip_id: Option<TooltipId>,
3592 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3593 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3594 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3595 show_delay: Option<Duration>,
3596 window: &mut Window,
3597) {
3598 let current_view = window.current_view();
3599 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3600
3601 window.on_mouse_event({
3602 let active_tooltip = active_tooltip.clone();
3603 let build_tooltip = build_tooltip.clone();
3604 let check_is_hovered = check_is_hovered.clone();
3605 move |_: &MouseMoveEvent, phase, window, cx| {
3606 handle_tooltip_mouse_move(
3607 &active_tooltip,
3608 &build_tooltip,
3609 &check_is_hovered,
3610 &check_is_hovered_during_prepaint,
3611 tooltip_id,
3612 current_view,
3613 phase,
3614 show_delay,
3615 window,
3616 cx,
3617 )
3618 }
3619 });
3620
3621 window.on_mouse_event({
3622 let active_tooltip = active_tooltip.clone();
3623 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3624 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3625 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3626 }
3627 }
3628 });
3629
3630 window.on_mouse_event({
3631 let active_tooltip = active_tooltip.clone();
3632 move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
3633 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3634 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3635 }
3636 }
3637 });
3638}
3639
3640fn handle_tooltip_mouse_move(
3652 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3653 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3654 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3655 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3656 tooltip_id: Option<TooltipId>,
3657 current_view: EntityId,
3658 phase: DispatchPhase,
3659 show_delay: Duration,
3660 window: &mut Window,
3661 cx: &mut App,
3662) {
3663 enum Action {
3666 None,
3667 CancelShow,
3668 ScheduleShow,
3669 CheckVisible,
3670 }
3671
3672 let action = match active_tooltip.borrow().as_ref() {
3673 None => {
3674 let is_hovered = check_is_hovered(window);
3675 if is_hovered && phase.bubble() {
3676 Action::ScheduleShow
3677 } else {
3678 Action::None
3679 }
3680 }
3681 Some(ActiveTooltip::WaitingForShow { .. }) => {
3682 let is_hovered = check_is_hovered(window);
3683 if is_hovered {
3684 Action::None
3685 } else {
3686 Action::CancelShow
3687 }
3688 }
3689 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3690 if phase.capture()
3691 && !check_is_hovered(window)
3692 && (!*is_hoverable
3693 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3694 {
3695 Action::CheckVisible
3696 } else {
3697 Action::None
3698 }
3699 }
3700 Some(ActiveTooltip::WaitingForHide { .. }) => {
3701 if phase.capture()
3702 && (check_is_hovered(window)
3703 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3704 {
3705 Action::CheckVisible
3706 } else {
3707 Action::None
3708 }
3709 }
3710 };
3711
3712 match action {
3713 Action::None => {}
3714 Action::CancelShow => {
3715 active_tooltip.borrow_mut().take();
3717 }
3718 Action::ScheduleShow => {
3719 let delayed_show_task = window.spawn(cx, {
3720 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3721 let build_tooltip = build_tooltip.clone();
3722 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3723 async move |cx| {
3724 cx.background_executor().timer(show_delay).await;
3725 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3726 return;
3727 };
3728 cx.update(|window, cx| {
3729 let new_tooltip =
3730 build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3731 let weak_active_tooltip = Rc::downgrade(&active_tooltip);
3732 ActiveTooltip::Visible {
3733 tooltip: AnyTooltip {
3734 view,
3735 mouse_position: window.mouse_position(),
3736 check_visible_and_update: Rc::new(
3737 move |tooltip_bounds, window, cx| {
3738 let Some(active_tooltip) =
3739 weak_active_tooltip.upgrade()
3740 else {
3741 return false;
3742 };
3743 handle_tooltip_check_visible_and_update(
3744 &active_tooltip,
3745 tooltip_is_hoverable,
3746 &check_is_hovered_during_prepaint,
3747 tooltip_bounds,
3748 window,
3749 cx,
3750 )
3751 },
3752 ),
3753 },
3754 is_hoverable: tooltip_is_hoverable,
3755 }
3756 });
3757 *active_tooltip.borrow_mut() = new_tooltip;
3758 window.refresh();
3759 })
3760 .ok();
3761 }
3762 });
3763 active_tooltip
3764 .borrow_mut()
3765 .replace(ActiveTooltip::WaitingForShow {
3766 _task: delayed_show_task,
3767 });
3768 }
3769 Action::CheckVisible => cx.notify(current_view),
3770 }
3771}
3772
3773fn handle_tooltip_check_visible_and_update(
3777 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3778 tooltip_is_hoverable: bool,
3779 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3780 tooltip_bounds: Bounds<Pixels>,
3781 window: &mut Window,
3782 cx: &mut App,
3783) -> bool {
3784 enum Action {
3787 None,
3788 Hide,
3789 ScheduleHide(AnyTooltip),
3790 CancelHide(AnyTooltip),
3791 }
3792
3793 let is_hovered = check_is_hovered(window)
3794 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
3795 let action = match active_tooltip.borrow().as_ref() {
3796 Some(ActiveTooltip::Visible { tooltip, .. }) => {
3797 if is_hovered {
3798 Action::None
3799 } else {
3800 if tooltip_is_hoverable {
3801 Action::ScheduleHide(tooltip.clone())
3802 } else {
3803 Action::Hide
3804 }
3805 }
3806 }
3807 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
3808 if is_hovered {
3809 Action::CancelHide(tooltip.clone())
3810 } else {
3811 Action::None
3812 }
3813 }
3814 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
3815 };
3816
3817 match action {
3818 Action::None => {}
3819 Action::Hide => clear_active_tooltip(active_tooltip, window),
3820 Action::ScheduleHide(tooltip) => {
3821 let delayed_hide_task = window.spawn(cx, {
3822 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3823 async move |cx| {
3824 cx.background_executor()
3825 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
3826 .await;
3827 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3828 return;
3829 };
3830 if active_tooltip.borrow_mut().take().is_some() {
3831 cx.update(|window, _cx| window.refresh()).ok();
3832 }
3833 }
3834 });
3835 active_tooltip
3836 .borrow_mut()
3837 .replace(ActiveTooltip::WaitingForHide {
3838 tooltip,
3839 _task: delayed_hide_task,
3840 });
3841 }
3842 Action::CancelHide(tooltip) => {
3843 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
3845 tooltip,
3846 is_hoverable: true,
3847 });
3848 }
3849 }
3850
3851 active_tooltip.borrow().is_some()
3852}
3853
3854#[derive(Default)]
3855pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
3856
3857impl Global for GroupHitboxes {}
3858
3859impl GroupHitboxes {
3860 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
3861 cx.default_global::<Self>()
3862 .0
3863 .get(name)
3864 .and_then(|bounds_stack| bounds_stack.last())
3865 .cloned()
3866 }
3867
3868 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
3869 cx.default_global::<Self>()
3870 .0
3871 .entry(name)
3872 .or_default()
3873 .push(hitbox_id);
3874 }
3875
3876 pub fn pop(name: &SharedString, cx: &mut App) {
3877 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
3878 }
3879}
3880
3881pub struct Stateful<E> {
3883 pub(crate) element: E,
3884}
3885
3886impl<E> Styled for Stateful<E>
3887where
3888 E: Styled,
3889{
3890 fn style(&mut self) -> &mut StyleRefinement {
3891 self.element.style()
3892 }
3893}
3894
3895impl<E> StatefulInteractiveElement for Stateful<E>
3896where
3897 E: Element,
3898 Self: InteractiveElement,
3899{
3900}
3901
3902impl<E> InteractiveElement for Stateful<E>
3903where
3904 E: InteractiveElement,
3905{
3906 fn interactivity(&mut self) -> &mut Interactivity {
3907 self.element.interactivity()
3908 }
3909}
3910
3911impl<E> Element for Stateful<E>
3912where
3913 E: Element,
3914{
3915 type RequestLayoutState = E::RequestLayoutState;
3916 type PrepaintState = E::PrepaintState;
3917
3918 fn id(&self) -> Option<ElementId> {
3919 self.element.id()
3920 }
3921
3922 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3923 self.element.source_location()
3924 }
3925
3926 fn a11y_role(&self) -> Option<accesskit::Role> {
3927 self.element.a11y_role()
3928 }
3929
3930 fn write_a11y_info(&self, node: &mut accesskit::Node) {
3931 self.element.write_a11y_info(node);
3932 }
3933
3934 fn a11y_synthetic_children(
3935 &mut self,
3936 prepaint: &mut Self::PrepaintState,
3937 builder: &mut crate::A11ySubtreeBuilder,
3938 ) {
3939 self.element.a11y_synthetic_children(prepaint, builder);
3940 }
3941
3942 fn request_layout(
3943 &mut self,
3944 id: Option<&GlobalElementId>,
3945 inspector_id: Option<&InspectorElementId>,
3946 window: &mut Window,
3947 cx: &mut App,
3948 ) -> (LayoutId, Self::RequestLayoutState) {
3949 self.element.request_layout(id, inspector_id, window, cx)
3950 }
3951
3952 fn prepaint(
3953 &mut self,
3954 id: Option<&GlobalElementId>,
3955 inspector_id: Option<&InspectorElementId>,
3956 bounds: Bounds<Pixels>,
3957 state: &mut Self::RequestLayoutState,
3958 window: &mut Window,
3959 cx: &mut App,
3960 ) -> E::PrepaintState {
3961 self.element
3962 .prepaint(id, inspector_id, bounds, state, window, cx)
3963 }
3964
3965 fn paint(
3966 &mut self,
3967 id: Option<&GlobalElementId>,
3968 inspector_id: Option<&InspectorElementId>,
3969 bounds: Bounds<Pixels>,
3970 request_layout: &mut Self::RequestLayoutState,
3971 prepaint: &mut Self::PrepaintState,
3972 window: &mut Window,
3973 cx: &mut App,
3974 ) {
3975 self.element.paint(
3976 id,
3977 inspector_id,
3978 bounds,
3979 request_layout,
3980 prepaint,
3981 window,
3982 cx,
3983 );
3984 }
3985}
3986
3987impl<E> IntoElement for Stateful<E>
3988where
3989 E: Element,
3990{
3991 type Element = Self;
3992
3993 fn into_element(self) -> Self::Element {
3994 self
3995 }
3996}
3997
3998impl<E> ParentElement for Stateful<E>
3999where
4000 E: ParentElement,
4001{
4002 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4003 self.element.extend(elements)
4004 }
4005}
4006
4007#[derive(Clone)]
4010pub struct ScrollAnchor {
4011 handle: ScrollHandle,
4012 last_origin: Rc<RefCell<Point<Pixels>>>,
4013}
4014
4015impl ScrollAnchor {
4016 pub fn for_handle(handle: ScrollHandle) -> Self {
4018 Self {
4019 handle,
4020 last_origin: Default::default(),
4021 }
4022 }
4023 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4025 let this = self.clone();
4026
4027 window.on_next_frame(move |_, _| {
4028 let viewport_bounds = this.handle.bounds();
4029 let self_bounds = *this.last_origin.borrow();
4030 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4031 });
4032 }
4033}
4034
4035#[derive(Default, Debug)]
4036struct ScrollHandleState {
4037 offset: Rc<RefCell<Point<Pixels>>>,
4038 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4039 bounds: Bounds<Pixels>,
4040 max_offset: Point<Pixels>,
4041 child_bounds: Vec<Bounds<Pixels>>,
4042 scroll_to_bottom: bool,
4043 overflow: Point<Overflow>,
4044 active_item: Option<ScrollActiveItem>,
4045}
4046
4047#[derive(Default, Debug, Clone, Copy)]
4048struct ScrollActiveItem {
4049 index: usize,
4050 strategy: ScrollStrategy,
4051}
4052
4053#[derive(Default, Debug, Clone, Copy)]
4054enum ScrollStrategy {
4055 #[default]
4056 FirstVisible,
4057 Top,
4058}
4059
4060#[derive(Clone, Debug)]
4064pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4065
4066impl Default for ScrollHandle {
4067 fn default() -> Self {
4068 Self::new()
4069 }
4070}
4071
4072impl ScrollHandle {
4073 pub fn new() -> Self {
4075 Self(Rc::default())
4076 }
4077
4078 pub fn offset(&self) -> Point<Pixels> {
4080 *self.0.borrow().offset.borrow()
4081 }
4082
4083 pub fn max_offset(&self) -> Point<Pixels> {
4085 self.0.borrow().max_offset
4086 }
4087
4088 pub fn top_item(&self) -> usize {
4090 let state = self.0.borrow();
4091 let top = state.bounds.top() - state.offset.borrow().y;
4092
4093 match state.child_bounds.binary_search_by(|bounds| {
4094 if top < bounds.top() {
4095 Ordering::Greater
4096 } else if top > bounds.bottom() {
4097 Ordering::Less
4098 } else {
4099 Ordering::Equal
4100 }
4101 }) {
4102 Ok(ix) => ix,
4103 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4104 }
4105 }
4106
4107 pub fn bottom_item(&self) -> usize {
4109 let state = self.0.borrow();
4110 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4111
4112 match state.child_bounds.binary_search_by(|bounds| {
4113 if bottom < bounds.top() {
4114 Ordering::Greater
4115 } else if bottom > bounds.bottom() {
4116 Ordering::Less
4117 } else {
4118 Ordering::Equal
4119 }
4120 }) {
4121 Ok(ix) => ix,
4122 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4123 }
4124 }
4125
4126 pub fn bounds(&self) -> Bounds<Pixels> {
4128 self.0.borrow().bounds
4129 }
4130
4131 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4133 self.0.borrow().child_bounds.get(ix).cloned()
4134 }
4135
4136 pub fn scroll_to_item(&self, ix: usize) {
4138 let mut state = self.0.borrow_mut();
4139 state.active_item = Some(ScrollActiveItem {
4140 index: ix,
4141 strategy: ScrollStrategy::default(),
4142 });
4143 }
4144
4145 pub fn scroll_to_top_of_item(&self, ix: usize) {
4148 let mut state = self.0.borrow_mut();
4149 state.active_item = Some(ScrollActiveItem {
4150 index: ix,
4151 strategy: ScrollStrategy::Top,
4152 });
4153 }
4154
4155 fn scroll_to_active_item(&self) {
4159 let mut state = self.0.borrow_mut();
4160
4161 let Some(active_item) = state.active_item else {
4162 return;
4163 };
4164
4165 let active_item = match state.child_bounds.get(active_item.index) {
4166 Some(bounds) => {
4167 let mut scroll_offset = state.offset.borrow_mut();
4168
4169 match active_item.strategy {
4170 ScrollStrategy::FirstVisible => {
4171 if state.overflow.y == Overflow::Scroll {
4172 let child_height = bounds.size.height;
4173 let viewport_height = state.bounds.size.height;
4174 if child_height > viewport_height {
4175 scroll_offset.y = state.bounds.top() - bounds.top();
4176 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4177 scroll_offset.y = state.bounds.top() - bounds.top();
4178 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4179 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4180 }
4181 }
4182 }
4183 ScrollStrategy::Top => {
4184 scroll_offset.y = state.bounds.top() - bounds.top();
4185 }
4186 }
4187
4188 if state.overflow.x == Overflow::Scroll {
4189 let child_width = bounds.size.width;
4190 let viewport_width = state.bounds.size.width;
4191 if child_width > viewport_width {
4192 scroll_offset.x = state.bounds.left() - bounds.left();
4193 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4194 scroll_offset.x = state.bounds.left() - bounds.left();
4195 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4196 scroll_offset.x = state.bounds.right() - bounds.right();
4197 }
4198 }
4199 None
4200 }
4201 None => Some(active_item),
4202 };
4203 state.active_item = active_item;
4204 }
4205
4206 pub fn scroll_to_bottom(&self) {
4208 let mut state = self.0.borrow_mut();
4209 state.scroll_to_bottom = true;
4210 }
4211
4212 pub fn set_offset(&self, mut position: Point<Pixels>) {
4216 let state = self.0.borrow();
4217 *state.offset.borrow_mut() = position;
4218 }
4219
4220 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4222 let ix = self.top_item();
4223 let state = self.0.borrow();
4224
4225 if let Some(child_bounds) = state.child_bounds.get(ix) {
4226 (
4227 ix,
4228 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4229 )
4230 } else {
4231 (ix, px(0.))
4232 }
4233 }
4234
4235 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4237 let ix = self.bottom_item();
4238 let state = self.0.borrow();
4239
4240 if let Some(child_bounds) = state.child_bounds.get(ix) {
4241 (
4242 ix,
4243 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4244 )
4245 } else {
4246 (ix, px(0.))
4247 }
4248 }
4249
4250 pub fn children_count(&self) -> usize {
4252 self.0.borrow().child_bounds.len()
4253 }
4254}
4255
4256#[cfg(test)]
4257mod tests {
4258 use super::*;
4259 use crate::{
4260 AnyWindowHandle, AppContext as _, Context, InputEvent, Keystroke, MouseMoveEvent,
4261 TestAppContext, canvas, util::FluentBuilder as _,
4262 };
4263 use std::{cell::Cell, rc::Weak};
4264
4265 struct GroupHoverTestView {
4266 render_count: Rc<Cell<usize>>,
4267 anonymous_paint_count: Rc<Cell<usize>>,
4268 stateful_width: Rc<Cell<Pixels>>,
4269 }
4270
4271 impl Render for GroupHoverTestView {
4272 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4273 self.render_count.set(self.render_count.get() + 1);
4274 let anonymous_paint_count = self.anonymous_paint_count.clone();
4275 let stateful_width = self.stateful_width.clone();
4276 div().size_full().child(
4277 div()
4278 .ml(px(20.))
4279 .mt(px(20.))
4280 .size(px(50.))
4281 .relative()
4282 .group("hover-group")
4283 .child(
4284 div()
4285 .absolute()
4286 .size_full()
4287 .invisible()
4288 .group_hover("hover-group", |style| style.visible())
4289 .child(canvas(
4290 |_, _, _| {},
4291 move |_, _, _, _| {
4292 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4293 },
4294 )),
4295 )
4296 .child(
4297 div()
4298 .id("stateful-group-hover-target")
4299 .absolute()
4300 .top_0()
4301 .left_0()
4302 .size(px(10.))
4303 .group_hover("hover-group", |style| style.size(px(20.)))
4304 .child(canvas(
4305 move |bounds, _, _| stateful_width.set(bounds.size.width),
4306 |_, _, _, _| {},
4307 )),
4308 ),
4309 )
4310 }
4311 }
4312
4313 #[gpui::test]
4314 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4315 let render_count = Rc::new(Cell::new(0));
4316 let anonymous_paint_count = Rc::new(Cell::new(0));
4317 let stateful_width = Rc::new(Cell::new(px(0.)));
4318 let window = cx.add_window({
4319 let render_count = render_count.clone();
4320 let anonymous_paint_count = anonymous_paint_count.clone();
4321 let stateful_width = stateful_width.clone();
4322 move |_, _| GroupHoverTestView {
4323 render_count,
4324 anonymous_paint_count,
4325 stateful_width,
4326 }
4327 });
4328 let window = AnyWindowHandle::from(window);
4329
4330 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4331 .unwrap();
4332 assert_eq!(anonymous_paint_count.get(), 0);
4333 assert_eq!(stateful_width.get(), px(10.));
4334
4335 let move_mouse = |cx: &mut TestAppContext, position| {
4336 cx.update_window(window, |_, window, cx| {
4337 window.simulate_mouse_move(position, cx)
4338 })
4339 .unwrap();
4340 };
4341
4342 let initial_render_count = render_count.get();
4343 move_mouse(cx, point(px(25.), px(25.)));
4344 assert_eq!(render_count.get(), initial_render_count + 1);
4345 assert_eq!(anonymous_paint_count.get(), 1);
4346 assert_eq!(stateful_width.get(), px(20.));
4347
4348 move_mouse(cx, point(px(30.), px(30.)));
4349 assert_eq!(render_count.get(), initial_render_count + 1);
4350 assert_eq!(anonymous_paint_count.get(), 1);
4351 assert_eq!(stateful_width.get(), px(20.));
4352
4353 move_mouse(cx, point(px(5.), px(5.)));
4354 assert_eq!(render_count.get(), initial_render_count + 2);
4355 assert_eq!(anonymous_paint_count.get(), 1);
4356 assert_eq!(stateful_width.get(), px(10.));
4357
4358 move_mouse(cx, point(px(10.), px(10.)));
4359 assert_eq!(render_count.get(), initial_render_count + 2);
4360 assert_eq!(anonymous_paint_count.get(), 1);
4361 assert_eq!(stateful_width.get(), px(10.));
4362 }
4363
4364 struct HoverListenerLayoutTestView {
4365 target_left: Pixels,
4366 hover_transitions: Rc<RefCell<Vec<bool>>>,
4367 }
4368
4369 impl Render for HoverListenerLayoutTestView {
4370 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4371 let hover_transitions = self.hover_transitions.clone();
4372 div().relative().size_full().child(
4373 div()
4374 .id("hover-target")
4375 .absolute()
4376 .left(self.target_left)
4377 .top_0()
4378 .size(px(20.))
4379 .on_click(|_, _, _| {})
4380 .on_hover(move |is_hovered, _, _| {
4381 hover_transitions.borrow_mut().push(*is_hovered);
4382 }),
4383 )
4384 }
4385 }
4386
4387 #[gpui::test]
4388 fn hover_listeners_update_when_layout_changes_under_stationary_mouse(cx: &mut TestAppContext) {
4389 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4390 let window = cx.add_window({
4391 let hover_transitions = hover_transitions.clone();
4392 move |_, _| HoverListenerLayoutTestView {
4393 target_left: px(40.),
4394 hover_transitions,
4395 }
4396 });
4397 let any_window = AnyWindowHandle::from(window);
4398
4399 cx.update_window(any_window, |_, window, cx| {
4400 window.draw(cx).clear(cx);
4401 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4402 })
4403 .unwrap();
4404 assert!(hover_transitions.borrow().is_empty());
4405
4406 window
4407 .update(cx, |view, _, cx| {
4408 view.target_left = px(0.);
4409 cx.notify();
4410 })
4411 .unwrap();
4412 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4413 .unwrap();
4414 assert_eq!(*hover_transitions.borrow(), [true]);
4415
4416 window
4417 .update(cx, |view, _, cx| {
4418 view.target_left = px(40.);
4419 cx.notify();
4420 })
4421 .unwrap();
4422 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4423 .unwrap();
4424 assert_eq!(*hover_transitions.borrow(), [true, false]);
4425 }
4426
4427 #[gpui::test]
4428 fn hover_listeners_remain_hovered_during_stationary_mouse_press(cx: &mut TestAppContext) {
4429 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4430 let window = cx.add_window({
4431 let hover_transitions = hover_transitions.clone();
4432 move |_, _| HoverListenerLayoutTestView {
4433 target_left: px(0.),
4434 hover_transitions,
4435 }
4436 });
4437 let any_window = AnyWindowHandle::from(window);
4438 let mouse_position = point(px(10.), px(10.));
4439
4440 cx.update_window(any_window, |_, window, cx| {
4441 window.draw(cx).clear(cx);
4442 window.simulate_mouse_move(mouse_position, cx);
4443 })
4444 .unwrap();
4445 assert_eq!(*hover_transitions.borrow(), [true]);
4446
4447 cx.update_window(any_window, |_, window, cx| {
4448 window.dispatch_event(
4449 MouseDownEvent {
4450 position: mouse_position,
4451 button: MouseButton::Left,
4452 modifiers: Default::default(),
4453 click_count: 1,
4454 first_mouse: false,
4455 }
4456 .to_platform_input(),
4457 cx,
4458 );
4459 window.draw(cx).clear(cx);
4460 })
4461 .unwrap();
4462 assert_eq!(*hover_transitions.borrow(), [true]);
4463
4464 cx.update_window(any_window, |_, window, cx| {
4465 window.dispatch_event(
4466 MouseUpEvent {
4467 position: mouse_position,
4468 button: MouseButton::Left,
4469 modifiers: Default::default(),
4470 click_count: 1,
4471 }
4472 .to_platform_input(),
4473 cx,
4474 );
4475 window.draw(cx).clear(cx);
4476 })
4477 .unwrap();
4478 assert_eq!(*hover_transitions.borrow(), [true]);
4479 }
4480
4481 struct TestTooltipView;
4482
4483 impl Render for TestTooltipView {
4484 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4485 div().w(px(20.)).h(px(20.)).child("tooltip")
4486 }
4487 }
4488
4489 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4490
4491 struct TooltipCaptureElement {
4492 child: AnyElement,
4493 captured_active_tooltip: CapturedActiveTooltip,
4494 }
4495
4496 impl IntoElement for TooltipCaptureElement {
4497 type Element = Self;
4498
4499 fn into_element(self) -> Self::Element {
4500 self
4501 }
4502 }
4503
4504 impl Element for TooltipCaptureElement {
4505 type RequestLayoutState = ();
4506 type PrepaintState = ();
4507
4508 fn id(&self) -> Option<ElementId> {
4509 None
4510 }
4511
4512 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4513 None
4514 }
4515
4516 fn request_layout(
4517 &mut self,
4518 _id: Option<&GlobalElementId>,
4519 _inspector_id: Option<&InspectorElementId>,
4520 window: &mut Window,
4521 cx: &mut App,
4522 ) -> (LayoutId, Self::RequestLayoutState) {
4523 (self.child.request_layout(window, cx), ())
4524 }
4525
4526 fn prepaint(
4527 &mut self,
4528 _id: Option<&GlobalElementId>,
4529 _inspector_id: Option<&InspectorElementId>,
4530 _bounds: Bounds<Pixels>,
4531 _request_layout: &mut Self::RequestLayoutState,
4532 window: &mut Window,
4533 cx: &mut App,
4534 ) -> Self::PrepaintState {
4535 self.child.prepaint(window, cx);
4536 }
4537
4538 fn paint(
4539 &mut self,
4540 _id: Option<&GlobalElementId>,
4541 _inspector_id: Option<&InspectorElementId>,
4542 _bounds: Bounds<Pixels>,
4543 _request_layout: &mut Self::RequestLayoutState,
4544 _prepaint: &mut Self::PrepaintState,
4545 window: &mut Window,
4546 cx: &mut App,
4547 ) {
4548 self.child.paint(window, cx);
4549 window.with_global_id("target".into(), |global_id, window| {
4550 window.with_element_state::<InteractiveElementState, _>(
4551 global_id,
4552 |state, _window| {
4553 let state = state.unwrap();
4554 *self.captured_active_tooltip.borrow_mut() =
4555 state.active_tooltip.as_ref().map(Rc::downgrade);
4556 ((), state)
4557 },
4558 )
4559 });
4560 }
4561 }
4562
4563 struct TooltipOwner {
4564 captured_active_tooltip: CapturedActiveTooltip,
4565 show_delay_override: Option<Duration>,
4566 }
4567
4568 impl Render for TooltipOwner {
4569 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4570 TooltipCaptureElement {
4571 child: div()
4572 .size_full()
4573 .child(
4574 div()
4575 .id("target")
4576 .w(px(50.))
4577 .h(px(50.))
4578 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4579 .when_some(self.show_delay_override, |this, delay| {
4580 this.tooltip_show_delay(delay)
4581 }),
4582 )
4583 .into_any_element(),
4584 captured_active_tooltip: self.captured_active_tooltip.clone(),
4585 }
4586 }
4587 }
4588
4589 #[test]
4590 fn scroll_handle_aligns_wide_children_to_left_edge() {
4591 let handle = ScrollHandle::new();
4592 {
4593 let mut state = handle.0.borrow_mut();
4594 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4595 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4596 state.overflow.x = Overflow::Scroll;
4597 state.active_item = Some(ScrollActiveItem {
4598 index: 0,
4599 strategy: ScrollStrategy::default(),
4600 });
4601 }
4602
4603 handle.scroll_to_active_item();
4604
4605 assert_eq!(handle.offset().x, px(-25.));
4606 }
4607
4608 #[test]
4609 fn scroll_handle_aligns_tall_children_to_top_edge() {
4610 let handle = ScrollHandle::new();
4611 {
4612 let mut state = handle.0.borrow_mut();
4613 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4614 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4615 state.overflow.y = Overflow::Scroll;
4616 state.active_item = Some(ScrollActiveItem {
4617 index: 0,
4618 strategy: ScrollStrategy::default(),
4619 });
4620 }
4621
4622 handle.scroll_to_active_item();
4623
4624 assert_eq!(handle.offset().y, px(-25.));
4625 }
4626
4627 fn setup_tooltip_owner_test(
4628 show_delay_override: Option<Duration>,
4629 ) -> (
4630 TestAppContext,
4631 crate::AnyWindowHandle,
4632 CapturedActiveTooltip,
4633 ) {
4634 let mut test_app = TestAppContext::single();
4635 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
4636 let window = test_app.add_window({
4637 let captured_active_tooltip = captured_active_tooltip.clone();
4638 move |_, _| TooltipOwner {
4639 captured_active_tooltip,
4640 show_delay_override,
4641 }
4642 });
4643 let any_window = window.into();
4644
4645 test_app
4646 .update_window(any_window, |_, window, cx| {
4647 window.draw(cx).clear(cx);
4648 })
4649 .unwrap();
4650
4651 test_app
4652 .update_window(any_window, |_, window, cx| {
4653 window.dispatch_event(
4654 MouseMoveEvent {
4655 position: point(px(10.), px(10.)),
4656 modifiers: Default::default(),
4657 pressed_button: None,
4658 }
4659 .to_platform_input(),
4660 cx,
4661 );
4662 })
4663 .unwrap();
4664
4665 test_app
4666 .update_window(any_window, |_, window, cx| {
4667 window.draw(cx).clear(cx);
4668 })
4669 .unwrap();
4670
4671 (test_app, any_window, captured_active_tooltip)
4672 }
4673
4674 #[test]
4675 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
4676 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4677
4678 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4679 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4680 assert!(matches!(
4681 active_tooltip.borrow().as_ref(),
4682 Some(ActiveTooltip::WaitingForShow { .. })
4683 ));
4684
4685 test_app
4686 .update_window(any_window, |_, window, _| {
4687 window.remove_window();
4688 })
4689 .unwrap();
4690 test_app.run_until_parked();
4691 drop(active_tooltip);
4692
4693 assert!(weak_active_tooltip.upgrade().is_none());
4694 }
4695
4696 #[test]
4697 fn tooltip_respects_custom_show_delay() {
4698 let extra_delay = Duration::from_secs(1);
4699 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
4700 let (mut test_app, _any_window, captured_active_tooltip) =
4701 setup_tooltip_owner_test(Some(show_delay_override));
4702
4703 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4704 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4705
4706 test_app
4707 .dispatcher
4708 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4709 test_app.run_until_parked();
4710
4711 assert!(matches!(
4712 active_tooltip.borrow().as_ref(),
4713 Some(ActiveTooltip::WaitingForShow { .. })
4714 ));
4715
4716 test_app.dispatcher.advance_clock(extra_delay);
4717 test_app.run_until_parked();
4718
4719 assert!(matches!(
4720 active_tooltip.borrow().as_ref(),
4721 Some(ActiveTooltip::Visible { .. })
4722 ));
4723 }
4724
4725 #[test]
4726 fn tooltip_is_released_when_its_owner_disappears() {
4727 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4728
4729 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4730 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4731
4732 test_app
4733 .dispatcher
4734 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4735 test_app.run_until_parked();
4736
4737 assert!(matches!(
4738 active_tooltip.borrow().as_ref(),
4739 Some(ActiveTooltip::Visible { .. })
4740 ));
4741
4742 test_app
4743 .update_window(any_window, |_, window, _| {
4744 window.remove_window();
4745 })
4746 .unwrap();
4747 test_app.run_until_parked();
4748 drop(active_tooltip);
4749
4750 assert!(weak_active_tooltip.upgrade().is_none());
4751 }
4752
4753 #[test]
4754 fn tooltip_hides_after_mouse_leaves_origin() {
4755 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4756
4757 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4758 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4759
4760 test_app
4761 .dispatcher
4762 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4763 test_app.run_until_parked();
4764
4765 assert!(matches!(
4766 active_tooltip.borrow().as_ref(),
4767 Some(ActiveTooltip::Visible { .. })
4768 ));
4769
4770 test_app
4771 .update_window(any_window, |_, window, cx| {
4772 window.dispatch_event(
4773 MouseMoveEvent {
4774 position: point(px(75.), px(75.)),
4775 modifiers: Default::default(),
4776 pressed_button: None,
4777 }
4778 .to_platform_input(),
4779 cx,
4780 );
4781 })
4782 .unwrap();
4783
4784 assert!(active_tooltip.borrow().is_none());
4785 }
4786
4787 struct MouseDownOutOwner {
4788 mouse_down_out_count: Rc<RefCell<usize>>,
4789 }
4790
4791 impl Render for MouseDownOutOwner {
4792 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4793 let mouse_down_out_count = self.mouse_down_out_count.clone();
4794 div()
4795 .size_full()
4796 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
4797 move |_, _, _| {
4798 *mouse_down_out_count.borrow_mut() += 1;
4799 },
4800 ))
4801 }
4802 }
4803
4804 #[test]
4805 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
4806 let mut test_app = TestAppContext::single();
4807 let mouse_down_out_count = Rc::new(RefCell::new(0));
4808 let window = test_app.add_window({
4809 let mouse_down_out_count = mouse_down_out_count.clone();
4810 move |_, _| MouseDownOutOwner {
4811 mouse_down_out_count,
4812 }
4813 });
4814 let any_window: AnyWindowHandle = window.into();
4815
4816 fn dispatch_mouse_down_outside_target(
4817 test_app: &mut TestAppContext,
4818 any_window: AnyWindowHandle,
4819 ) {
4820 test_app
4821 .update_window(any_window, |_, window, cx| {
4822 window.dispatch_event(
4823 MouseDownEvent {
4824 position: point(px(75.), px(75.)),
4825 button: MouseButton::Left,
4826 modifiers: Default::default(),
4827 click_count: 1,
4828 first_mouse: false,
4829 }
4830 .to_platform_input(),
4831 cx,
4832 );
4833 })
4834 .unwrap();
4835 }
4836
4837 test_app
4838 .update_window(any_window, |_, window, cx| {
4839 window.draw(cx).clear(cx);
4840 })
4841 .unwrap();
4842
4843 dispatch_mouse_down_outside_target(&mut test_app, any_window);
4844 assert_eq!(
4845 *mouse_down_out_count.borrow(),
4846 1,
4847 "mouse down outside the element should fire mouse-down-out listeners"
4848 );
4849
4850 test_app
4851 .update_window(any_window, |_, window, cx| {
4852 cx.set_prompt_builder(crate::fallback_prompt_renderer);
4853 let _receiver =
4854 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
4855 assert!(window.has_active_prompt());
4856 window.draw(cx).clear(cx);
4857 })
4858 .unwrap();
4859
4860 dispatch_mouse_down_outside_target(&mut test_app, any_window);
4861 assert_eq!(
4862 *mouse_down_out_count.borrow(),
4863 1,
4864 "mouse down over an active prompt should not fire mouse-down-out listeners"
4865 );
4866 }
4867
4868 #[test]
4869 fn test_accessibility_id_builder_writes_author_id() {
4870 let mut element = div()
4871 .id("buffer-font-size")
4872 .accessibility_id("settings.buffer-font-size");
4873 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
4874
4875 element.interactivity().write_a11y_info(&mut node);
4876
4877 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
4878 }
4879
4880 #[test]
4881 fn test_write_a11y_info_string_and_numeric_properties() {
4882 let mut interactivity = Interactivity::default();
4883 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
4884 interactivity.aria.label = Some("Buffer Font Size".into());
4885 interactivity.aria.value = Some("15".into());
4886 interactivity.aria.placeholder = Some("Search".into());
4887 interactivity.aria.numeric_value = Some(15.0);
4888 interactivity.aria.min_numeric_value = Some(6.0);
4889 interactivity.aria.max_numeric_value = Some(72.0);
4890 interactivity.aria.numeric_value_step = Some(1.0);
4891
4892 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
4893 interactivity.write_a11y_info(&mut node);
4894
4895 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
4896 assert_eq!(node.label(), Some("Buffer Font Size"));
4897 assert_eq!(node.value(), Some("15"));
4898 assert_eq!(node.placeholder(), Some("Search"));
4899 assert_eq!(node.numeric_value(), Some(15.0));
4900 assert_eq!(node.min_numeric_value(), Some(6.0));
4901 assert_eq!(node.max_numeric_value(), Some(72.0));
4902 assert_eq!(node.numeric_value_step(), Some(1.0));
4903 }
4904
4905 struct KeyboardActivationTest {
4908 focus_a: FocusHandle,
4909 focus_b: FocusHandle,
4910 clicks: Rc<RefCell<Vec<&'static str>>>,
4911 }
4912
4913 impl Render for KeyboardActivationTest {
4914 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4915 let clicks_a = self.clicks.clone();
4916 let clicks_b = self.clicks.clone();
4917 div()
4918 .size_full()
4919 .child(
4920 div()
4921 .id("a")
4922 .w(px(50.))
4923 .h(px(50.))
4924 .track_focus(&self.focus_a)
4925 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
4926 )
4927 .child(
4928 div()
4929 .id("b")
4930 .w(px(50.))
4931 .h(px(50.))
4932 .track_focus(&self.focus_b)
4933 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
4934 )
4935 }
4936 }
4937
4938 fn setup_keyboard_activation_test() -> (
4939 TestAppContext,
4940 AnyWindowHandle,
4941 Rc<RefCell<Vec<&'static str>>>,
4942 FocusHandle,
4943 FocusHandle,
4944 ) {
4945 let mut cx = TestAppContext::single();
4946 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
4947 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
4948 let window = cx.add_window({
4949 let focus_a = focus_a.clone();
4950 let focus_b = focus_b.clone();
4951 let clicks = clicks.clone();
4952 move |_, _| KeyboardActivationTest {
4953 focus_a,
4954 focus_b,
4955 clicks,
4956 }
4957 });
4958 (cx, window.into(), clicks, focus_a, focus_b)
4959 }
4960
4961 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
4964 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
4965 .unwrap();
4966 cx.run_until_parked();
4967 cx.update_window(window, |_, window, cx| {
4968 window.draw(cx).clear(cx);
4969 })
4970 .unwrap();
4971 }
4972
4973 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4974 let keystroke = Keystroke::parse(key).unwrap();
4975 cx.update_window(window, |_, window, cx| {
4976 window.dispatch_event(
4977 KeyDownEvent {
4978 keystroke,
4979 is_held: false,
4980 prefer_character_input: false,
4981 }
4982 .to_platform_input(),
4983 cx,
4984 );
4985 })
4986 .unwrap();
4987 }
4988
4989 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4990 let keystroke = Keystroke::parse(key).unwrap();
4991 cx.update_window(window, |_, window, cx| {
4992 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
4993 })
4994 .unwrap();
4995 }
4996
4997 #[test]
4999 fn keyboard_activation_fires_click_on_same_element() {
5000 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5001
5002 focus_and_draw(&mut cx, window, &focus_a);
5003 key_down(&mut cx, window, "enter");
5004 key_up(&mut cx, window, "enter");
5005
5006 assert_eq!(*clicks.borrow(), vec!["a"]);
5007 }
5008
5009 #[test]
5014 fn keyboard_activation_does_not_leak_across_focus_change() {
5015 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5016
5017 focus_and_draw(&mut cx, window, &focus_a);
5019 key_down(&mut cx, window, "enter");
5020
5021 focus_and_draw(&mut cx, window, &focus_b);
5023 key_up(&mut cx, window, "enter");
5024
5025 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5028 }
5029
5030 #[test]
5035 fn keyboard_activation_does_not_leak_when_focus_returns() {
5036 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5037
5038 focus_and_draw(&mut cx, window, &focus_a);
5040 key_down(&mut cx, window, "enter");
5041
5042 focus_and_draw(&mut cx, window, &focus_b);
5045 focus_and_draw(&mut cx, window, &focus_a);
5046 key_up(&mut cx, window, "enter");
5047
5048 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5050 }
5051
5052 #[test]
5057 fn keyboard_activation_cleared_by_intervening_key_release() {
5058 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5059
5060 focus_and_draw(&mut cx, window, &focus_a);
5061 key_down(&mut cx, window, "escape");
5062 key_down(&mut cx, window, "space");
5063 key_up(&mut cx, window, "escape");
5064 key_up(&mut cx, window, "space");
5065
5066 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5067 }
5068
5069 #[test]
5073 fn keyboard_activation_does_not_distinguish_space_and_enter() {
5074 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5075
5076 focus_and_draw(&mut cx, window, &focus_a);
5077 key_down(&mut cx, window, "space");
5078 key_up(&mut cx, window, "enter");
5079
5080 assert_eq!(*clicks.borrow(), vec!["a"]);
5081 }
5082
5083 #[test]
5086 fn keyboard_activation_cleared_by_intervening_keydown() {
5087 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5088
5089 focus_and_draw(&mut cx, window, &focus_a);
5090 key_down(&mut cx, window, "enter");
5091 key_down(&mut cx, window, "a");
5092 key_up(&mut cx, window, "enter");
5093
5094 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5095 }
5096
5097 #[test]
5100 fn keyboard_activation_ignores_modified_keys() {
5101 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5102
5103 focus_and_draw(&mut cx, window, &focus_a);
5104 key_down(&mut cx, window, "cmd-enter");
5105 key_up(&mut cx, window, "cmd-enter");
5106
5107 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5108 }
5109
5110 struct TabGroupFocus {
5114 group_a: FocusHandle,
5115 item_a: FocusHandle,
5116 group_b: FocusHandle,
5117 item_b: FocusHandle,
5118 }
5119
5120 impl Render for TabGroupFocus {
5121 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5122 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
5123 div()
5124 .track_focus(container)
5125 .tab_group()
5126 .child(div().track_focus(item))
5127 }
5128 div()
5129 .child(group(&self.group_a, &self.item_a))
5130 .child(group(&self.group_b, &self.item_b))
5131 }
5132 }
5133
5134 #[test]
5138 fn focus_next_from_tab_group_container_enters_that_group() {
5139 let mut cx = TestAppContext::single();
5140 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
5141 (
5142 cx.focus_handle(),
5143 cx.focus_handle().tab_stop(true),
5144 cx.focus_handle(),
5145 cx.focus_handle().tab_stop(true),
5146 )
5147 });
5148 let window: AnyWindowHandle = cx
5149 .add_window({
5150 let (group_a, item_a, group_b, item_b) =
5151 (group_a, item_a, group_b.clone(), item_b.clone());
5152 move |_, _| TabGroupFocus {
5153 group_a,
5154 item_a,
5155 group_b,
5156 item_b,
5157 }
5158 })
5159 .into();
5160 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5161 .unwrap();
5162
5163 let focused = cx
5165 .update_window(window, |_, window, cx| {
5166 window.focus(&group_b, cx);
5167 window.focus_next(cx);
5168 window.focused(cx).map(|handle| handle.id)
5169 })
5170 .unwrap();
5171
5172 assert_eq!(focused, Some(item_b.id));
5173 }
5174
5175 #[gpui::test]
5176 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5177 cx: &mut TestAppContext,
5178 ) {
5179 struct PaddedContainer {
5180 scroll_handle: ScrollHandle,
5181 }
5182
5183 impl Render for PaddedContainer {
5184 fn render(
5185 &mut self,
5186 _window: &mut Window,
5187 _cx: &mut Context<Self>,
5188 ) -> impl IntoElement {
5189 div().size_full().child(
5192 div()
5193 .id("container")
5194 .h(px(50.))
5195 .w(px(100.))
5196 .py(px(4.25))
5197 .overflow_y_scroll()
5198 .track_scroll(&self.scroll_handle)
5199 .child(div().w_full().h(px(42.))),
5200 )
5201 }
5202 }
5203
5204 let scroll_handle = ScrollHandle::new();
5205 let window: AnyWindowHandle = cx
5206 .add_window({
5207 let scroll_handle = scroll_handle.clone();
5208 move |_, _| PaddedContainer { scroll_handle }
5209 })
5210 .into();
5211 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5212 .unwrap();
5213
5214 assert_eq!(scroll_handle.max_offset().y, px(0.));
5215 }
5216
5217 struct ContentSizedGrid;
5218
5219 impl Render for ContentSizedGrid {
5220 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5221 let widths = [px(100.), px(200.), px(50.)];
5222 div().size_full().child(
5223 div()
5224 .w_full()
5225 .grid()
5226 .grid_cols_max_content(widths.len() as u16)
5227 .children(widths.into_iter().enumerate().map(|(index, width)| {
5228 div()
5229 .debug_selector(move || format!("cell-{index}"))
5230 .w(width)
5231 .h(px(10.))
5232 })),
5233 )
5234 }
5235 }
5236
5237 #[gpui::test]
5238 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
5239 let window = cx.add_window(|_, _| ContentSizedGrid);
5240 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
5241 .unwrap();
5242
5243 let mut bounds = |selector: &'static str| {
5244 cx.update_window(window.into(), |_, window, _| {
5245 window.rendered_frame.debug_bounds.get(selector).copied()
5246 })
5247 .unwrap()
5248 .unwrap_or_else(|| panic!("{selector} was not rendered"))
5249 };
5250
5251 assert_eq!(bounds("cell-0").origin.x, px(0.));
5252 assert_eq!(bounds("cell-1").origin.x, px(100.));
5253 assert_eq!(bounds("cell-2").origin.x, px(300.));
5254 }
5255}