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.padding.to_pixels(bounds.size.into(), rem_size);
2350 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2351 let padded_content_size = self.content_size + padding_size;
2358 let scroll_max = Point::from(padded_content_size - bounds.size)
2359 .map(round_to_two_decimals)
2360 .max(&Default::default());
2361 let mut scroll_offset = scroll_offset.borrow_mut();
2364
2365 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2366 if scroll_to_bottom {
2367 scroll_offset.y = -scroll_max.y;
2368 } else {
2369 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2370 }
2371
2372 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2373 scroll_handle_state.max_offset = scroll_max;
2374 scroll_handle_state.bounds = bounds;
2375 }
2376
2377 *scroll_offset
2378 } else {
2379 Point::default()
2380 }
2381 }
2382
2383 pub fn paint(
2392 &mut self,
2393 global_id: Option<&GlobalElementId>,
2394 _inspector_id: Option<&InspectorElementId>,
2395 bounds: Bounds<Pixels>,
2396 hitbox: Option<&Hitbox>,
2397 window: &mut Window,
2398 cx: &mut App,
2399 f: impl FnOnce(&Style, &mut Window, &mut App),
2400 ) {
2401 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2402 window.with_optional_element_state::<InteractiveElementState, _>(
2403 global_id,
2404 |element_state, window| {
2405 let mut element_state =
2406 element_state.map(|element_state| element_state.unwrap_or_default());
2407
2408 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2409
2410 #[cfg(any(feature = "test-support", test))]
2411 if let Some(debug_selector) = &self.debug_selector {
2412 window
2413 .next_frame
2414 .debug_bounds
2415 .insert(debug_selector.clone(), bounds);
2416 }
2417
2418 self.paint_hover_group_handler(window, cx);
2419
2420 if style.visibility == Visibility::Hidden {
2421 return ((), element_state);
2422 }
2423
2424 let mut tab_group = None;
2425 if self.tab_group {
2426 tab_group = self.tab_index;
2427 }
2428
2429 window.with_element_opacity(style.opacity, |window| {
2430 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2431 window.with_text_style(style.text_style().cloned(), |window| {
2432 window.with_content_mask(
2433 style.overflow_mask(bounds, window.rem_size()),
2434 |window| {
2435 window.with_tab_group(tab_group, |window| {
2436 if let Some(focus_handle) = &self.tracked_focus_handle {
2445 window.next_frame.tab_stops.insert(focus_handle);
2446 }
2447 if let Some(hitbox) = hitbox {
2448 #[cfg(debug_assertions)]
2449 self.paint_debug_info(
2450 global_id, hitbox, &style, window, cx,
2451 );
2452
2453 if let Some(drag) = cx.active_drag.as_ref() {
2454 if let Some(mouse_cursor) = drag.cursor_style {
2455 window.set_window_cursor_style(mouse_cursor);
2456 }
2457 } else {
2458 if let Some(mouse_cursor) = style.mouse_cursor {
2459 window.set_cursor_style(mouse_cursor, hitbox);
2460 }
2461 }
2462
2463 if let Some(group) = self.group.clone() {
2464 GroupHitboxes::push(group, hitbox.id, cx);
2465 }
2466
2467 if let Some(area) = self.window_control {
2468 window.insert_window_control_hitbox(
2469 area,
2470 hitbox.clone(),
2471 );
2472 }
2473
2474 self.paint_mouse_listeners(
2475 hitbox,
2476 element_state.as_mut(),
2477 window,
2478 cx,
2479 );
2480 self.paint_scroll_listener(hitbox, &style, window, cx);
2481 }
2482
2483 self.paint_keyboard_listeners(window, cx);
2484
2485 if window.a11y.is_active() {
2486 if let Some(global_id) = global_id {
2487 if !self.a11y_action_listeners.is_empty() {
2488 let node_id = global_id.accesskit_node_id();
2489 for (action, listener) in
2490 self.a11y_action_listeners.drain(..)
2491 {
2492 window.on_a11y_action(
2493 node_id, action, listener,
2494 );
2495 }
2496 }
2497 }
2498 }
2499
2500 f(&style, window, cx);
2501
2502 if let Some(_hitbox) = hitbox {
2503 #[cfg(any(feature = "inspector", debug_assertions))]
2504 window.insert_inspector_hitbox(
2505 _hitbox.id,
2506 _inspector_id,
2507 cx,
2508 );
2509
2510 if let Some(group) = self.group.as_ref() {
2511 GroupHitboxes::pop(group, cx);
2512 }
2513 }
2514 })
2515 },
2516 );
2517 });
2518 });
2519 });
2520
2521 ((), element_state)
2522 },
2523 );
2524 }
2525
2526 #[cfg(debug_assertions)]
2527 fn paint_debug_info(
2528 &self,
2529 global_id: Option<&GlobalElementId>,
2530 hitbox: &Hitbox,
2531 style: &Style,
2532 window: &mut Window,
2533 cx: &mut App,
2534 ) {
2535 use crate::{BorderStyle, TextAlign};
2536
2537 if let Some(global_id) = global_id
2538 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2539 && hitbox.is_hovered(window)
2540 {
2541 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2542 let element_id = format!("{global_id:?}");
2543 let str_len = element_id.len();
2544
2545 let render_debug_text = |window: &mut Window| {
2546 if let Some(text) = window
2547 .text_system()
2548 .shape_text(
2549 element_id.into(),
2550 FONT_SIZE,
2551 &[window.text_style().to_run(str_len)],
2552 None,
2553 None,
2554 )
2555 .ok()
2556 .and_then(|mut text| text.pop())
2557 {
2558 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2559 .ok();
2560
2561 let text_bounds = crate::Bounds {
2562 origin: hitbox.origin,
2563 size: text.size(FONT_SIZE),
2564 };
2565 if let Some(source_location) = self.source_location
2566 && text_bounds.contains(&window.mouse_position())
2567 && window.modifiers().secondary()
2568 {
2569 let secondary_held = window.modifiers().secondary();
2570 window.on_key_event({
2571 move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2572 if e.modifiers.secondary() != secondary_held
2573 && text_bounds.contains(&window.mouse_position())
2574 {
2575 window.refresh();
2576 }
2577 }
2578 });
2579
2580 let was_hovered = hitbox.is_hovered(window);
2581 let current_view = window.current_view();
2582 window.on_mouse_event({
2583 let hitbox = hitbox.clone();
2584 move |_: &MouseMoveEvent, phase, window, cx| {
2585 if phase == DispatchPhase::Capture {
2586 let hovered = hitbox.is_hovered(window);
2587 if hovered != was_hovered {
2588 cx.notify(current_view)
2589 }
2590 }
2591 }
2592 });
2593
2594 window.on_mouse_event({
2595 let hitbox = hitbox.clone();
2596 move |e: &crate::MouseDownEvent, phase, window, cx| {
2597 if text_bounds.contains(&e.position)
2598 && phase.capture()
2599 && hitbox.is_hovered(window)
2600 {
2601 cx.stop_propagation();
2602 let Ok(dir) = std::env::current_dir() else {
2603 return;
2604 };
2605
2606 eprintln!(
2607 "This element was created at:\n{}:{}:{}",
2608 dir.join(source_location.file()).to_string_lossy(),
2609 source_location.line(),
2610 source_location.column()
2611 );
2612 }
2613 }
2614 });
2615 window.paint_quad(crate::outline(
2616 crate::Bounds {
2617 origin: hitbox.origin
2618 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2619 size: crate::Size {
2620 width: text_bounds.size.width,
2621 height: crate::px(1.),
2622 },
2623 },
2624 crate::red(),
2625 BorderStyle::default(),
2626 ))
2627 }
2628 }
2629 };
2630
2631 window.with_text_style(
2632 Some(crate::TextStyleRefinement {
2633 color: Some(crate::red()),
2634 line_height: Some(FONT_SIZE.into()),
2635 background_color: Some(crate::white()),
2636 ..Default::default()
2637 }),
2638 render_debug_text,
2639 )
2640 }
2641 }
2642
2643 fn paint_mouse_listeners(
2644 &mut self,
2645 hitbox: &Hitbox,
2646 element_state: Option<&mut InteractiveElementState>,
2647 window: &mut Window,
2648 cx: &mut App,
2649 ) {
2650 let is_focused = self
2651 .tracked_focus_handle
2652 .as_ref()
2653 .map(|handle| handle.is_focused(window))
2654 .unwrap_or(false);
2655
2656 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2660 let hitbox = hitbox.clone();
2661 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2662 if phase == DispatchPhase::Bubble
2663 && hitbox.is_hovered(window)
2664 && !window.default_prevented()
2665 {
2666 window.focus(&focus_handle, cx);
2667 window.prevent_default();
2670 }
2671 });
2672 }
2673
2674 for listener in self.mouse_down_listeners.drain(..) {
2675 let hitbox = hitbox.clone();
2676 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2677 listener(event, phase, &hitbox, window, cx);
2678 })
2679 }
2680
2681 for listener in self.mouse_up_listeners.drain(..) {
2682 let hitbox = hitbox.clone();
2683 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2684 listener(event, phase, &hitbox, window, cx);
2685 })
2686 }
2687
2688 for listener in self.mouse_pressure_listeners.drain(..) {
2689 let hitbox = hitbox.clone();
2690 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2691 listener(event, phase, &hitbox, window, cx);
2692 })
2693 }
2694
2695 for listener in self.mouse_move_listeners.drain(..) {
2696 let hitbox = hitbox.clone();
2697 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2698 listener(event, phase, &hitbox, window, cx);
2699 })
2700 }
2701
2702 for listener in self.mouse_exit_listeners.drain(..) {
2703 let hitbox = hitbox.clone();
2704 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2705 listener(event, phase, &hitbox, window, cx);
2706 })
2707 }
2708
2709 for listener in self.scroll_wheel_listeners.drain(..) {
2710 let hitbox = hitbox.clone();
2711 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2712 listener(event, phase, &hitbox, window, cx);
2713 })
2714 }
2715
2716 for listener in self.pinch_listeners.drain(..) {
2717 let hitbox = hitbox.clone();
2718 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2719 listener(event, phase, &hitbox, window, cx);
2720 })
2721 }
2722
2723 if self.hover_style.is_some()
2724 || self.base_style.mouse_cursor.is_some()
2725 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2726 {
2727 let hitbox = hitbox.clone();
2728 let hover_state = self.hover_style.as_ref().and_then(|_| {
2729 element_state
2730 .as_ref()
2731 .and_then(|state| state.hover_state.as_ref())
2732 .cloned()
2733 });
2734 let current_view = window.current_view();
2735
2736 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2737 let hovered = hitbox.is_hovered(window);
2738 let was_hovered = hover_state
2739 .as_ref()
2740 .is_some_and(|state| state.borrow().element);
2741 if phase == DispatchPhase::Capture && hovered != was_hovered {
2742 if let Some(hover_state) = &hover_state {
2743 hover_state.borrow_mut().element = hovered;
2744 cx.notify(current_view);
2745 }
2746 }
2747 });
2748 }
2749
2750 if let Some(group_hover) = self.group_hover_style.as_ref() {
2751 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2752 let hover_state = element_state
2753 .as_ref()
2754 .and_then(|element| element.hover_state.as_ref())
2755 .cloned();
2756 let current_view = window.current_view();
2757
2758 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2759 let group_hovered = group_hitbox_id.is_hovered(window);
2760 let was_group_hovered = hover_state
2761 .as_ref()
2762 .is_some_and(|state| state.borrow().group);
2763 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2764 if let Some(hover_state) = &hover_state {
2765 hover_state.borrow_mut().group = group_hovered;
2766 cx.notify(current_view);
2767 }
2768 }
2769 });
2770 }
2771 }
2772
2773 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2774
2775 let mut drag_listener = mem::take(&mut self.drag_listener);
2776 let drop_listeners = mem::take(&mut self.drop_listeners);
2777 let click_listeners = mem::take(&mut self.click_listeners);
2778 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2779 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2780
2781 if !drop_listeners.is_empty() {
2782 let hitbox = hitbox.clone();
2783 window.on_mouse_event({
2784 move |_: &MouseUpEvent, phase, window, cx| {
2785 if let Some(drag) = &cx.active_drag
2786 && phase == DispatchPhase::Bubble
2787 && hitbox.is_hovered(window)
2788 {
2789 let drag_state_type = drag.value.as_ref().type_id();
2790 for (drop_state_type, listener) in &drop_listeners {
2791 if *drop_state_type == drag_state_type {
2792 let drag = cx
2793 .active_drag
2794 .take()
2795 .expect("checked for type drag state type above");
2796
2797 let mut can_drop = true;
2798 if let Some(predicate) = &can_drop_predicate {
2799 can_drop = predicate(drag.value.as_ref(), window, cx);
2800 }
2801
2802 if can_drop {
2803 listener(drag.value.as_ref(), window, cx);
2804 window.refresh();
2805 cx.stop_propagation();
2806 }
2807 }
2808 }
2809 }
2810 }
2811 });
2812 }
2813
2814 if let Some(element_state) = element_state {
2815 if !click_listeners.is_empty()
2816 || !aux_click_listeners.is_empty()
2817 || drag_listener.is_some()
2818 {
2819 let pending_mouse_down = element_state
2820 .pending_mouse_down
2821 .get_or_insert_with(Default::default)
2822 .clone();
2823
2824 let pending_keyboard_down = element_state
2825 .pending_keyboard_down
2826 .get_or_insert_with(Default::default)
2827 .clone();
2828
2829 let clicked_state = element_state
2830 .clicked_state
2831 .get_or_insert_with(Default::default)
2832 .clone();
2833
2834 window.on_mouse_event({
2835 let pending_mouse_down = pending_mouse_down.clone();
2836 let hitbox = hitbox.clone();
2837 let has_aux_click_listeners = !aux_click_listeners.is_empty();
2838 move |event: &MouseDownEvent, phase, window, _cx| {
2839 if phase == DispatchPhase::Bubble
2840 && (event.button == MouseButton::Left || has_aux_click_listeners)
2841 && hitbox.is_hovered(window)
2842 {
2843 *pending_mouse_down.borrow_mut() = Some(event.clone());
2844 window.refresh();
2845 }
2846 }
2847 });
2848
2849 window.on_mouse_event({
2850 let pending_mouse_down = pending_mouse_down.clone();
2851 let hitbox = hitbox.clone();
2852 move |event: &MouseMoveEvent, phase, window, cx| {
2853 if phase == DispatchPhase::Capture {
2854 return;
2855 }
2856
2857 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2858 if let Some(mouse_down) = pending_mouse_down.clone()
2859 && !cx.has_active_drag()
2860 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2861 && let Some(listener) = drag_listener.take()
2862 && mouse_down.button == MouseButton::Left
2863 {
2864 *clicked_state.borrow_mut() = ElementClickedState::default();
2865 let cursor_offset = event.position - hitbox.origin;
2866 let drag = (listener.render)(
2867 listener.value.as_ref(),
2868 cursor_offset,
2869 window,
2870 cx,
2871 );
2872 let external_payload_source =
2873 listener.external_payload.map(|external_payload| {
2874 let value = listener.value.clone();
2875 Box::new(move |window: &mut Window, cx: &mut App| {
2876 external_payload(value.as_ref(), window, cx)
2877 })
2878 as ExternalDragPayloadSource
2879 });
2880 cx.active_drag = Some(AnyDrag {
2881 view: drag,
2882 value: listener.value,
2883 cursor_offset,
2884 cursor_style: drag_cursor_style,
2885 external_payload_source,
2886 });
2887 pending_mouse_down.take();
2888 window.refresh();
2889 cx.stop_propagation();
2890 }
2891 }
2892 });
2893
2894 if is_focused {
2895 window.on_key_event({
2905 let pending_keyboard_down = pending_keyboard_down.clone();
2906 move |event: &KeyDownEvent, phase, window, _cx| {
2907 if phase.bubble() && !window.default_prevented() {
2908 let stroke = &event.keystroke;
2909 let is_activation_key = (stroke.key.eq("enter")
2910 || stroke.key.eq("space"))
2911 && !stroke.modifiers.modified();
2912 *pending_keyboard_down.borrow_mut() =
2913 is_activation_key.then_some(window.focus_generation);
2914 }
2915 }
2916 });
2917
2918 window.on_key_event({
2920 let click_listeners = click_listeners.clone();
2921 let hitbox = hitbox.clone();
2922 move |event: &KeyUpEvent, phase, window, cx| {
2923 if phase.bubble() && !window.default_prevented() {
2924 let stroke = &event.keystroke;
2925 let keyboard_button = if stroke.key.eq("enter") {
2926 Some(KeyboardButton::Enter)
2927 } else if stroke.key.eq("space") {
2928 Some(KeyboardButton::Space)
2929 } else {
2930 None
2931 };
2932
2933 if let Some(button) = keyboard_button
2934 && !stroke.modifiers.modified()
2935 {
2936 let pending =
2937 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
2938 if pending != Some(window.focus_generation) {
2939 return;
2940 }
2941
2942 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2943 button,
2944 bounds: hitbox.bounds,
2945 });
2946
2947 for listener in &click_listeners {
2948 listener(&click_event, window, cx);
2949 }
2950 } else {
2951 *pending_keyboard_down.borrow_mut() = None;
2955 }
2956 }
2957 }
2958 });
2959 }
2960
2961 window.on_mouse_event({
2962 let mut captured_mouse_down = None;
2963 let hitbox = hitbox.clone();
2964 move |event: &MouseUpEvent, phase, window, cx| match phase {
2965 DispatchPhase::Capture => {
2969 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2970 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2971 captured_mouse_down = pending_mouse_down.take();
2972 window.refresh();
2973 } else if pending_mouse_down.is_some() {
2974 pending_mouse_down.take();
2980 window.refresh();
2981 }
2982 }
2983 DispatchPhase::Bubble => {
2985 if let Some(mouse_down) = captured_mouse_down.take() {
2986 let btn = mouse_down.button;
2987
2988 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2989 down: mouse_down,
2990 up: event.clone(),
2991 });
2992
2993 match btn {
2994 MouseButton::Left => {
2995 for listener in &click_listeners {
2996 listener(&mouse_click, window, cx);
2997 }
2998 }
2999 _ => {
3000 for listener in &aux_click_listeners {
3001 listener(&mouse_click, window, cx);
3002 }
3003 }
3004 }
3005 }
3006 }
3007 }
3008 });
3009 }
3010
3011 if let Some(hover_listener) = self.hover_listener.take() {
3012 let was_hovered = element_state
3013 .hover_listener_state
3014 .get_or_insert_with(Default::default)
3015 .clone();
3016 let has_mouse_down = element_state
3017 .pending_mouse_down
3018 .get_or_insert_with(Default::default)
3019 .clone();
3020 let hover_listener = Rc::new(hover_listener);
3021 let hover_listener_state = was_hovered.clone();
3022 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3023 let mut was_hovered = hover_listener_state.borrow_mut();
3024 if is_hovered != *was_hovered {
3025 *was_hovered = is_hovered;
3026 drop(was_hovered);
3027 hover_listener(&is_hovered, window, cx);
3028 }
3029 };
3030
3031 if has_mouse_down.borrow().is_none() {
3032 let is_hovered = !cx.has_active_drag() && hitbox.is_hovered(window);
3033 if is_hovered != *was_hovered.borrow() {
3034 let update_hover = update_hover.clone();
3035 window.defer(cx, move |window, cx| {
3036 update_hover(is_hovered, window, cx);
3037 });
3038 }
3039 }
3040
3041 window.on_mouse_event({
3042 let update_hover = update_hover.clone();
3043 let hitbox = hitbox.clone();
3044 move |_: &MouseMoveEvent, phase, window, cx| {
3045 if phase == DispatchPhase::Bubble {
3046 let is_hovered = has_mouse_down.borrow().is_none()
3047 && !cx.has_active_drag()
3048 && hitbox.is_hovered(window);
3049 update_hover(is_hovered, window, cx);
3050 }
3051 }
3052 });
3053
3054 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3057 if phase == DispatchPhase::Bubble {
3058 update_hover(false, window, cx);
3059 }
3060 });
3061 }
3062
3063 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3064 let active_tooltip = element_state
3065 .active_tooltip
3066 .get_or_insert_with(Default::default)
3067 .clone();
3068 let pending_mouse_down = element_state
3069 .pending_mouse_down
3070 .get_or_insert_with(Default::default)
3071 .clone();
3072
3073 let tooltip_is_hoverable = tooltip_builder.hoverable;
3074 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3075 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3076 });
3077 let check_is_hovered_during_prepaint = Rc::new({
3079 let pending_mouse_down = pending_mouse_down.clone();
3080 let source_bounds = hitbox.bounds;
3081 move |window: &Window| {
3082 !window.last_input_was_keyboard()
3083 && pending_mouse_down.borrow().is_none()
3084 && source_bounds.contains(&window.mouse_position())
3085 }
3086 });
3087 let check_is_hovered = Rc::new({
3088 let hitbox = hitbox.clone();
3089 move |window: &Window| {
3090 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3091 }
3092 });
3093 register_tooltip_mouse_handlers(
3094 &active_tooltip,
3095 self.tooltip_id,
3096 build_tooltip,
3097 check_is_hovered,
3098 check_is_hovered_during_prepaint,
3099 self.tooltip_show_delay,
3100 window,
3101 );
3102 }
3103
3104 let active_state = element_state
3107 .clicked_state
3108 .get_or_insert_with(Default::default)
3109 .clone();
3110
3111 {
3112 let active_state = active_state.clone();
3113 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3114 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3115 *active_state.borrow_mut() = ElementClickedState::default();
3116 window.refresh();
3117 }
3118 });
3119 }
3120
3121 {
3122 let active_group_hitbox = self
3123 .group_active_style
3124 .as_ref()
3125 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3126 let hitbox = hitbox.clone();
3127 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3128 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3129 let group_hovered = active_group_hitbox
3130 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3131 let element_hovered = hitbox.is_hovered(window);
3132 if group_hovered || element_hovered {
3133 *active_state.borrow_mut() = ElementClickedState {
3134 group: group_hovered,
3135 element: element_hovered,
3136 };
3137 window.refresh();
3138 }
3139 }
3140 });
3141 }
3142 }
3143 }
3144
3145 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3146 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3147 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3148 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3149 let action_listeners = mem::take(&mut self.action_listeners);
3150 if let Some(context) = self.key_context.clone() {
3151 window.set_key_context(context);
3152 }
3153
3154 for listener in key_down_listeners {
3155 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3156 listener(event, phase, window, cx);
3157 })
3158 }
3159
3160 for listener in key_up_listeners {
3161 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3162 listener(event, phase, window, cx);
3163 })
3164 }
3165
3166 for listener in modifiers_changed_listeners {
3167 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3168 listener(event, window, cx);
3169 })
3170 }
3171
3172 for (action_type, listener) in action_listeners {
3173 window.on_action(action_type, listener)
3174 }
3175 }
3176
3177 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3178 let group_hitbox = self
3179 .group_hover_style
3180 .as_ref()
3181 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3182
3183 if let Some(group_hitbox) = group_hitbox {
3184 let was_hovered = group_hitbox.is_hovered(window);
3185 let current_view = window.current_view();
3186 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3187 let hovered = group_hitbox.is_hovered(window);
3188 if phase == DispatchPhase::Capture && hovered != was_hovered {
3189 cx.notify(current_view);
3190 }
3191 });
3192 }
3193 }
3194
3195 fn paint_scroll_listener(
3196 &self,
3197 hitbox: &Hitbox,
3198 style: &Style,
3199 window: &mut Window,
3200 _cx: &mut App,
3201 ) {
3202 if let Some(scroll_offset) = self.scroll_offset.clone() {
3203 let ongoing_scroll = self.ongoing_scroll.clone();
3204 let overflow = style.overflow;
3205 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3206 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3207 let line_height = window.line_height();
3208 let hitbox = hitbox.clone();
3209 let current_view = window.current_view();
3210 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
3211 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3212 let mut scroll_offset = scroll_offset.borrow_mut();
3213 let old_scroll_offset = *scroll_offset;
3214 let mut delta = event.delta.pixel_delta(line_height);
3215
3216 if restrict_scroll_to_axis
3217 && event.delta.precise()
3218 && let Some(ongoing_scroll) = &ongoing_scroll
3219 {
3220 ongoing_scroll
3221 .borrow_mut()
3222 .filter(&mut delta, event.touch_phase);
3223 }
3224
3225 let mut delta_x = match overflow.x {
3226 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3227 Overflow::Scroll
3228 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3229 {
3230 delta.y
3231 }
3232 _ => Pixels::ZERO,
3233 };
3234 let mut delta_y = match overflow.y {
3235 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3236 Overflow::Scroll
3237 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3238 {
3239 delta.x
3240 }
3241 _ => Pixels::ZERO,
3242 };
3243 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3244 if delta_x.abs() > delta_y.abs() {
3245 delta_y = Pixels::ZERO;
3246 } else {
3247 delta_x = Pixels::ZERO;
3248 }
3249 }
3250 scroll_offset.y += delta_y;
3251 scroll_offset.x += delta_x;
3252 if *scroll_offset != old_scroll_offset {
3253 cx.notify(current_view);
3254 }
3255 }
3256 });
3257 }
3258 }
3259
3260 pub fn compute_style(
3262 &self,
3263 global_id: Option<&GlobalElementId>,
3264 hitbox: Option<&Hitbox>,
3265 window: &mut Window,
3266 cx: &mut App,
3267 ) -> Style {
3268 window.with_optional_element_state(global_id, |element_state, window| {
3269 let mut element_state =
3270 element_state.map(|element_state| element_state.unwrap_or_default());
3271 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3272 (style, element_state)
3273 })
3274 }
3275
3276 fn compute_style_internal(
3278 &self,
3279 hitbox: Option<&Hitbox>,
3280 element_state: Option<&mut InteractiveElementState>,
3281 window: &mut Window,
3282 cx: &mut App,
3283 ) -> Style {
3284 let mut style = Style::default();
3285 style.refine(&self.base_style);
3286
3287 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3288 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3289 && focus_handle.within_focused(window, cx)
3290 {
3291 style.refine(in_focus_style);
3292 }
3293
3294 if let Some(focus_style) = self.focus_style.as_ref()
3295 && focus_handle.is_focused(window)
3296 {
3297 style.refine(focus_style);
3298 }
3299
3300 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3301 && focus_handle.is_focused(window)
3302 && window.last_input_was_keyboard()
3303 {
3304 style.refine(focus_visible_style);
3305 }
3306 }
3307
3308 if !cx.has_active_drag() {
3309 if let Some(group_hover) = self.group_hover_style.as_ref() {
3310 let is_group_hovered =
3311 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3312 group_hitbox_id.is_hovered(window)
3313 } else if let Some(element_state) = element_state.as_ref() {
3314 element_state
3315 .hover_state
3316 .as_ref()
3317 .map(|state| state.borrow().group)
3318 .unwrap_or(false)
3319 } else {
3320 false
3321 };
3322
3323 if is_group_hovered {
3324 style.refine(&group_hover.style);
3325 }
3326 }
3327
3328 if let Some(hover_style) = self.hover_style.as_ref() {
3329 let is_hovered = if let Some(hitbox) = hitbox {
3330 hitbox.is_hovered(window)
3331 } else if let Some(element_state) = element_state.as_ref() {
3332 element_state
3333 .hover_state
3334 .as_ref()
3335 .map(|state| state.borrow().element)
3336 .unwrap_or(false)
3337 } else {
3338 false
3339 };
3340
3341 if is_hovered {
3342 style.refine(hover_style);
3343 }
3344 }
3345 }
3346
3347 if let Some(hitbox) = hitbox {
3348 if let Some(drag) = cx.active_drag.take() {
3349 let mut can_drop = true;
3350 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3351 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3352 }
3353
3354 if can_drop {
3355 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3356 if let Some(group_hitbox_id) =
3357 GroupHitboxes::get(&group_drag_style.group, cx)
3358 && *state_type == drag.value.as_ref().type_id()
3359 && group_hitbox_id.is_hovered(window)
3360 {
3361 style.refine(&group_drag_style.style);
3362 }
3363 }
3364
3365 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3366 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3367 {
3368 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3369 }
3370 }
3371 }
3372
3373 style.mouse_cursor = drag.cursor_style;
3374 cx.active_drag = Some(drag);
3375 }
3376 }
3377
3378 if let Some(element_state) = element_state {
3379 let clicked_state = element_state
3380 .clicked_state
3381 .get_or_insert_with(Default::default)
3382 .borrow();
3383 if clicked_state.group
3384 && let Some(group) = self.group_active_style.as_ref()
3385 {
3386 style.refine(&group.style)
3387 }
3388
3389 if let Some(active_style) = self.active_style.as_ref()
3390 && clicked_state.element
3391 {
3392 style.refine(active_style)
3393 }
3394 }
3395
3396 style
3397 }
3398
3399 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3400 if let Some(id) = &self.aria.author_id {
3401 node.set_author_id(id.to_string());
3402 }
3403 if let Some(label) = &self.aria.label {
3404 node.set_label(label.to_string());
3405 }
3406 if let Some(description) = &self.aria.description {
3407 node.set_description(description.to_string());
3408 }
3409 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3410 node.set_keyboard_shortcut(keyshortcuts.to_string());
3411 }
3412 if let Some(selected) = self.aria.selected {
3413 node.set_selected(selected);
3414 }
3415 if let Some(expanded) = self.aria.expanded {
3416 node.set_expanded(expanded);
3417 }
3418 if let Some(toggled) = self.aria.toggled {
3419 node.set_toggled(toggled);
3420 }
3421 if let Some(value) = self.aria.numeric_value {
3422 node.set_numeric_value(value);
3423 }
3424 if let Some(value) = self.aria.min_numeric_value {
3425 node.set_min_numeric_value(value);
3426 }
3427 if let Some(value) = self.aria.max_numeric_value {
3428 node.set_max_numeric_value(value);
3429 }
3430 if let Some(step) = self.aria.numeric_value_step {
3431 node.set_numeric_value_step(step);
3432 }
3433 if let Some(value) = &self.aria.value {
3434 node.set_value(value.to_string());
3435 }
3436 if let Some(placeholder) = &self.aria.placeholder {
3437 node.set_placeholder(placeholder.to_string());
3438 }
3439 if let Some(orientation) = self.aria.orientation {
3440 node.set_orientation(orientation);
3441 }
3442 if let Some(level) = self.aria.level {
3443 node.set_level(level);
3444 }
3445 if let Some(position) = self.aria.position_in_set {
3446 node.set_position_in_set(position);
3447 }
3448 if let Some(size) = self.aria.size_of_set {
3449 node.set_size_of_set(size);
3450 }
3451 if let Some(index) = self.aria.row_index {
3452 node.set_row_index(index);
3453 }
3454 if let Some(index) = self.aria.column_index {
3455 node.set_column_index(index);
3456 }
3457 if let Some(count) = self.aria.row_count {
3458 node.set_row_count(count);
3459 }
3460 if let Some(count) = self.aria.column_count {
3461 node.set_column_count(count);
3462 }
3463 if !self.click_listeners.is_empty() {
3464 node.add_action(accesskit::Action::Click);
3465 }
3466 if self.tracked_focus_handle.is_some() || self.focusable {
3467 node.add_action(accesskit::Action::Focus);
3468 }
3469 for (action, _) in &self.a11y_action_listeners {
3470 node.add_action(*action);
3471 }
3472 }
3473}
3474
3475#[derive(Default)]
3478pub struct InteractiveElementState {
3479 pub(crate) focus_handle: Option<FocusHandle>,
3480 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3481 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3482 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3483 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3484 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3492 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3493 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3494 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3495}
3496
3497#[derive(Copy, Clone, Default, Eq, PartialEq)]
3499pub struct ElementClickedState {
3500 pub group: bool,
3502
3503 pub element: bool,
3505}
3506
3507impl ElementClickedState {
3508 fn is_clicked(&self) -> bool {
3509 self.group || self.element
3510 }
3511}
3512
3513#[derive(Copy, Clone, Default, Eq, PartialEq)]
3515pub struct ElementHoverState {
3516 pub group: bool,
3518
3519 pub element: bool,
3521}
3522
3523pub(crate) enum ActiveTooltip {
3524 WaitingForShow { _task: Task<()> },
3526 Visible {
3528 tooltip: AnyTooltip,
3529 is_hoverable: bool,
3530 },
3531 WaitingForHide {
3534 tooltip: AnyTooltip,
3535 _task: Task<()>,
3536 },
3537}
3538
3539pub(crate) fn clear_active_tooltip(
3540 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3541 window: &mut Window,
3542) {
3543 match active_tooltip.borrow_mut().take() {
3544 None => {}
3545 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3546 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3547 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3548 }
3549}
3550
3551pub(crate) fn clear_active_tooltip_if_not_hoverable(
3552 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3553 window: &mut Window,
3554) {
3555 let should_clear = match active_tooltip.borrow().as_ref() {
3556 None => false,
3557 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3558 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3559 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3560 };
3561 if should_clear {
3562 active_tooltip.borrow_mut().take();
3563 window.refresh();
3564 }
3565}
3566
3567pub(crate) fn set_tooltip_on_window(
3568 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3569 window: &mut Window,
3570) -> Option<TooltipId> {
3571 let tooltip = match active_tooltip.borrow().as_ref() {
3572 None => return None,
3573 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3574 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3575 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3576 };
3577 Some(window.set_tooltip(tooltip))
3578}
3579
3580pub(crate) fn register_tooltip_mouse_handlers(
3581 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3582 tooltip_id: Option<TooltipId>,
3583 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3584 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3585 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3586 show_delay: Option<Duration>,
3587 window: &mut Window,
3588) {
3589 let current_view = window.current_view();
3590 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3591
3592 window.on_mouse_event({
3593 let active_tooltip = active_tooltip.clone();
3594 let build_tooltip = build_tooltip.clone();
3595 let check_is_hovered = check_is_hovered.clone();
3596 move |_: &MouseMoveEvent, phase, window, cx| {
3597 handle_tooltip_mouse_move(
3598 &active_tooltip,
3599 &build_tooltip,
3600 &check_is_hovered,
3601 &check_is_hovered_during_prepaint,
3602 tooltip_id,
3603 current_view,
3604 phase,
3605 show_delay,
3606 window,
3607 cx,
3608 )
3609 }
3610 });
3611
3612 window.on_mouse_event({
3613 let active_tooltip = active_tooltip.clone();
3614 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3615 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3616 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3617 }
3618 }
3619 });
3620
3621 window.on_mouse_event({
3622 let active_tooltip = active_tooltip.clone();
3623 move |_: &ScrollWheelEvent, _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
3631fn handle_tooltip_mouse_move(
3643 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3644 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3645 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3646 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3647 tooltip_id: Option<TooltipId>,
3648 current_view: EntityId,
3649 phase: DispatchPhase,
3650 show_delay: Duration,
3651 window: &mut Window,
3652 cx: &mut App,
3653) {
3654 enum Action {
3657 None,
3658 CancelShow,
3659 ScheduleShow,
3660 CheckVisible,
3661 }
3662
3663 let action = match active_tooltip.borrow().as_ref() {
3664 None => {
3665 let is_hovered = check_is_hovered(window);
3666 if is_hovered && phase.bubble() {
3667 Action::ScheduleShow
3668 } else {
3669 Action::None
3670 }
3671 }
3672 Some(ActiveTooltip::WaitingForShow { .. }) => {
3673 let is_hovered = check_is_hovered(window);
3674 if is_hovered {
3675 Action::None
3676 } else {
3677 Action::CancelShow
3678 }
3679 }
3680 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3681 if phase.capture()
3682 && !check_is_hovered(window)
3683 && (!*is_hoverable
3684 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3685 {
3686 Action::CheckVisible
3687 } else {
3688 Action::None
3689 }
3690 }
3691 Some(ActiveTooltip::WaitingForHide { .. }) => {
3692 if phase.capture()
3693 && (check_is_hovered(window)
3694 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3695 {
3696 Action::CheckVisible
3697 } else {
3698 Action::None
3699 }
3700 }
3701 };
3702
3703 match action {
3704 Action::None => {}
3705 Action::CancelShow => {
3706 active_tooltip.borrow_mut().take();
3708 }
3709 Action::ScheduleShow => {
3710 let delayed_show_task = window.spawn(cx, {
3711 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3712 let build_tooltip = build_tooltip.clone();
3713 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3714 async move |cx| {
3715 cx.background_executor().timer(show_delay).await;
3716 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3717 return;
3718 };
3719 cx.update(|window, cx| {
3720 let new_tooltip =
3721 build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3722 let weak_active_tooltip = Rc::downgrade(&active_tooltip);
3723 ActiveTooltip::Visible {
3724 tooltip: AnyTooltip {
3725 view,
3726 mouse_position: window.mouse_position(),
3727 check_visible_and_update: Rc::new(
3728 move |tooltip_bounds, window, cx| {
3729 let Some(active_tooltip) =
3730 weak_active_tooltip.upgrade()
3731 else {
3732 return false;
3733 };
3734 handle_tooltip_check_visible_and_update(
3735 &active_tooltip,
3736 tooltip_is_hoverable,
3737 &check_is_hovered_during_prepaint,
3738 tooltip_bounds,
3739 window,
3740 cx,
3741 )
3742 },
3743 ),
3744 },
3745 is_hoverable: tooltip_is_hoverable,
3746 }
3747 });
3748 *active_tooltip.borrow_mut() = new_tooltip;
3749 window.refresh();
3750 })
3751 .ok();
3752 }
3753 });
3754 active_tooltip
3755 .borrow_mut()
3756 .replace(ActiveTooltip::WaitingForShow {
3757 _task: delayed_show_task,
3758 });
3759 }
3760 Action::CheckVisible => cx.notify(current_view),
3761 }
3762}
3763
3764fn handle_tooltip_check_visible_and_update(
3768 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3769 tooltip_is_hoverable: bool,
3770 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3771 tooltip_bounds: Bounds<Pixels>,
3772 window: &mut Window,
3773 cx: &mut App,
3774) -> bool {
3775 enum Action {
3778 None,
3779 Hide,
3780 ScheduleHide(AnyTooltip),
3781 CancelHide(AnyTooltip),
3782 }
3783
3784 let is_hovered = check_is_hovered(window)
3785 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
3786 let action = match active_tooltip.borrow().as_ref() {
3787 Some(ActiveTooltip::Visible { tooltip, .. }) => {
3788 if is_hovered {
3789 Action::None
3790 } else {
3791 if tooltip_is_hoverable {
3792 Action::ScheduleHide(tooltip.clone())
3793 } else {
3794 Action::Hide
3795 }
3796 }
3797 }
3798 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
3799 if is_hovered {
3800 Action::CancelHide(tooltip.clone())
3801 } else {
3802 Action::None
3803 }
3804 }
3805 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
3806 };
3807
3808 match action {
3809 Action::None => {}
3810 Action::Hide => clear_active_tooltip(active_tooltip, window),
3811 Action::ScheduleHide(tooltip) => {
3812 let delayed_hide_task = window.spawn(cx, {
3813 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3814 async move |cx| {
3815 cx.background_executor()
3816 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
3817 .await;
3818 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3819 return;
3820 };
3821 if active_tooltip.borrow_mut().take().is_some() {
3822 cx.update(|window, _cx| window.refresh()).ok();
3823 }
3824 }
3825 });
3826 active_tooltip
3827 .borrow_mut()
3828 .replace(ActiveTooltip::WaitingForHide {
3829 tooltip,
3830 _task: delayed_hide_task,
3831 });
3832 }
3833 Action::CancelHide(tooltip) => {
3834 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
3836 tooltip,
3837 is_hoverable: true,
3838 });
3839 }
3840 }
3841
3842 active_tooltip.borrow().is_some()
3843}
3844
3845#[derive(Default)]
3846pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
3847
3848impl Global for GroupHitboxes {}
3849
3850impl GroupHitboxes {
3851 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
3852 cx.default_global::<Self>()
3853 .0
3854 .get(name)
3855 .and_then(|bounds_stack| bounds_stack.last())
3856 .cloned()
3857 }
3858
3859 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
3860 cx.default_global::<Self>()
3861 .0
3862 .entry(name)
3863 .or_default()
3864 .push(hitbox_id);
3865 }
3866
3867 pub fn pop(name: &SharedString, cx: &mut App) {
3868 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
3869 }
3870}
3871
3872pub struct Stateful<E> {
3874 pub(crate) element: E,
3875}
3876
3877impl<E> Styled for Stateful<E>
3878where
3879 E: Styled,
3880{
3881 fn style(&mut self) -> &mut StyleRefinement {
3882 self.element.style()
3883 }
3884}
3885
3886impl<E> StatefulInteractiveElement for Stateful<E>
3887where
3888 E: Element,
3889 Self: InteractiveElement,
3890{
3891}
3892
3893impl<E> InteractiveElement for Stateful<E>
3894where
3895 E: InteractiveElement,
3896{
3897 fn interactivity(&mut self) -> &mut Interactivity {
3898 self.element.interactivity()
3899 }
3900}
3901
3902impl<E> Element for Stateful<E>
3903where
3904 E: Element,
3905{
3906 type RequestLayoutState = E::RequestLayoutState;
3907 type PrepaintState = E::PrepaintState;
3908
3909 fn id(&self) -> Option<ElementId> {
3910 self.element.id()
3911 }
3912
3913 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3914 self.element.source_location()
3915 }
3916
3917 fn a11y_role(&self) -> Option<accesskit::Role> {
3918 self.element.a11y_role()
3919 }
3920
3921 fn write_a11y_info(&self, node: &mut accesskit::Node) {
3922 self.element.write_a11y_info(node);
3923 }
3924
3925 fn a11y_synthetic_children(
3926 &mut self,
3927 prepaint: &mut Self::PrepaintState,
3928 builder: &mut crate::A11ySubtreeBuilder,
3929 ) {
3930 self.element.a11y_synthetic_children(prepaint, builder);
3931 }
3932
3933 fn request_layout(
3934 &mut self,
3935 id: Option<&GlobalElementId>,
3936 inspector_id: Option<&InspectorElementId>,
3937 window: &mut Window,
3938 cx: &mut App,
3939 ) -> (LayoutId, Self::RequestLayoutState) {
3940 self.element.request_layout(id, inspector_id, window, cx)
3941 }
3942
3943 fn prepaint(
3944 &mut self,
3945 id: Option<&GlobalElementId>,
3946 inspector_id: Option<&InspectorElementId>,
3947 bounds: Bounds<Pixels>,
3948 state: &mut Self::RequestLayoutState,
3949 window: &mut Window,
3950 cx: &mut App,
3951 ) -> E::PrepaintState {
3952 self.element
3953 .prepaint(id, inspector_id, bounds, state, window, cx)
3954 }
3955
3956 fn paint(
3957 &mut self,
3958 id: Option<&GlobalElementId>,
3959 inspector_id: Option<&InspectorElementId>,
3960 bounds: Bounds<Pixels>,
3961 request_layout: &mut Self::RequestLayoutState,
3962 prepaint: &mut Self::PrepaintState,
3963 window: &mut Window,
3964 cx: &mut App,
3965 ) {
3966 self.element.paint(
3967 id,
3968 inspector_id,
3969 bounds,
3970 request_layout,
3971 prepaint,
3972 window,
3973 cx,
3974 );
3975 }
3976}
3977
3978impl<E> IntoElement for Stateful<E>
3979where
3980 E: Element,
3981{
3982 type Element = Self;
3983
3984 fn into_element(self) -> Self::Element {
3985 self
3986 }
3987}
3988
3989impl<E> ParentElement for Stateful<E>
3990where
3991 E: ParentElement,
3992{
3993 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
3994 self.element.extend(elements)
3995 }
3996}
3997
3998#[derive(Clone)]
4001pub struct ScrollAnchor {
4002 handle: ScrollHandle,
4003 last_origin: Rc<RefCell<Point<Pixels>>>,
4004}
4005
4006impl ScrollAnchor {
4007 pub fn for_handle(handle: ScrollHandle) -> Self {
4009 Self {
4010 handle,
4011 last_origin: Default::default(),
4012 }
4013 }
4014 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4016 let this = self.clone();
4017
4018 window.on_next_frame(move |_, _| {
4019 let viewport_bounds = this.handle.bounds();
4020 let self_bounds = *this.last_origin.borrow();
4021 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4022 });
4023 }
4024}
4025
4026#[derive(Default, Debug)]
4027struct ScrollHandleState {
4028 offset: Rc<RefCell<Point<Pixels>>>,
4029 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4030 bounds: Bounds<Pixels>,
4031 max_offset: Point<Pixels>,
4032 child_bounds: Vec<Bounds<Pixels>>,
4033 scroll_to_bottom: bool,
4034 overflow: Point<Overflow>,
4035 active_item: Option<ScrollActiveItem>,
4036}
4037
4038#[derive(Default, Debug, Clone, Copy)]
4039struct ScrollActiveItem {
4040 index: usize,
4041 strategy: ScrollStrategy,
4042}
4043
4044#[derive(Default, Debug, Clone, Copy)]
4045enum ScrollStrategy {
4046 #[default]
4047 FirstVisible,
4048 Top,
4049}
4050
4051#[derive(Clone, Debug)]
4055pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4056
4057impl Default for ScrollHandle {
4058 fn default() -> Self {
4059 Self::new()
4060 }
4061}
4062
4063impl ScrollHandle {
4064 pub fn new() -> Self {
4066 Self(Rc::default())
4067 }
4068
4069 pub fn offset(&self) -> Point<Pixels> {
4071 *self.0.borrow().offset.borrow()
4072 }
4073
4074 pub fn max_offset(&self) -> Point<Pixels> {
4076 self.0.borrow().max_offset
4077 }
4078
4079 pub fn top_item(&self) -> usize {
4081 let state = self.0.borrow();
4082 let top = state.bounds.top() - state.offset.borrow().y;
4083
4084 match state.child_bounds.binary_search_by(|bounds| {
4085 if top < bounds.top() {
4086 Ordering::Greater
4087 } else if top > bounds.bottom() {
4088 Ordering::Less
4089 } else {
4090 Ordering::Equal
4091 }
4092 }) {
4093 Ok(ix) => ix,
4094 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4095 }
4096 }
4097
4098 pub fn bottom_item(&self) -> usize {
4100 let state = self.0.borrow();
4101 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4102
4103 match state.child_bounds.binary_search_by(|bounds| {
4104 if bottom < bounds.top() {
4105 Ordering::Greater
4106 } else if bottom > bounds.bottom() {
4107 Ordering::Less
4108 } else {
4109 Ordering::Equal
4110 }
4111 }) {
4112 Ok(ix) => ix,
4113 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4114 }
4115 }
4116
4117 pub fn bounds(&self) -> Bounds<Pixels> {
4119 self.0.borrow().bounds
4120 }
4121
4122 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4124 self.0.borrow().child_bounds.get(ix).cloned()
4125 }
4126
4127 pub fn scroll_to_item(&self, ix: usize) {
4129 let mut state = self.0.borrow_mut();
4130 state.active_item = Some(ScrollActiveItem {
4131 index: ix,
4132 strategy: ScrollStrategy::default(),
4133 });
4134 }
4135
4136 pub fn scroll_to_top_of_item(&self, ix: usize) {
4139 let mut state = self.0.borrow_mut();
4140 state.active_item = Some(ScrollActiveItem {
4141 index: ix,
4142 strategy: ScrollStrategy::Top,
4143 });
4144 }
4145
4146 fn scroll_to_active_item(&self) {
4150 let mut state = self.0.borrow_mut();
4151
4152 let Some(active_item) = state.active_item else {
4153 return;
4154 };
4155
4156 let active_item = match state.child_bounds.get(active_item.index) {
4157 Some(bounds) => {
4158 let mut scroll_offset = state.offset.borrow_mut();
4159
4160 match active_item.strategy {
4161 ScrollStrategy::FirstVisible => {
4162 if state.overflow.y == Overflow::Scroll {
4163 let child_height = bounds.size.height;
4164 let viewport_height = state.bounds.size.height;
4165 if child_height > viewport_height {
4166 scroll_offset.y = state.bounds.top() - bounds.top();
4167 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4168 scroll_offset.y = state.bounds.top() - bounds.top();
4169 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4170 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4171 }
4172 }
4173 }
4174 ScrollStrategy::Top => {
4175 scroll_offset.y = state.bounds.top() - bounds.top();
4176 }
4177 }
4178
4179 if state.overflow.x == Overflow::Scroll {
4180 let child_width = bounds.size.width;
4181 let viewport_width = state.bounds.size.width;
4182 if child_width > viewport_width {
4183 scroll_offset.x = state.bounds.left() - bounds.left();
4184 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4185 scroll_offset.x = state.bounds.left() - bounds.left();
4186 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4187 scroll_offset.x = state.bounds.right() - bounds.right();
4188 }
4189 }
4190 None
4191 }
4192 None => Some(active_item),
4193 };
4194 state.active_item = active_item;
4195 }
4196
4197 pub fn scroll_to_bottom(&self) {
4199 let mut state = self.0.borrow_mut();
4200 state.scroll_to_bottom = true;
4201 }
4202
4203 pub fn set_offset(&self, mut position: Point<Pixels>) {
4207 let state = self.0.borrow();
4208 *state.offset.borrow_mut() = position;
4209 }
4210
4211 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4213 let ix = self.top_item();
4214 let state = self.0.borrow();
4215
4216 if let Some(child_bounds) = state.child_bounds.get(ix) {
4217 (
4218 ix,
4219 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4220 )
4221 } else {
4222 (ix, px(0.))
4223 }
4224 }
4225
4226 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4228 let ix = self.bottom_item();
4229 let state = self.0.borrow();
4230
4231 if let Some(child_bounds) = state.child_bounds.get(ix) {
4232 (
4233 ix,
4234 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4235 )
4236 } else {
4237 (ix, px(0.))
4238 }
4239 }
4240
4241 pub fn children_count(&self) -> usize {
4243 self.0.borrow().child_bounds.len()
4244 }
4245}
4246
4247#[cfg(test)]
4248mod tests {
4249 use super::*;
4250 use crate::{
4251 AnyWindowHandle, AppContext as _, Context, InputEvent, Keystroke, MouseMoveEvent,
4252 TestAppContext, canvas, util::FluentBuilder as _,
4253 };
4254 use std::{cell::Cell, rc::Weak};
4255
4256 struct GroupHoverTestView {
4257 render_count: Rc<Cell<usize>>,
4258 anonymous_paint_count: Rc<Cell<usize>>,
4259 stateful_width: Rc<Cell<Pixels>>,
4260 }
4261
4262 impl Render for GroupHoverTestView {
4263 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4264 self.render_count.set(self.render_count.get() + 1);
4265 let anonymous_paint_count = self.anonymous_paint_count.clone();
4266 let stateful_width = self.stateful_width.clone();
4267 div().size_full().child(
4268 div()
4269 .ml(px(20.))
4270 .mt(px(20.))
4271 .size(px(50.))
4272 .relative()
4273 .group("hover-group")
4274 .child(
4275 div()
4276 .absolute()
4277 .size_full()
4278 .invisible()
4279 .group_hover("hover-group", |style| style.visible())
4280 .child(canvas(
4281 |_, _, _| {},
4282 move |_, _, _, _| {
4283 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4284 },
4285 )),
4286 )
4287 .child(
4288 div()
4289 .id("stateful-group-hover-target")
4290 .absolute()
4291 .top_0()
4292 .left_0()
4293 .size(px(10.))
4294 .group_hover("hover-group", |style| style.size(px(20.)))
4295 .child(canvas(
4296 move |bounds, _, _| stateful_width.set(bounds.size.width),
4297 |_, _, _, _| {},
4298 )),
4299 ),
4300 )
4301 }
4302 }
4303
4304 #[gpui::test]
4305 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4306 let render_count = Rc::new(Cell::new(0));
4307 let anonymous_paint_count = Rc::new(Cell::new(0));
4308 let stateful_width = Rc::new(Cell::new(px(0.)));
4309 let window = cx.add_window({
4310 let render_count = render_count.clone();
4311 let anonymous_paint_count = anonymous_paint_count.clone();
4312 let stateful_width = stateful_width.clone();
4313 move |_, _| GroupHoverTestView {
4314 render_count,
4315 anonymous_paint_count,
4316 stateful_width,
4317 }
4318 });
4319 let window = AnyWindowHandle::from(window);
4320
4321 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4322 .unwrap();
4323 assert_eq!(anonymous_paint_count.get(), 0);
4324 assert_eq!(stateful_width.get(), px(10.));
4325
4326 let move_mouse = |cx: &mut TestAppContext, position| {
4327 cx.update_window(window, |_, window, cx| {
4328 window.simulate_mouse_move(position, cx)
4329 })
4330 .unwrap();
4331 };
4332
4333 let initial_render_count = render_count.get();
4334 move_mouse(cx, point(px(25.), px(25.)));
4335 assert_eq!(render_count.get(), initial_render_count + 1);
4336 assert_eq!(anonymous_paint_count.get(), 1);
4337 assert_eq!(stateful_width.get(), px(20.));
4338
4339 move_mouse(cx, point(px(30.), px(30.)));
4340 assert_eq!(render_count.get(), initial_render_count + 1);
4341 assert_eq!(anonymous_paint_count.get(), 1);
4342 assert_eq!(stateful_width.get(), px(20.));
4343
4344 move_mouse(cx, point(px(5.), px(5.)));
4345 assert_eq!(render_count.get(), initial_render_count + 2);
4346 assert_eq!(anonymous_paint_count.get(), 1);
4347 assert_eq!(stateful_width.get(), px(10.));
4348
4349 move_mouse(cx, point(px(10.), px(10.)));
4350 assert_eq!(render_count.get(), initial_render_count + 2);
4351 assert_eq!(anonymous_paint_count.get(), 1);
4352 assert_eq!(stateful_width.get(), px(10.));
4353 }
4354
4355 struct HoverListenerLayoutTestView {
4356 target_left: Pixels,
4357 hover_transitions: Rc<RefCell<Vec<bool>>>,
4358 }
4359
4360 impl Render for HoverListenerLayoutTestView {
4361 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4362 let hover_transitions = self.hover_transitions.clone();
4363 div().relative().size_full().child(
4364 div()
4365 .id("hover-target")
4366 .absolute()
4367 .left(self.target_left)
4368 .top_0()
4369 .size(px(20.))
4370 .on_click(|_, _, _| {})
4371 .on_hover(move |is_hovered, _, _| {
4372 hover_transitions.borrow_mut().push(*is_hovered);
4373 }),
4374 )
4375 }
4376 }
4377
4378 #[gpui::test]
4379 fn hover_listeners_update_when_layout_changes_under_stationary_mouse(cx: &mut TestAppContext) {
4380 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4381 let window = cx.add_window({
4382 let hover_transitions = hover_transitions.clone();
4383 move |_, _| HoverListenerLayoutTestView {
4384 target_left: px(40.),
4385 hover_transitions,
4386 }
4387 });
4388 let any_window = AnyWindowHandle::from(window);
4389
4390 cx.update_window(any_window, |_, window, cx| {
4391 window.draw(cx).clear(cx);
4392 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4393 })
4394 .unwrap();
4395 assert!(hover_transitions.borrow().is_empty());
4396
4397 window
4398 .update(cx, |view, _, cx| {
4399 view.target_left = px(0.);
4400 cx.notify();
4401 })
4402 .unwrap();
4403 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4404 .unwrap();
4405 assert_eq!(*hover_transitions.borrow(), [true]);
4406
4407 window
4408 .update(cx, |view, _, cx| {
4409 view.target_left = px(40.);
4410 cx.notify();
4411 })
4412 .unwrap();
4413 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4414 .unwrap();
4415 assert_eq!(*hover_transitions.borrow(), [true, false]);
4416 }
4417
4418 #[gpui::test]
4419 fn hover_listeners_remain_hovered_during_stationary_mouse_press(cx: &mut TestAppContext) {
4420 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4421 let window = cx.add_window({
4422 let hover_transitions = hover_transitions.clone();
4423 move |_, _| HoverListenerLayoutTestView {
4424 target_left: px(0.),
4425 hover_transitions,
4426 }
4427 });
4428 let any_window = AnyWindowHandle::from(window);
4429 let mouse_position = point(px(10.), px(10.));
4430
4431 cx.update_window(any_window, |_, window, cx| {
4432 window.draw(cx).clear(cx);
4433 window.simulate_mouse_move(mouse_position, cx);
4434 })
4435 .unwrap();
4436 assert_eq!(*hover_transitions.borrow(), [true]);
4437
4438 cx.update_window(any_window, |_, window, cx| {
4439 window.dispatch_event(
4440 MouseDownEvent {
4441 position: mouse_position,
4442 button: MouseButton::Left,
4443 modifiers: Default::default(),
4444 click_count: 1,
4445 first_mouse: false,
4446 }
4447 .to_platform_input(),
4448 cx,
4449 );
4450 window.draw(cx).clear(cx);
4451 })
4452 .unwrap();
4453 assert_eq!(*hover_transitions.borrow(), [true]);
4454
4455 cx.update_window(any_window, |_, window, cx| {
4456 window.dispatch_event(
4457 MouseUpEvent {
4458 position: mouse_position,
4459 button: MouseButton::Left,
4460 modifiers: Default::default(),
4461 click_count: 1,
4462 }
4463 .to_platform_input(),
4464 cx,
4465 );
4466 window.draw(cx).clear(cx);
4467 })
4468 .unwrap();
4469 assert_eq!(*hover_transitions.borrow(), [true]);
4470 }
4471
4472 struct TestTooltipView;
4473
4474 impl Render for TestTooltipView {
4475 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4476 div().w(px(20.)).h(px(20.)).child("tooltip")
4477 }
4478 }
4479
4480 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4481
4482 struct TooltipCaptureElement {
4483 child: AnyElement,
4484 captured_active_tooltip: CapturedActiveTooltip,
4485 }
4486
4487 impl IntoElement for TooltipCaptureElement {
4488 type Element = Self;
4489
4490 fn into_element(self) -> Self::Element {
4491 self
4492 }
4493 }
4494
4495 impl Element for TooltipCaptureElement {
4496 type RequestLayoutState = ();
4497 type PrepaintState = ();
4498
4499 fn id(&self) -> Option<ElementId> {
4500 None
4501 }
4502
4503 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4504 None
4505 }
4506
4507 fn request_layout(
4508 &mut self,
4509 _id: Option<&GlobalElementId>,
4510 _inspector_id: Option<&InspectorElementId>,
4511 window: &mut Window,
4512 cx: &mut App,
4513 ) -> (LayoutId, Self::RequestLayoutState) {
4514 (self.child.request_layout(window, cx), ())
4515 }
4516
4517 fn prepaint(
4518 &mut self,
4519 _id: Option<&GlobalElementId>,
4520 _inspector_id: Option<&InspectorElementId>,
4521 _bounds: Bounds<Pixels>,
4522 _request_layout: &mut Self::RequestLayoutState,
4523 window: &mut Window,
4524 cx: &mut App,
4525 ) -> Self::PrepaintState {
4526 self.child.prepaint(window, cx);
4527 }
4528
4529 fn paint(
4530 &mut self,
4531 _id: Option<&GlobalElementId>,
4532 _inspector_id: Option<&InspectorElementId>,
4533 _bounds: Bounds<Pixels>,
4534 _request_layout: &mut Self::RequestLayoutState,
4535 _prepaint: &mut Self::PrepaintState,
4536 window: &mut Window,
4537 cx: &mut App,
4538 ) {
4539 self.child.paint(window, cx);
4540 window.with_global_id("target".into(), |global_id, window| {
4541 window.with_element_state::<InteractiveElementState, _>(
4542 global_id,
4543 |state, _window| {
4544 let state = state.unwrap();
4545 *self.captured_active_tooltip.borrow_mut() =
4546 state.active_tooltip.as_ref().map(Rc::downgrade);
4547 ((), state)
4548 },
4549 )
4550 });
4551 }
4552 }
4553
4554 struct TooltipOwner {
4555 captured_active_tooltip: CapturedActiveTooltip,
4556 show_delay_override: Option<Duration>,
4557 }
4558
4559 impl Render for TooltipOwner {
4560 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4561 TooltipCaptureElement {
4562 child: div()
4563 .size_full()
4564 .child(
4565 div()
4566 .id("target")
4567 .w(px(50.))
4568 .h(px(50.))
4569 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4570 .when_some(self.show_delay_override, |this, delay| {
4571 this.tooltip_show_delay(delay)
4572 }),
4573 )
4574 .into_any_element(),
4575 captured_active_tooltip: self.captured_active_tooltip.clone(),
4576 }
4577 }
4578 }
4579
4580 #[test]
4581 fn scroll_handle_aligns_wide_children_to_left_edge() {
4582 let handle = ScrollHandle::new();
4583 {
4584 let mut state = handle.0.borrow_mut();
4585 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4586 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4587 state.overflow.x = Overflow::Scroll;
4588 state.active_item = Some(ScrollActiveItem {
4589 index: 0,
4590 strategy: ScrollStrategy::default(),
4591 });
4592 }
4593
4594 handle.scroll_to_active_item();
4595
4596 assert_eq!(handle.offset().x, px(-25.));
4597 }
4598
4599 #[test]
4600 fn scroll_handle_aligns_tall_children_to_top_edge() {
4601 let handle = ScrollHandle::new();
4602 {
4603 let mut state = handle.0.borrow_mut();
4604 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4605 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4606 state.overflow.y = Overflow::Scroll;
4607 state.active_item = Some(ScrollActiveItem {
4608 index: 0,
4609 strategy: ScrollStrategy::default(),
4610 });
4611 }
4612
4613 handle.scroll_to_active_item();
4614
4615 assert_eq!(handle.offset().y, px(-25.));
4616 }
4617
4618 fn setup_tooltip_owner_test(
4619 show_delay_override: Option<Duration>,
4620 ) -> (
4621 TestAppContext,
4622 crate::AnyWindowHandle,
4623 CapturedActiveTooltip,
4624 ) {
4625 let mut test_app = TestAppContext::single();
4626 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
4627 let window = test_app.add_window({
4628 let captured_active_tooltip = captured_active_tooltip.clone();
4629 move |_, _| TooltipOwner {
4630 captured_active_tooltip,
4631 show_delay_override,
4632 }
4633 });
4634 let any_window = window.into();
4635
4636 test_app
4637 .update_window(any_window, |_, window, cx| {
4638 window.draw(cx).clear(cx);
4639 })
4640 .unwrap();
4641
4642 test_app
4643 .update_window(any_window, |_, window, cx| {
4644 window.dispatch_event(
4645 MouseMoveEvent {
4646 position: point(px(10.), px(10.)),
4647 modifiers: Default::default(),
4648 pressed_button: None,
4649 }
4650 .to_platform_input(),
4651 cx,
4652 );
4653 })
4654 .unwrap();
4655
4656 test_app
4657 .update_window(any_window, |_, window, cx| {
4658 window.draw(cx).clear(cx);
4659 })
4660 .unwrap();
4661
4662 (test_app, any_window, captured_active_tooltip)
4663 }
4664
4665 #[test]
4666 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
4667 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4668
4669 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4670 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4671 assert!(matches!(
4672 active_tooltip.borrow().as_ref(),
4673 Some(ActiveTooltip::WaitingForShow { .. })
4674 ));
4675
4676 test_app
4677 .update_window(any_window, |_, window, _| {
4678 window.remove_window();
4679 })
4680 .unwrap();
4681 test_app.run_until_parked();
4682 drop(active_tooltip);
4683
4684 assert!(weak_active_tooltip.upgrade().is_none());
4685 }
4686
4687 #[test]
4688 fn tooltip_respects_custom_show_delay() {
4689 let extra_delay = Duration::from_secs(1);
4690 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
4691 let (mut test_app, _any_window, captured_active_tooltip) =
4692 setup_tooltip_owner_test(Some(show_delay_override));
4693
4694 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4695 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4696
4697 test_app
4698 .dispatcher
4699 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4700 test_app.run_until_parked();
4701
4702 assert!(matches!(
4703 active_tooltip.borrow().as_ref(),
4704 Some(ActiveTooltip::WaitingForShow { .. })
4705 ));
4706
4707 test_app.dispatcher.advance_clock(extra_delay);
4708 test_app.run_until_parked();
4709
4710 assert!(matches!(
4711 active_tooltip.borrow().as_ref(),
4712 Some(ActiveTooltip::Visible { .. })
4713 ));
4714 }
4715
4716 #[test]
4717 fn tooltip_is_released_when_its_owner_disappears() {
4718 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4719
4720 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4721 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4722
4723 test_app
4724 .dispatcher
4725 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4726 test_app.run_until_parked();
4727
4728 assert!(matches!(
4729 active_tooltip.borrow().as_ref(),
4730 Some(ActiveTooltip::Visible { .. })
4731 ));
4732
4733 test_app
4734 .update_window(any_window, |_, window, _| {
4735 window.remove_window();
4736 })
4737 .unwrap();
4738 test_app.run_until_parked();
4739 drop(active_tooltip);
4740
4741 assert!(weak_active_tooltip.upgrade().is_none());
4742 }
4743
4744 #[test]
4745 fn tooltip_hides_after_mouse_leaves_origin() {
4746 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4747
4748 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4749 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4750
4751 test_app
4752 .dispatcher
4753 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4754 test_app.run_until_parked();
4755
4756 assert!(matches!(
4757 active_tooltip.borrow().as_ref(),
4758 Some(ActiveTooltip::Visible { .. })
4759 ));
4760
4761 test_app
4762 .update_window(any_window, |_, window, cx| {
4763 window.dispatch_event(
4764 MouseMoveEvent {
4765 position: point(px(75.), px(75.)),
4766 modifiers: Default::default(),
4767 pressed_button: None,
4768 }
4769 .to_platform_input(),
4770 cx,
4771 );
4772 })
4773 .unwrap();
4774
4775 assert!(active_tooltip.borrow().is_none());
4776 }
4777
4778 struct MouseDownOutOwner {
4779 mouse_down_out_count: Rc<RefCell<usize>>,
4780 }
4781
4782 impl Render for MouseDownOutOwner {
4783 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4784 let mouse_down_out_count = self.mouse_down_out_count.clone();
4785 div()
4786 .size_full()
4787 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
4788 move |_, _, _| {
4789 *mouse_down_out_count.borrow_mut() += 1;
4790 },
4791 ))
4792 }
4793 }
4794
4795 #[test]
4796 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
4797 let mut test_app = TestAppContext::single();
4798 let mouse_down_out_count = Rc::new(RefCell::new(0));
4799 let window = test_app.add_window({
4800 let mouse_down_out_count = mouse_down_out_count.clone();
4801 move |_, _| MouseDownOutOwner {
4802 mouse_down_out_count,
4803 }
4804 });
4805 let any_window: AnyWindowHandle = window.into();
4806
4807 fn dispatch_mouse_down_outside_target(
4808 test_app: &mut TestAppContext,
4809 any_window: AnyWindowHandle,
4810 ) {
4811 test_app
4812 .update_window(any_window, |_, window, cx| {
4813 window.dispatch_event(
4814 MouseDownEvent {
4815 position: point(px(75.), px(75.)),
4816 button: MouseButton::Left,
4817 modifiers: Default::default(),
4818 click_count: 1,
4819 first_mouse: false,
4820 }
4821 .to_platform_input(),
4822 cx,
4823 );
4824 })
4825 .unwrap();
4826 }
4827
4828 test_app
4829 .update_window(any_window, |_, window, cx| {
4830 window.draw(cx).clear(cx);
4831 })
4832 .unwrap();
4833
4834 dispatch_mouse_down_outside_target(&mut test_app, any_window);
4835 assert_eq!(
4836 *mouse_down_out_count.borrow(),
4837 1,
4838 "mouse down outside the element should fire mouse-down-out listeners"
4839 );
4840
4841 test_app
4842 .update_window(any_window, |_, window, cx| {
4843 cx.set_prompt_builder(crate::fallback_prompt_renderer);
4844 let _receiver =
4845 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
4846 assert!(window.has_active_prompt());
4847 window.draw(cx).clear(cx);
4848 })
4849 .unwrap();
4850
4851 dispatch_mouse_down_outside_target(&mut test_app, any_window);
4852 assert_eq!(
4853 *mouse_down_out_count.borrow(),
4854 1,
4855 "mouse down over an active prompt should not fire mouse-down-out listeners"
4856 );
4857 }
4858
4859 #[test]
4860 fn test_accessibility_id_builder_writes_author_id() {
4861 let mut element = div()
4862 .id("buffer-font-size")
4863 .accessibility_id("settings.buffer-font-size");
4864 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
4865
4866 element.interactivity().write_a11y_info(&mut node);
4867
4868 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
4869 }
4870
4871 #[test]
4872 fn test_write_a11y_info_string_and_numeric_properties() {
4873 let mut interactivity = Interactivity::default();
4874 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
4875 interactivity.aria.label = Some("Buffer Font Size".into());
4876 interactivity.aria.value = Some("15".into());
4877 interactivity.aria.placeholder = Some("Search".into());
4878 interactivity.aria.numeric_value = Some(15.0);
4879 interactivity.aria.min_numeric_value = Some(6.0);
4880 interactivity.aria.max_numeric_value = Some(72.0);
4881 interactivity.aria.numeric_value_step = Some(1.0);
4882
4883 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
4884 interactivity.write_a11y_info(&mut node);
4885
4886 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
4887 assert_eq!(node.label(), Some("Buffer Font Size"));
4888 assert_eq!(node.value(), Some("15"));
4889 assert_eq!(node.placeholder(), Some("Search"));
4890 assert_eq!(node.numeric_value(), Some(15.0));
4891 assert_eq!(node.min_numeric_value(), Some(6.0));
4892 assert_eq!(node.max_numeric_value(), Some(72.0));
4893 assert_eq!(node.numeric_value_step(), Some(1.0));
4894 }
4895
4896 struct KeyboardActivationTest {
4899 focus_a: FocusHandle,
4900 focus_b: FocusHandle,
4901 clicks: Rc<RefCell<Vec<&'static str>>>,
4902 }
4903
4904 impl Render for KeyboardActivationTest {
4905 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4906 let clicks_a = self.clicks.clone();
4907 let clicks_b = self.clicks.clone();
4908 div()
4909 .size_full()
4910 .child(
4911 div()
4912 .id("a")
4913 .w(px(50.))
4914 .h(px(50.))
4915 .track_focus(&self.focus_a)
4916 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
4917 )
4918 .child(
4919 div()
4920 .id("b")
4921 .w(px(50.))
4922 .h(px(50.))
4923 .track_focus(&self.focus_b)
4924 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
4925 )
4926 }
4927 }
4928
4929 fn setup_keyboard_activation_test() -> (
4930 TestAppContext,
4931 AnyWindowHandle,
4932 Rc<RefCell<Vec<&'static str>>>,
4933 FocusHandle,
4934 FocusHandle,
4935 ) {
4936 let mut cx = TestAppContext::single();
4937 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
4938 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
4939 let window = cx.add_window({
4940 let focus_a = focus_a.clone();
4941 let focus_b = focus_b.clone();
4942 let clicks = clicks.clone();
4943 move |_, _| KeyboardActivationTest {
4944 focus_a,
4945 focus_b,
4946 clicks,
4947 }
4948 });
4949 (cx, window.into(), clicks, focus_a, focus_b)
4950 }
4951
4952 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
4955 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
4956 .unwrap();
4957 cx.run_until_parked();
4958 cx.update_window(window, |_, window, cx| {
4959 window.draw(cx).clear(cx);
4960 })
4961 .unwrap();
4962 }
4963
4964 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4965 let keystroke = Keystroke::parse(key).unwrap();
4966 cx.update_window(window, |_, window, cx| {
4967 window.dispatch_event(
4968 KeyDownEvent {
4969 keystroke,
4970 is_held: false,
4971 prefer_character_input: false,
4972 }
4973 .to_platform_input(),
4974 cx,
4975 );
4976 })
4977 .unwrap();
4978 }
4979
4980 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4981 let keystroke = Keystroke::parse(key).unwrap();
4982 cx.update_window(window, |_, window, cx| {
4983 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
4984 })
4985 .unwrap();
4986 }
4987
4988 #[test]
4990 fn keyboard_activation_fires_click_on_same_element() {
4991 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4992
4993 focus_and_draw(&mut cx, window, &focus_a);
4994 key_down(&mut cx, window, "enter");
4995 key_up(&mut cx, window, "enter");
4996
4997 assert_eq!(*clicks.borrow(), vec!["a"]);
4998 }
4999
5000 #[test]
5005 fn keyboard_activation_does_not_leak_across_focus_change() {
5006 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5007
5008 focus_and_draw(&mut cx, window, &focus_a);
5010 key_down(&mut cx, window, "enter");
5011
5012 focus_and_draw(&mut cx, window, &focus_b);
5014 key_up(&mut cx, window, "enter");
5015
5016 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5019 }
5020
5021 #[test]
5026 fn keyboard_activation_does_not_leak_when_focus_returns() {
5027 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5028
5029 focus_and_draw(&mut cx, window, &focus_a);
5031 key_down(&mut cx, window, "enter");
5032
5033 focus_and_draw(&mut cx, window, &focus_b);
5036 focus_and_draw(&mut cx, window, &focus_a);
5037 key_up(&mut cx, window, "enter");
5038
5039 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5041 }
5042
5043 #[test]
5048 fn keyboard_activation_cleared_by_intervening_key_release() {
5049 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5050
5051 focus_and_draw(&mut cx, window, &focus_a);
5052 key_down(&mut cx, window, "escape");
5053 key_down(&mut cx, window, "space");
5054 key_up(&mut cx, window, "escape");
5055 key_up(&mut cx, window, "space");
5056
5057 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5058 }
5059
5060 #[test]
5064 fn keyboard_activation_does_not_distinguish_space_and_enter() {
5065 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5066
5067 focus_and_draw(&mut cx, window, &focus_a);
5068 key_down(&mut cx, window, "space");
5069 key_up(&mut cx, window, "enter");
5070
5071 assert_eq!(*clicks.borrow(), vec!["a"]);
5072 }
5073
5074 #[test]
5077 fn keyboard_activation_cleared_by_intervening_keydown() {
5078 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5079
5080 focus_and_draw(&mut cx, window, &focus_a);
5081 key_down(&mut cx, window, "enter");
5082 key_down(&mut cx, window, "a");
5083 key_up(&mut cx, window, "enter");
5084
5085 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5086 }
5087
5088 #[test]
5091 fn keyboard_activation_ignores_modified_keys() {
5092 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5093
5094 focus_and_draw(&mut cx, window, &focus_a);
5095 key_down(&mut cx, window, "cmd-enter");
5096 key_up(&mut cx, window, "cmd-enter");
5097
5098 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5099 }
5100
5101 struct TabGroupFocus {
5105 group_a: FocusHandle,
5106 item_a: FocusHandle,
5107 group_b: FocusHandle,
5108 item_b: FocusHandle,
5109 }
5110
5111 impl Render for TabGroupFocus {
5112 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5113 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
5114 div()
5115 .track_focus(container)
5116 .tab_group()
5117 .child(div().track_focus(item))
5118 }
5119 div()
5120 .child(group(&self.group_a, &self.item_a))
5121 .child(group(&self.group_b, &self.item_b))
5122 }
5123 }
5124
5125 #[test]
5129 fn focus_next_from_tab_group_container_enters_that_group() {
5130 let mut cx = TestAppContext::single();
5131 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
5132 (
5133 cx.focus_handle(),
5134 cx.focus_handle().tab_stop(true),
5135 cx.focus_handle(),
5136 cx.focus_handle().tab_stop(true),
5137 )
5138 });
5139 let window: AnyWindowHandle = cx
5140 .add_window({
5141 let (group_a, item_a, group_b, item_b) =
5142 (group_a, item_a, group_b.clone(), item_b.clone());
5143 move |_, _| TabGroupFocus {
5144 group_a,
5145 item_a,
5146 group_b,
5147 item_b,
5148 }
5149 })
5150 .into();
5151 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5152 .unwrap();
5153
5154 let focused = cx
5156 .update_window(window, |_, window, cx| {
5157 window.focus(&group_b, cx);
5158 window.focus_next(cx);
5159 window.focused(cx).map(|handle| handle.id)
5160 })
5161 .unwrap();
5162
5163 assert_eq!(focused, Some(item_b.id));
5164 }
5165
5166 struct ContentSizedGrid;
5167
5168 impl Render for ContentSizedGrid {
5169 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5170 let widths = [px(100.), px(200.), px(50.)];
5171 div().size_full().child(
5172 div()
5173 .w_full()
5174 .grid()
5175 .grid_cols_max_content(widths.len() as u16)
5176 .children(widths.into_iter().enumerate().map(|(index, width)| {
5177 div()
5178 .debug_selector(move || format!("cell-{index}"))
5179 .w(width)
5180 .h(px(10.))
5181 })),
5182 )
5183 }
5184 }
5185
5186 #[gpui::test]
5187 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
5188 let window = cx.add_window(|_, _| ContentSizedGrid);
5189 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
5190 .unwrap();
5191
5192 let mut bounds = |selector: &'static str| {
5193 cx.update_window(window.into(), |_, window, _| {
5194 window.rendered_frame.debug_bounds.get(selector).copied()
5195 })
5196 .unwrap()
5197 .unwrap_or_else(|| panic!("{selector} was not rendered"))
5198 };
5199
5200 assert_eq!(bounds("cell-0").origin.x, px(0.));
5201 assert_eq!(bounds("cell-1").origin.x, px(100.));
5202 assert_eq!(bounds("cell-2").origin.x, px(300.));
5203 }
5204}