1use crate::{
19 Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, BackGestureEvent, Bounds, ClickEvent,
20 DispatchPhase, Display, Element, ElementId, Entity, EntityId, ExternalDragPayload,
21 ExternalDragPayloadSource, FileDropEvent, FocusHandle, Global, GlobalElementId, Hitbox,
22 HitboxBehavior, HitboxId, InspectorElementId, IsZero, KeyContext, KeyDownEvent, KeyUpEvent,
23 KeyboardButton, KeyboardClickEvent, LayoutId, LongPressEvent, ModifiersChangedEvent,
24 MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent, MouseMoveEvent,
25 MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels,
26 Point, Render, ScrollEvent, SharedString, Size, Style, StyleRefinement, Styled, Task,
27 TooltipId, TouchPhase, Visibility, Window, WindowControlArea, point, px, size,
28};
29use collections::HashMap;
30use gpui_util::ResultExt;
31use refineable::Refineable;
32use smallvec::SmallVec;
33use std::{
34 any::{Any, TypeId},
35 cell::{Cell, RefCell},
36 cmp::Ordering,
37 fmt::Debug,
38 marker::PhantomData,
39 mem,
40 rc::Rc,
41 sync::Arc,
42 time::Duration,
43};
44
45use super::ImageCacheProvider;
46
47#[cfg(feature = "stacker")]
48type StackSafe<T> = stacksafe::StackSafe<T>;
49#[cfg(not(feature = "stacker"))]
50type StackSafe<T> = T;
51
52const DRAG_THRESHOLD: f64 = 2.;
53const DEFAULT_TOOLTIP_SHOW_DELAY: Duration = Duration::from_millis(500);
54const HOVERABLE_TOOLTIP_HIDE_DELAY: Duration = Duration::from_millis(500);
55
56pub struct GroupStyle {
58 pub group: SharedString,
60
61 pub style: Box<StyleRefinement>,
64}
65
66pub struct DragMoveEvent<T> {
68 pub event: MouseMoveEvent,
70
71 pub bounds: Bounds<Pixels>,
73 drag: PhantomData<T>,
74 dragged_item: Arc<dyn Any>,
75}
76
77impl<T: 'static> DragMoveEvent<T> {
78 pub fn drag<'b>(&self, cx: &'b App) -> &'b T {
80 cx.active_drag
81 .as_ref()
82 .and_then(|drag| drag.value.downcast_ref::<T>())
83 .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
84 }
85
86 pub fn dragged_item(&self) -> &dyn Any {
88 self.dragged_item.as_ref()
89 }
90}
91
92impl Interactivity {
93 #[cfg(any(feature = "inspector", debug_assertions))]
95 #[track_caller]
96 pub fn new() -> Interactivity {
97 Interactivity {
98 source_location: Some(core::panic::Location::caller()),
99 ..Default::default()
100 }
101 }
102
103 #[cfg(not(any(feature = "inspector", debug_assertions)))]
105 pub fn new() -> Interactivity {
106 Interactivity::default()
107 }
108
109 pub fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
111 #[cfg(any(feature = "inspector", debug_assertions))]
112 {
113 self.source_location
114 }
115
116 #[cfg(not(any(feature = "inspector", debug_assertions)))]
117 {
118 None
119 }
120 }
121
122 pub fn on_mouse_down(
127 &mut self,
128 button: MouseButton,
129 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
130 ) {
131 self.mouse_down_listeners
132 .push(Box::new(move |event, phase, hitbox, window, cx| {
133 if phase == DispatchPhase::Bubble
134 && event.button == button
135 && hitbox.is_hovered(window)
136 {
137 (listener)(event, window, cx)
138 }
139 }));
140 }
141
142 pub fn capture_any_mouse_down(
147 &mut self,
148 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
149 ) {
150 self.mouse_down_listeners
151 .push(Box::new(move |event, phase, hitbox, window, cx| {
152 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
153 (listener)(event, window, cx)
154 }
155 }));
156 }
157
158 pub fn on_any_mouse_down(
163 &mut self,
164 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
165 ) {
166 self.mouse_down_listeners
167 .push(Box::new(move |event, phase, hitbox, window, cx| {
168 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
169 (listener)(event, window, cx)
170 }
171 }));
172 }
173
174 pub fn on_mouse_pressure(
179 &mut self,
180 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
181 ) {
182 self.mouse_pressure_listeners
183 .push(Box::new(move |event, phase, hitbox, window, cx| {
184 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
185 (listener)(event, window, cx)
186 }
187 }));
188 }
189
190 pub fn capture_mouse_pressure(
195 &mut self,
196 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
197 ) {
198 self.mouse_pressure_listeners
199 .push(Box::new(move |event, phase, hitbox, window, cx| {
200 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
201 (listener)(event, window, cx)
202 }
203 }));
204 }
205
206 pub fn on_mouse_up(
211 &mut self,
212 button: MouseButton,
213 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
214 ) {
215 self.mouse_up_listeners
216 .push(Box::new(move |event, phase, hitbox, window, cx| {
217 if phase == DispatchPhase::Bubble
218 && event.button == button
219 && hitbox.is_hovered(window)
220 {
221 (listener)(event, window, cx)
222 }
223 }));
224 }
225
226 pub fn capture_any_mouse_up(
231 &mut self,
232 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
233 ) {
234 self.mouse_up_listeners
235 .push(Box::new(move |event, phase, hitbox, window, cx| {
236 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
237 (listener)(event, window, cx)
238 }
239 }));
240 }
241
242 pub fn on_any_mouse_up(
247 &mut self,
248 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
249 ) {
250 self.mouse_up_listeners
251 .push(Box::new(move |event, phase, hitbox, window, cx| {
252 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
253 (listener)(event, window, cx)
254 }
255 }));
256 }
257
258 pub fn on_mouse_down_out(
264 &mut self,
265 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
266 ) {
267 self.mouse_down_listeners
268 .push(Box::new(move |event, phase, hitbox, window, cx| {
269 if phase == DispatchPhase::Capture
270 && !window.has_active_prompt()
271 && !hitbox.contains(&window.mouse_position())
272 {
273 (listener)(event, window, cx)
274 }
275 }));
276 }
277
278 pub fn on_mouse_up_out(
284 &mut self,
285 button: MouseButton,
286 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
287 ) {
288 self.mouse_up_listeners
289 .push(Box::new(move |event, phase, hitbox, window, cx| {
290 if phase == DispatchPhase::Capture
291 && event.button == button
292 && !hitbox.is_hovered(window)
293 {
294 (listener)(event, window, cx);
295 }
296 }));
297 }
298
299 pub fn on_mouse_move(
304 &mut self,
305 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
306 ) {
307 self.mouse_move_listeners
308 .push(Box::new(move |event, phase, hitbox, window, cx| {
309 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
310 (listener)(event, window, cx);
311 }
312 }));
313 }
314
315 pub fn on_mouse_exit(
320 &mut self,
321 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
322 ) {
323 self.mouse_exit_listeners
324 .push(Box::new(move |event, phase, hitbox, window, cx| {
325 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
326 (listener)(event, window, cx);
327 }
328 }));
329 }
330
331 pub fn on_file_drop_exit(
339 &mut self,
340 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
341 ) {
342 self.file_drop_exit_listeners
343 .push(Box::new(move |event, phase, hitbox, window, cx| {
344 if phase == DispatchPhase::Bubble
345 && matches!(event, FileDropEvent::Exited)
346 && hitbox.id.is_hovered_ignoring_last_input(window)
347 {
348 (listener)(event, window, cx);
349 }
350 }));
351 }
352
353 pub fn on_drag_move<T>(
361 &mut self,
362 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
363 ) where
364 T: 'static,
365 {
366 self.mouse_move_listeners
367 .push(Box::new(move |event, phase, hitbox, window, cx| {
368 if phase == DispatchPhase::Capture
369 && let Some(drag) = &cx.active_drag
370 && drag.value.as_ref().type_id() == TypeId::of::<T>()
371 {
372 (listener)(
373 &DragMoveEvent {
374 event: event.clone(),
375 bounds: hitbox.bounds,
376 drag: PhantomData,
377 dragged_item: Arc::clone(&drag.value),
378 },
379 window,
380 cx,
381 );
382 }
383 }));
384 }
385
386 pub fn on_scroll(&mut self, listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static) {
391 self.scroll_listeners
392 .push(Box::new(move |event, phase, hitbox, window, cx| {
393 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
394 (listener)(event, window, cx);
395 }
396 }));
397 }
398
399 #[deprecated(note = "renamed to `on_scroll`")]
401 pub fn on_scroll_wheel(
402 &mut self,
403 listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static,
404 ) {
405 self.on_scroll(listener);
406 }
407
408 pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
412 self.pinch_listeners
413 .push(Box::new(move |event, phase, hitbox, window, cx| {
414 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
415 (listener)(event, window, cx);
416 }
417 }));
418 }
419
420 pub fn on_back_gesture(
425 &mut self,
426 listener: impl Fn(&BackGestureEvent, &mut Window, &mut App) + 'static,
427 ) {
428 self.back_gesture_listeners
429 .push(Box::new(move |event, phase, hitbox, window, cx| {
430 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
431 (listener)(event, window, cx);
432 window.prevent_default();
433 cx.stop_propagation();
434 }
435 }));
436 }
437
438 pub fn capture_pinch(
442 &mut self,
443 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
444 ) {
445 self.pinch_listeners
446 .push(Box::new(move |event, phase, _hitbox, window, cx| {
447 if phase == DispatchPhase::Capture {
448 (listener)(event, window, cx);
449 } else {
450 cx.propagate();
451 }
452 }));
453 }
454
455 pub fn capture_action<A: Action>(
460 &mut self,
461 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
462 ) {
463 self.action_listeners.push((
464 TypeId::of::<A>(),
465 Box::new(move |action, phase, window, cx| {
466 let action = action.downcast_ref().unwrap();
467 if phase == DispatchPhase::Capture {
468 (listener)(action, window, cx)
469 } else {
470 cx.propagate();
471 }
472 }),
473 ));
474 }
475
476 #[track_caller]
481 #[inline(always)]
482 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
483 self.action_listeners.push((
484 TypeId::of::<A>(),
485 Box::new(move |action, phase, window, cx| {
486 let action = action.downcast_ref().unwrap();
487 if phase == DispatchPhase::Bubble {
488 (listener)(action, window, cx)
489 }
490 }),
491 ));
492 }
493
494 pub fn on_boxed_action(
501 &mut self,
502 action: &dyn Action,
503 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
504 ) {
505 let action = action.boxed_clone();
506 self.action_listeners.push((
507 (*action).type_id(),
508 Box::new(move |_, phase, window, cx| {
509 if phase == DispatchPhase::Bubble {
510 (listener)(&*action, window, cx)
511 }
512 }),
513 ));
514 }
515
516 pub fn on_key_down(
521 &mut self,
522 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
523 ) {
524 self.key_down_listeners
525 .push(Box::new(move |event, phase, window, cx| {
526 if phase == DispatchPhase::Bubble {
527 (listener)(event, window, cx)
528 }
529 }));
530 }
531
532 pub fn capture_key_down(
537 &mut self,
538 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
539 ) {
540 self.key_down_listeners
541 .push(Box::new(move |event, phase, window, cx| {
542 if phase == DispatchPhase::Capture {
543 listener(event, window, cx)
544 }
545 }));
546 }
547
548 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
553 self.key_up_listeners
554 .push(Box::new(move |event, phase, window, cx| {
555 if phase == DispatchPhase::Bubble {
556 listener(event, window, cx)
557 }
558 }));
559 }
560
561 pub fn capture_key_up(
566 &mut self,
567 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
568 ) {
569 self.key_up_listeners
570 .push(Box::new(move |event, phase, window, cx| {
571 if phase == DispatchPhase::Capture {
572 listener(event, window, cx)
573 }
574 }));
575 }
576
577 pub fn on_modifiers_changed(
582 &mut self,
583 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
584 ) {
585 self.modifiers_changed_listeners.push(Box::new(listener));
586 }
587
588 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
593 self.drop_listeners.push((
594 TypeId::of::<T>(),
595 Box::new(move |dragged_value, window, cx| {
596 listener(dragged_value.downcast_ref().unwrap(), window, cx);
597 }),
598 ));
599 }
600
601 pub fn can_drop(
604 &mut self,
605 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
606 ) {
607 self.can_drop_predicate = Some(Box::new(predicate));
608 }
609
610 #[inline(always)]
615 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
616 where
617 Self: Sized,
618 {
619 self.click_listeners.push(Rc::new(listener));
620 }
621
622 pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
627 where
628 Self: Sized,
629 {
630 self.aux_click_listeners.push(Rc::new(listener));
631 }
632
633 pub fn on_drag<T, W>(
640 &mut self,
641 value: T,
642 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
643 ) where
644 Self: Sized,
645 T: 'static,
646 W: 'static + Render,
647 {
648 debug_assert!(
649 self.drag_listener.is_none(),
650 "calling on_drag more than once on the same element is not supported"
651 );
652 self.drag_listener = Some(DragListener {
653 value: Arc::new(value),
654 render: Box::new(move |value, offset, window, cx| {
655 constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
656 }),
657 external_payload: None,
658 });
659 }
660
661 pub fn external_drag_payload<T>(
666 &mut self,
667 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
668 ) where
669 Self: Sized,
670 T: 'static,
671 {
672 let Some(drag_listener) = self.drag_listener.as_mut() else {
673 debug_assert!(false, "external_drag_payload must be called after on_drag");
674 return;
675 };
676 debug_assert!(
677 drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
678 "external_drag_payload must use the same dragged value type as on_drag"
679 );
680 debug_assert!(
681 drag_listener.external_payload.is_none(),
682 "calling external_drag_payload more than once on the same element is not supported"
683 );
684 drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
685 resolver(value.downcast_ref::<T>()?, window, cx)
686 }));
687 }
688
689 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
700 where
701 Self: Sized,
702 {
703 debug_assert!(
704 self.hover_listener.is_none(),
705 "calling on_hover more than once on the same element is not supported"
706 );
707 self.hover_listener = Some(Box::new(listener));
708 }
709
710 pub fn hover_listener_mode(&mut self, mode: HoverListenerMode)
714 where
715 Self: Sized,
716 {
717 self.hover_listener_mode = mode;
718 }
719
720 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
723 where
724 Self: Sized,
725 {
726 debug_assert!(
727 self.tooltip_builder.is_none(),
728 "calling tooltip more than once on the same element is not supported"
729 );
730 self.tooltip_builder = Some(TooltipBuilder {
731 build: Rc::new(build_tooltip),
732 hoverable: false,
733 });
734 }
735
736 pub fn hoverable_tooltip(
740 &mut self,
741 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
742 ) where
743 Self: Sized,
744 {
745 debug_assert!(
746 self.tooltip_builder.is_none(),
747 "calling tooltip more than once on the same element is not supported"
748 );
749 self.tooltip_builder = Some(TooltipBuilder {
750 build: Rc::new(build_tooltip),
751 hoverable: true,
752 });
753 }
754
755 pub fn tooltip_show_delay(&mut self, delay: Duration) {
760 self.tooltip_show_delay = Some(delay);
761 }
762
763 pub fn occlude_mouse(&mut self) {
768 self.hitbox_behavior = HitboxBehavior::BlockMouse;
769 }
770
771 pub fn window_control_area(&mut self, area: WindowControlArea) {
774 self.window_control = Some(area);
775 }
776
777 pub fn block_mouse_except_scroll(&mut self) {
782 self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
783 }
784
785 fn has_pinch_listeners(&self) -> bool {
786 !self.pinch_listeners.is_empty()
787 }
788}
789
790pub trait InteractiveElement: Sized {
793 fn interactivity(&mut self) -> &mut Interactivity;
795
796 fn group(mut self, group: impl Into<SharedString>) -> Self {
798 self.interactivity().group = Some(group.into());
799 self
800 }
801
802 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
804 self.interactivity().element_id = Some(id.into());
805
806 Stateful { element: self }
807 }
808
809 fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
813 self.interactivity().focusable = true;
814 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
815 self
816 }
817
818 fn tab_stop(mut self, tab_stop: bool) -> Self {
825 self.interactivity().tab_stop = tab_stop;
826 self
827 }
828
829 fn tab_index(mut self, index: isize) -> Self {
834 self.interactivity().focusable = true;
835 self.interactivity().tab_index = Some(index);
836 self.interactivity().tab_stop = true;
837 self
838 }
839
840 fn tab_group(mut self) -> Self {
845 self.interactivity().tab_group = true;
846 if self.interactivity().tab_index.is_none() {
847 self.interactivity().tab_index = Some(0);
848 }
849 self
850 }
851
852 fn key_context<C, E>(mut self, key_context: C) -> Self
855 where
856 C: TryInto<KeyContext, Error = E>,
857 E: std::fmt::Display,
858 {
859 if let Some(key_context) = key_context.try_into().log_err() {
860 self.interactivity().key_context = Some(key_context);
861 }
862 self
863 }
864
865 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
867 debug_assert!(
868 self.interactivity().hover_style.is_none(),
869 "hover style already set"
870 );
871 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
872 self
873 }
874
875 fn group_hover(
877 mut self,
878 group_name: impl Into<SharedString>,
879 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
880 ) -> Self {
881 self.interactivity().group_hover_style = Some(GroupStyle {
882 group: group_name.into(),
883 style: Box::new(f(StyleRefinement::default())),
884 });
885 self
886 }
887
888 #[inline(always)]
893 fn on_mouse_down(
894 mut self,
895 button: MouseButton,
896 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
897 ) -> Self {
898 self.interactivity().on_mouse_down(button, listener);
899 self
900 }
901
902 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
909 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
910 self.interactivity().debug_selector = Some(f());
911 self
912 }
913
914 #[cfg(not(any(test, all(debug_assertions, feature = "test-support"))))]
921 #[inline]
922 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
923 self
924 }
925
926 fn capture_any_mouse_down(
931 mut self,
932 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
933 ) -> Self {
934 self.interactivity().capture_any_mouse_down(listener);
935 self
936 }
937
938 fn on_any_mouse_down(
943 mut self,
944 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
945 ) -> Self {
946 self.interactivity().on_any_mouse_down(listener);
947 self
948 }
949
950 fn on_mouse_up(
955 mut self,
956 button: MouseButton,
957 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
958 ) -> Self {
959 self.interactivity().on_mouse_up(button, listener);
960 self
961 }
962
963 fn capture_any_mouse_up(
968 mut self,
969 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
970 ) -> Self {
971 self.interactivity().capture_any_mouse_up(listener);
972 self
973 }
974
975 fn on_mouse_pressure(
980 mut self,
981 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
982 ) -> Self {
983 self.interactivity().on_mouse_pressure(listener);
984 self
985 }
986
987 fn capture_mouse_pressure(
992 mut self,
993 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
994 ) -> Self {
995 self.interactivity().capture_mouse_pressure(listener);
996 self
997 }
998
999 fn on_mouse_down_out(
1005 mut self,
1006 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
1007 ) -> Self {
1008 self.interactivity().on_mouse_down_out(listener);
1009 self
1010 }
1011
1012 fn on_mouse_up_out(
1018 mut self,
1019 button: MouseButton,
1020 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
1021 ) -> Self {
1022 self.interactivity().on_mouse_up_out(button, listener);
1023 self
1024 }
1025
1026 fn on_mouse_move(
1031 mut self,
1032 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
1033 ) -> Self {
1034 self.interactivity().on_mouse_move(listener);
1035 self
1036 }
1037
1038 fn on_mouse_exit(
1043 mut self,
1044 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
1045 ) -> Self {
1046 self.interactivity().on_mouse_exit(listener);
1047 self
1048 }
1049
1050 fn on_file_drop_exit(
1058 mut self,
1059 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
1060 ) -> Self {
1061 self.interactivity().on_file_drop_exit(listener);
1062 self
1063 }
1064
1065 fn on_drag_move<T: 'static>(
1073 mut self,
1074 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
1075 ) -> Self {
1076 self.interactivity().on_drag_move(listener);
1077 self
1078 }
1079
1080 fn on_scroll(
1085 mut self,
1086 listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static,
1087 ) -> Self {
1088 self.interactivity().on_scroll(listener);
1089 self
1090 }
1091
1092 #[deprecated(note = "renamed to `on_scroll`")]
1094 fn on_scroll_wheel(
1095 self,
1096 listener: impl Fn(&ScrollEvent, &mut Window, &mut App) + 'static,
1097 ) -> Self {
1098 self.on_scroll(listener)
1099 }
1100
1101 fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
1106 self.interactivity().on_pinch(listener);
1107 self
1108 }
1109
1110 fn on_back_gesture(
1117 mut self,
1118 listener: impl Fn(&BackGestureEvent, &mut Window, &mut App) + 'static,
1119 ) -> Self {
1120 self.interactivity().on_back_gesture(listener);
1121 self
1122 }
1123
1124 fn capture_pinch(
1129 mut self,
1130 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
1131 ) -> Self {
1132 self.interactivity().capture_pinch(listener);
1133 self
1134 }
1135 fn capture_action<A: Action>(
1140 mut self,
1141 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1142 ) -> Self {
1143 self.interactivity().capture_action(listener);
1144 self
1145 }
1146
1147 #[track_caller]
1152 #[inline(always)]
1153 fn on_action<A: Action>(
1154 mut self,
1155 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1156 ) -> Self {
1157 self.interactivity().on_action(listener);
1158 self
1159 }
1160
1161 fn on_boxed_action(
1168 mut self,
1169 action: &dyn Action,
1170 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1171 ) -> Self {
1172 self.interactivity().on_boxed_action(action, listener);
1173 self
1174 }
1175
1176 fn on_key_down(
1181 mut self,
1182 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1183 ) -> Self {
1184 self.interactivity().on_key_down(listener);
1185 self
1186 }
1187
1188 fn capture_key_down(
1193 mut self,
1194 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1195 ) -> Self {
1196 self.interactivity().capture_key_down(listener);
1197 self
1198 }
1199
1200 fn on_key_up(
1205 mut self,
1206 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1207 ) -> Self {
1208 self.interactivity().on_key_up(listener);
1209 self
1210 }
1211
1212 fn capture_key_up(
1217 mut self,
1218 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1219 ) -> Self {
1220 self.interactivity().capture_key_up(listener);
1221 self
1222 }
1223
1224 #[inline(always)]
1229 fn on_modifiers_changed(
1230 mut self,
1231 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1232 ) -> Self {
1233 self.interactivity().on_modifiers_changed(listener);
1234 self
1235 }
1236
1237 fn drag_over<S: 'static>(
1239 mut self,
1240 f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1241 ) -> Self {
1242 self.interactivity().drag_over_styles.push((
1243 TypeId::of::<S>(),
1244 Box::new(move |currently_dragged: &dyn Any, window, cx| {
1245 f(
1246 StyleRefinement::default(),
1247 currently_dragged.downcast_ref::<S>().unwrap(),
1248 window,
1249 cx,
1250 )
1251 }),
1252 ));
1253 self
1254 }
1255
1256 fn group_drag_over<S: 'static>(
1258 mut self,
1259 group_name: impl Into<SharedString>,
1260 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1261 ) -> Self {
1262 self.interactivity().group_drag_over_styles.push((
1263 TypeId::of::<S>(),
1264 GroupStyle {
1265 group: group_name.into(),
1266 style: Box::new(f(StyleRefinement::default())),
1267 },
1268 ));
1269 self
1270 }
1271
1272 fn on_drop<T: 'static>(
1277 mut self,
1278 listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1279 ) -> Self {
1280 self.interactivity().on_drop(listener);
1281 self
1282 }
1283
1284 fn can_drop(
1287 mut self,
1288 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1289 ) -> Self {
1290 self.interactivity().can_drop(predicate);
1291 self
1292 }
1293
1294 fn occlude(mut self) -> Self {
1298 self.interactivity().occlude_mouse();
1299 self
1300 }
1301
1302 fn window_control_area(mut self, area: WindowControlArea) -> Self {
1305 self.interactivity().window_control_area(area);
1306 self
1307 }
1308
1309 fn block_mouse_except_scroll(mut self) -> Self {
1314 self.interactivity().block_mouse_except_scroll();
1315 self
1316 }
1317
1318 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1321 where
1322 Self: Sized,
1323 {
1324 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1325 self
1326 }
1327
1328 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1331 where
1332 Self: Sized,
1333 {
1334 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1335 self
1336 }
1337
1338 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1343 where
1344 Self: Sized,
1345 {
1346 self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1347 self
1348 }
1349}
1350
1351pub trait StatefulInteractiveElement: InteractiveElement {
1354 fn role(mut self, role: accesskit::Role) -> Self {
1358 debug_assert!(
1359 role != accesskit::Role::GenericContainer,
1360 "GenericContainer is filtered out of the a11y tree and has no effect"
1361 );
1362 self.interactivity().override_role = Some(role);
1363 self
1364 }
1365
1366 fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self {
1374 self.interactivity().aria.author_id = Some(id.into());
1375 self
1376 }
1377
1378 fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1380 self.interactivity().aria.label = Some(label.into());
1381 self
1382 }
1383
1384 fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
1389 self.interactivity().aria.description = Some(description.into());
1390 self
1391 }
1392
1393 fn aria_keyshortcuts(mut self, keyshortcuts: impl Into<SharedString>) -> Self {
1399 self.interactivity().aria.keyshortcuts = Some(keyshortcuts.into());
1400 self
1401 }
1402
1403 fn aria_active_descendant(mut self) -> Self {
1419 self.interactivity().report_active_descendant_focus = true;
1420 self
1421 }
1422
1423 fn a11y_synthetic_children(
1433 mut self,
1434 f: impl FnOnce(&mut crate::A11ySubtreeBuilder) + 'static,
1435 ) -> Self {
1436 self.interactivity().a11y_synthetic_children = Some(Box::new(f));
1437 self
1438 }
1439
1440 fn aria_selected(mut self, selected: bool) -> Self {
1442 self.interactivity().aria.selected = Some(selected);
1443 self
1444 }
1445
1446 fn aria_expanded(mut self, expanded: bool) -> Self {
1448 self.interactivity().aria.expanded = Some(expanded);
1449 self
1450 }
1451
1452 fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1454 self.interactivity().aria.toggled = Some(toggled);
1455 self
1456 }
1457
1458 fn aria_numeric_value(mut self, value: f64) -> Self {
1460 self.interactivity().aria.numeric_value = Some(value);
1461 self
1462 }
1463
1464 fn aria_numeric_value_step(mut self, step: f64) -> Self {
1467 self.interactivity().aria.numeric_value_step = Some(step);
1468 self
1469 }
1470
1471 fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
1474 self.interactivity().aria.value = Some(value.into());
1475 self
1476 }
1477
1478 fn aria_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1481 self.interactivity().aria.placeholder = Some(placeholder.into());
1482 self
1483 }
1484
1485 fn aria_min_numeric_value(mut self, value: f64) -> Self {
1487 self.interactivity().aria.min_numeric_value = Some(value);
1488 self
1489 }
1490
1491 fn aria_max_numeric_value(mut self, value: f64) -> Self {
1493 self.interactivity().aria.max_numeric_value = Some(value);
1494 self
1495 }
1496
1497 fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1499 self.interactivity().aria.orientation = Some(orientation);
1500 self
1501 }
1502
1503 fn aria_level(mut self, level: usize) -> Self {
1505 self.interactivity().aria.level = Some(level);
1506 self
1507 }
1508
1509 fn aria_position_in_set(mut self, position: usize) -> Self {
1511 self.interactivity().aria.position_in_set = Some(position);
1512 self
1513 }
1514
1515 fn aria_size_of_set(mut self, size: usize) -> Self {
1517 self.interactivity().aria.size_of_set = Some(size);
1518 self
1519 }
1520
1521 fn aria_row_index(mut self, index: usize) -> Self {
1523 self.interactivity().aria.row_index = Some(index);
1524 self
1525 }
1526
1527 fn aria_column_index(mut self, index: usize) -> Self {
1529 self.interactivity().aria.column_index = Some(index);
1530 self
1531 }
1532
1533 fn aria_row_count(mut self, count: usize) -> Self {
1535 self.interactivity().aria.row_count = Some(count);
1536 self
1537 }
1538
1539 fn aria_column_count(mut self, count: usize) -> Self {
1541 self.interactivity().aria.column_count = Some(count);
1542 self
1543 }
1544
1545 #[inline(always)]
1550 fn on_a11y_action(
1551 mut self,
1552 action: accesskit::Action,
1553 listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1554 + 'static,
1555 ) -> Self {
1556 self.interactivity()
1557 .a11y_action_listeners
1558 .push((action, Box::new(listener)));
1559 self
1560 }
1561
1562 fn focusable(mut self) -> Self {
1564 self.interactivity().focusable = true;
1565 self
1566 }
1567
1568 fn overflow_scroll(mut self) -> Self {
1570 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1571 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1572 self
1573 }
1574
1575 fn overflow_x_scroll(mut self) -> Self {
1577 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1578 self
1579 }
1580
1581 fn overflow_y_scroll(mut self) -> Self {
1583 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1584 self
1585 }
1586
1587 fn restrict_scroll_to_axis(mut self) -> Self {
1591 self.interactivity().base_style.restrict_scroll_to_axis = Some(true);
1592 self
1593 }
1594
1595 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1597 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1598 self
1599 }
1600
1601 fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1603 self.interactivity().scroll_anchor = scroll_anchor;
1604 self
1605 }
1606
1607 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1609 where
1610 Self: Sized,
1611 {
1612 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1613 self
1614 }
1615
1616 fn group_active(
1618 mut self,
1619 group_name: impl Into<SharedString>,
1620 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1621 ) -> Self
1622 where
1623 Self: Sized,
1624 {
1625 self.interactivity().group_active_style = Some(GroupStyle {
1626 group: group_name.into(),
1627 style: Box::new(f(StyleRefinement::default())),
1628 });
1629 self
1630 }
1631
1632 #[inline(always)]
1637 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1638 where
1639 Self: Sized,
1640 {
1641 self.interactivity().on_click(listener);
1642 self
1643 }
1644
1645 fn on_aux_click(
1650 mut self,
1651 listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1652 ) -> Self
1653 where
1654 Self: Sized,
1655 {
1656 self.interactivity().on_aux_click(listener);
1657 self
1658 }
1659
1660 fn on_drag<T, W>(
1668 mut self,
1669 value: T,
1670 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1671 ) -> Self
1672 where
1673 Self: Sized,
1674 T: 'static,
1675 W: 'static + Render,
1676 {
1677 self.interactivity().on_drag(value, constructor);
1678 self
1679 }
1680
1681 fn external_drag_payload<T>(
1687 mut self,
1688 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
1689 ) -> Self
1690 where
1691 Self: Sized,
1692 T: 'static,
1693 {
1694 self.interactivity().external_drag_payload(resolver);
1695 self
1696 }
1697
1698 fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1709 where
1710 Self: Sized,
1711 {
1712 self.interactivity().on_hover(listener);
1713 self
1714 }
1715
1716 fn hover_listener_mode(mut self, mode: HoverListenerMode) -> Self
1720 where
1721 Self: Sized,
1722 {
1723 self.interactivity().hover_listener_mode(mode);
1724 self
1725 }
1726
1727 fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1730 where
1731 Self: Sized,
1732 {
1733 self.interactivity().tooltip(build_tooltip);
1734 self
1735 }
1736
1737 fn hoverable_tooltip(
1741 mut self,
1742 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1743 ) -> Self
1744 where
1745 Self: Sized,
1746 {
1747 self.interactivity().hoverable_tooltip(build_tooltip);
1748 self
1749 }
1750
1751 fn tooltip_show_delay(mut self, delay: Duration) -> Self
1756 where
1757 Self: Sized,
1758 {
1759 self.interactivity().tooltip_show_delay(delay);
1760 self
1761 }
1762}
1763
1764pub(crate) type MouseDownListener =
1765 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1766pub(crate) type MouseUpListener =
1767 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1768pub(crate) type MousePressureListener =
1769 Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1770pub(crate) type MouseMoveListener =
1771 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1772pub(crate) type MouseExitListener =
1773 Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1774
1775pub(crate) type FileDropExitListener =
1776 Box<dyn Fn(&FileDropEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1777
1778pub(crate) type ScrollListener =
1779 Box<dyn Fn(&ScrollEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1780
1781pub(crate) type PinchListener =
1782 Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1783
1784pub(crate) type BackGestureListener =
1785 Box<dyn Fn(&BackGestureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1786
1787pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1788
1789#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1792pub enum HoverListenerMode {
1793 #[default]
1796 InputModalityAware,
1797 InputModalityIndependent,
1801}
1802
1803impl HoverListenerMode {
1804 fn is_hovered(self, hitbox: &Hitbox, window: &Window) -> bool {
1805 match self {
1806 Self::InputModalityAware => hitbox.is_hovered(window),
1807 Self::InputModalityIndependent => hitbox.id.is_hovered_ignoring_last_input(window),
1808 }
1809 }
1810}
1811
1812pub(crate) struct DragListener {
1813 value: Arc<dyn Any>,
1814 render: Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>,
1815 external_payload: Option<ExternalDragPayloadResolver>,
1816}
1817
1818type ExternalDragPayloadResolver =
1819 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
1820
1821type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1822
1823type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1824
1825pub(crate) struct TooltipBuilder {
1826 build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1827 hoverable: bool,
1828}
1829
1830pub(crate) type KeyDownListener =
1831 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1832
1833pub(crate) type KeyUpListener =
1834 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1835
1836pub(crate) type ModifiersChangedListener =
1837 Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1838
1839pub(crate) type ActionListener =
1840 Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1841
1842#[track_caller]
1844pub fn div() -> Div {
1845 #[allow(unused_mut)]
1846 let mut interactivity = InteractivityBox::new();
1847 #[cfg(any(feature = "inspector", debug_assertions))]
1848 {
1849 interactivity.source_location = Some(core::panic::Location::caller());
1850 }
1851 Div {
1852 interactivity,
1853 children: SmallVec::default(),
1854 prepaint_listener: None,
1855 image_cache: None,
1856 prepaint_order_fn: None,
1857 }
1858}
1859
1860enum InteractivityBox {
1864 Arena(crate::ArenaBox<Interactivity>),
1865 Heap(Box<Interactivity>),
1866}
1867
1868impl InteractivityBox {
1869 #[inline]
1871 fn new() -> Self {
1872 if crate::window::draw_in_progress() {
1873 Self::Arena(crate::window::with_element_arena(|arena| {
1874 arena.alloc(Interactivity::default)
1875 }))
1876 } else {
1877 Self::Heap(Box::default())
1878 }
1879 }
1880}
1881
1882impl std::ops::Deref for InteractivityBox {
1883 type Target = Interactivity;
1884
1885 #[inline]
1886 fn deref(&self) -> &Interactivity {
1887 match self {
1888 Self::Arena(interactivity) => interactivity,
1889 Self::Heap(interactivity) => interactivity,
1890 }
1891 }
1892}
1893
1894impl std::ops::DerefMut for InteractivityBox {
1895 #[inline]
1896 fn deref_mut(&mut self) -> &mut Interactivity {
1897 match self {
1898 Self::Arena(interactivity) => interactivity,
1899 Self::Heap(interactivity) => interactivity,
1900 }
1901 }
1902}
1903
1904pub struct Div {
1906 interactivity: InteractivityBox,
1909 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1910 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1911 image_cache: Option<Box<dyn ImageCacheProvider>>,
1912 prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1913}
1914
1915impl Div {
1916 pub fn on_children_prepainted(
1919 mut self,
1920 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1921 ) -> Self {
1922 self.prepaint_listener = Some(Box::new(listener));
1923 self
1924 }
1925
1926 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1928 self.image_cache = Some(Box::new(cache));
1929 self
1930 }
1931
1932 pub fn with_dynamic_prepaint_order(
1941 mut self,
1942 order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1943 ) -> Self {
1944 self.prepaint_order_fn = Some(Box::new(order_fn));
1945 self
1946 }
1947}
1948
1949pub struct DivFrameState {
1956 child_layout_ids: SmallVec<[LayoutId; 2]>,
1957}
1958
1959#[derive(Clone)]
1961pub struct DivInspectorState {
1962 #[cfg(any(feature = "inspector", debug_assertions))]
1966 pub base_style: Box<StyleRefinement>,
1967 pub bounds: Bounds<Pixels>,
1969 pub content_size: Size<Pixels>,
1971}
1972
1973impl Styled for Div {
1974 fn style(&mut self) -> &mut StyleRefinement {
1975 &mut self.interactivity.base_style
1976 }
1977}
1978
1979impl InteractiveElement for Div {
1980 fn interactivity(&mut self) -> &mut Interactivity {
1981 &mut self.interactivity
1982 }
1983}
1984
1985impl ParentElement for Div {
1986 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1987 #[cfg(feature = "stacker")]
1988 self.children
1989 .extend(elements.into_iter().map(StackSafe::new));
1990 #[cfg(not(feature = "stacker"))]
1991 self.children.extend(elements);
1992 }
1993}
1994
1995impl Element for Div {
1996 type RequestLayoutState = DivFrameState;
1997 type PrepaintState = Option<Hitbox>;
1998
1999 fn id(&self) -> Option<ElementId> {
2000 self.interactivity.element_id.clone()
2001 }
2002
2003 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
2004 self.interactivity.source_location()
2005 }
2006
2007 fn a11y_role(&self) -> Option<accesskit::Role> {
2008 self.interactivity
2011 .override_role
2012 .filter(|role| *role != accesskit::Role::GenericContainer)
2013 }
2014
2015 fn write_a11y_info(&self, node: &mut accesskit::Node) {
2016 self.interactivity.write_a11y_info(node);
2017 }
2018
2019 fn a11y_synthetic_children(
2020 &mut self,
2021 _prepaint: &mut Self::PrepaintState,
2022 builder: &mut crate::A11ySubtreeBuilder,
2023 ) {
2024 if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
2025 f(builder);
2026 }
2027 }
2028
2029 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2030 fn request_layout(
2031 &mut self,
2032 global_id: Option<&GlobalElementId>,
2033 inspector_id: Option<&InspectorElementId>,
2034 window: &mut Window,
2035 cx: &mut App,
2036 ) -> (LayoutId, Self::RequestLayoutState) {
2037 let mut child_layout_ids = SmallVec::new();
2038 let image_cache = self
2039 .image_cache
2040 .as_mut()
2041 .map(|provider| provider.provide(window, cx));
2042
2043 let layout_id = window.with_image_cache(image_cache, |window| {
2044 self.interactivity.request_layout(
2045 global_id,
2046 inspector_id,
2047 window,
2048 cx,
2049 |style, window, cx| {
2050 window.with_text_style(style.text_style().cloned(), |window| {
2051 child_layout_ids = self
2052 .children
2053 .iter_mut()
2054 .map(|child| child.request_layout(window, cx))
2055 .collect::<SmallVec<_>>();
2056 window.request_layout(style, child_layout_ids.iter().copied(), cx)
2057 })
2058 },
2059 )
2060 });
2061
2062 (layout_id, DivFrameState { child_layout_ids })
2063 }
2064
2065 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2066 fn prepaint(
2067 &mut self,
2068 global_id: Option<&GlobalElementId>,
2069 inspector_id: Option<&InspectorElementId>,
2070 bounds: Bounds<Pixels>,
2071 request_layout: &mut Self::RequestLayoutState,
2072 window: &mut Window,
2073 cx: &mut App,
2074 ) -> Option<Hitbox> {
2075 let image_cache = self
2076 .image_cache
2077 .as_mut()
2078 .map(|provider| provider.provide(window, cx));
2079
2080 let has_prepaint_listener = self.prepaint_listener.is_some();
2081 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
2082 request_layout.child_layout_ids.len()
2083 } else {
2084 0
2085 });
2086
2087 let mut child_min = point(Pixels::MAX, Pixels::MAX);
2088 let mut child_max = Point::default();
2089 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
2090 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
2091 }
2092 let content_size = if request_layout.child_layout_ids.is_empty() {
2093 bounds.size
2094 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2095 let mut state = scroll_handle.0.borrow_mut();
2096 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
2097 for child_layout_id in &request_layout.child_layout_ids {
2098 let child_bounds = window.layout_bounds(*child_layout_id);
2099 child_min = child_min.min(&child_bounds.origin);
2100 child_max = child_max.max(&child_bounds.bottom_right());
2101 state.child_bounds.push(child_bounds);
2102 }
2103 (child_max - child_min).into()
2104 } else {
2105 for child_layout_id in &request_layout.child_layout_ids {
2106 let child_bounds = window.layout_bounds(*child_layout_id);
2107 child_min = child_min.min(&child_bounds.origin);
2108 child_max = child_max.max(&child_bounds.bottom_right());
2109
2110 if has_prepaint_listener {
2111 children_bounds.push(child_bounds);
2112 }
2113 }
2114 (child_max - child_min).into()
2115 };
2116
2117 self.interactivity.prepaint(
2118 global_id,
2119 inspector_id,
2120 bounds,
2121 content_size,
2122 window,
2123 cx,
2124 |style, scroll_offset, hitbox, window, cx| {
2125 if style.display == Display::None {
2127 return hitbox;
2128 }
2129
2130 window.with_image_cache(image_cache, |window| {
2131 window.with_element_offset(scroll_offset, |window| {
2132 if let Some(order_fn) = &self.prepaint_order_fn {
2133 let order = order_fn(window, cx);
2134 for idx in order {
2135 if let Some(child) = self.children.get_mut(idx) {
2136 child.prepaint(window, cx);
2137 }
2138 }
2139 } else {
2140 for child in &mut self.children {
2141 child.prepaint(window, cx);
2142 }
2143 }
2144 });
2145
2146 if let Some(listener) = self.prepaint_listener.as_ref() {
2147 listener(children_bounds, window, cx);
2148 }
2149 });
2150
2151 hitbox
2152 },
2153 )
2154 }
2155
2156 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2157 fn paint(
2158 &mut self,
2159 global_id: Option<&GlobalElementId>,
2160 inspector_id: Option<&InspectorElementId>,
2161 bounds: Bounds<Pixels>,
2162 _request_layout: &mut Self::RequestLayoutState,
2163 hitbox: &mut Option<Hitbox>,
2164 window: &mut Window,
2165 cx: &mut App,
2166 ) {
2167 let image_cache = self
2168 .image_cache
2169 .as_mut()
2170 .map(|provider| provider.provide(window, cx));
2171
2172 window.with_image_cache(image_cache, |window| {
2173 self.interactivity.paint(
2174 global_id,
2175 inspector_id,
2176 bounds,
2177 hitbox.as_ref(),
2178 window,
2179 cx,
2180 |style, window, cx| {
2181 if style.display == Display::None {
2183 return;
2184 }
2185
2186 for child in &mut self.children {
2187 child.paint(window, cx);
2188 }
2189 },
2190 )
2191 });
2192 }
2193}
2194
2195#[derive(Default)]
2196pub(crate) struct AriaProperties {
2197 pub(crate) author_id: Option<SharedString>,
2198 pub(crate) label: Option<SharedString>,
2199 pub(crate) description: Option<SharedString>,
2200 pub(crate) keyshortcuts: Option<SharedString>,
2201 pub(crate) selected: Option<bool>,
2202 pub(crate) expanded: Option<bool>,
2203 pub(crate) toggled: Option<accesskit::Toggled>,
2204 pub(crate) numeric_value: Option<f64>,
2205 pub(crate) min_numeric_value: Option<f64>,
2206 pub(crate) max_numeric_value: Option<f64>,
2207 pub(crate) numeric_value_step: Option<f64>,
2208 pub(crate) value: Option<SharedString>,
2209 pub(crate) placeholder: Option<SharedString>,
2210 pub(crate) orientation: Option<accesskit::Orientation>,
2211 pub(crate) level: Option<usize>,
2212 pub(crate) position_in_set: Option<usize>,
2213 pub(crate) size_of_set: Option<usize>,
2214 pub(crate) row_index: Option<usize>,
2215 pub(crate) column_index: Option<usize>,
2216 pub(crate) row_count: Option<usize>,
2217 pub(crate) column_count: Option<usize>,
2218}
2219
2220#[derive(Default)]
2223pub struct Interactivity {
2224 pub element_id: Option<ElementId>,
2226 pub active: Option<bool>,
2228 pub hovered: Option<bool>,
2231 pub(crate) tooltip_id: Option<TooltipId>,
2232 pub(crate) content_size: Size<Pixels>,
2233 pub(crate) key_context: Option<KeyContext>,
2234 pub(crate) focusable: bool,
2235 pub(crate) tracked_focus_handle: Option<FocusHandle>,
2236 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2237 pub(crate) scroll_anchor: Option<ScrollAnchor>,
2238 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2239 pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2240 pub(crate) group: Option<SharedString>,
2241 pub base_style: Box<StyleRefinement>,
2244 pub(crate) focus_style: Option<Box<StyleRefinement>>,
2245 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2246 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2247 pub(crate) hover_style: Option<Box<StyleRefinement>>,
2248 pub(crate) group_hover_style: Option<GroupStyle>,
2249 pub(crate) active_style: Option<Box<StyleRefinement>>,
2250 pub(crate) group_active_style: Option<GroupStyle>,
2251 pub(crate) drag_over_styles: Vec<(
2252 TypeId,
2253 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2254 )>,
2255 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
2256 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
2257 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
2258 pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
2259 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
2260 pub(crate) mouse_exit_listeners: Vec<MouseExitListener>,
2261 pub(crate) file_drop_exit_listeners: Vec<FileDropExitListener>,
2262 pub(crate) scroll_listeners: Vec<ScrollListener>,
2263 pub(crate) pinch_listeners: Vec<PinchListener>,
2264 pub(crate) back_gesture_listeners: Vec<BackGestureListener>,
2265 pub(crate) key_down_listeners: Vec<KeyDownListener>,
2266 pub(crate) key_up_listeners: Vec<KeyUpListener>,
2267 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
2268 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
2269 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
2270 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
2271 pub(crate) click_listeners: Vec<ClickListener>,
2272 pub(crate) aux_click_listeners: Vec<ClickListener>,
2273 pub(crate) drag_listener: Option<DragListener>,
2274 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2275 pub(crate) hover_listener_mode: HoverListenerMode,
2276 pub(crate) tooltip_builder: Option<TooltipBuilder>,
2277 pub(crate) tooltip_show_delay: Option<Duration>,
2278 pub(crate) window_control: Option<WindowControlArea>,
2279 pub(crate) hitbox_behavior: HitboxBehavior,
2280 pub(crate) tab_index: Option<isize>,
2281 pub(crate) tab_group: bool,
2282 pub(crate) tab_stop: bool,
2283
2284 pub(crate) a11y_action_listeners:
2285 Vec<(accesskit::Action, crate::window::a11y::A11yActionListener)>,
2286 pub(crate) a11y_synthetic_children: Option<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2287 pub(crate) report_active_descendant_focus: bool,
2288 pub(crate) override_role: Option<accesskit::Role>,
2289 pub(crate) aria: AriaProperties,
2290
2291 #[cfg(any(feature = "inspector", debug_assertions))]
2292 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2293
2294 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2295 pub(crate) debug_selector: Option<String>,
2296}
2297
2298impl Interactivity {
2299 pub fn request_layout(
2301 &mut self,
2302 global_id: Option<&GlobalElementId>,
2303 _inspector_id: Option<&InspectorElementId>,
2304 window: &mut Window,
2305 cx: &mut App,
2306 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2307 ) -> LayoutId {
2308 #[cfg(any(feature = "inspector", debug_assertions))]
2309 window.with_inspector_state(
2310 _inspector_id,
2311 cx,
2312 |inspector_state: &mut Option<DivInspectorState>, _window| {
2313 if let Some(inspector_state) = inspector_state {
2314 self.base_style = inspector_state.base_style.clone();
2315 } else {
2316 *inspector_state = Some(DivInspectorState {
2317 base_style: self.base_style.clone(),
2318 bounds: Default::default(),
2319 content_size: Default::default(),
2320 })
2321 }
2322 },
2323 );
2324
2325 window.with_optional_element_state::<InteractiveElementState, _>(
2326 global_id,
2327 |element_state, window| {
2328 let mut element_state =
2329 element_state.map(|element_state| element_state.unwrap_or_default());
2330
2331 if let Some(element_state) = element_state.as_ref()
2332 && cx.has_active_drag()
2333 {
2334 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2335 *pending_mouse_down.borrow_mut() = None;
2336 }
2337 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2338 *clicked_state.borrow_mut() = ElementClickedState::default();
2339 }
2340 }
2341
2342 if self.focusable
2347 && self.tracked_focus_handle.is_none()
2348 && let Some(element_state) = element_state.as_mut()
2349 {
2350 let mut handle = element_state
2351 .focus_handle
2352 .get_or_insert_with(|| cx.focus_handle())
2353 .clone()
2354 .tab_stop(self.tab_stop);
2355
2356 if let Some(index) = self.tab_index {
2357 handle = handle.tab_index(index);
2358 }
2359
2360 self.tracked_focus_handle = Some(handle);
2361 }
2362
2363 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2364 let scroll_handle_state = scroll_handle.0.borrow();
2365 self.scroll_offset = Some(scroll_handle_state.offset.clone());
2366 self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2367 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2368 || self.base_style.overflow.y == Some(Overflow::Scroll))
2369 && let Some(element_state) = element_state.as_mut()
2370 {
2371 self.scroll_offset = Some(
2372 element_state
2373 .scroll_offset
2374 .get_or_insert_with(Rc::default)
2375 .clone(),
2376 );
2377 self.ongoing_scroll = Some(
2378 element_state
2379 .ongoing_scroll
2380 .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2381 .clone(),
2382 );
2383 }
2384
2385 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2386 let layout_id = f(style, window, cx);
2387 (layout_id, element_state)
2388 },
2389 )
2390 }
2391
2392 pub fn prepaint<R>(
2394 &mut self,
2395 global_id: Option<&GlobalElementId>,
2396 _inspector_id: Option<&InspectorElementId>,
2397 bounds: Bounds<Pixels>,
2398 content_size: Size<Pixels>,
2399 window: &mut Window,
2400 cx: &mut App,
2401 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2402 ) -> R {
2403 self.content_size = content_size;
2404
2405 #[cfg(any(feature = "inspector", debug_assertions))]
2406 window.with_inspector_state(
2407 _inspector_id,
2408 cx,
2409 |inspector_state: &mut Option<DivInspectorState>, _window| {
2410 if let Some(inspector_state) = inspector_state {
2411 inspector_state.bounds = bounds;
2412 inspector_state.content_size = content_size;
2413 }
2414 },
2415 );
2416
2417 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2418 window.set_focus_handle(focus_handle, cx);
2419
2420 if window.a11y.is_active() {
2421 if let Some(global_id) = global_id {
2422 let node_id = global_id.accesskit_node_id();
2423 window.a11y.set_focusable(node_id, focus_handle.id);
2424 if focus_handle.is_focused(window) {
2425 window.a11y.set_focus(node_id);
2426 }
2427 } else if focus_handle.is_focused(window) {
2428 window
2432 .a11y
2433 .note_focus_without_node(focus_handle.id, "it has no element id");
2434 }
2435 }
2436 }
2437
2438 if self.report_active_descendant_focus && window.a11y.is_active() {
2439 if let Some(global_id) = global_id {
2440 window
2441 .a11y
2442 .set_active_descendant(global_id.accesskit_node_id());
2443 }
2444 }
2445 window.with_optional_element_state::<InteractiveElementState, _>(
2446 global_id,
2447 |element_state, window| {
2448 let mut element_state =
2449 element_state.map(|element_state| element_state.unwrap_or_default());
2450 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2451
2452 if let Some(element_state) = element_state.as_mut() {
2453 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2454 let clicked_state = clicked_state.borrow();
2455 self.active = Some(clicked_state.element);
2456 }
2457 if self.hover_style.is_some() || self.group_hover_style.is_some() {
2458 element_state
2459 .hover_state
2460 .get_or_insert_with(Default::default);
2461 }
2462 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2463 if self.tooltip_builder.is_some() {
2464 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2465 } else {
2466 if let Some(long_press_tooltip_active) =
2468 element_state.long_press_tooltip_active.as_ref()
2469 {
2470 long_press_tooltip_active.set(false);
2471 }
2472 element_state.active_tooltip.take();
2473 }
2474 }
2475 }
2476
2477 window.with_text_style(style.text_style().cloned(), |window| {
2478 window.with_content_mask(
2479 style.overflow_mask(bounds, window.rem_size()),
2480 |window| {
2481 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2482 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2483 } else {
2484 None
2485 };
2486
2487 let scroll_offset =
2488 self.clamp_scroll_position(bounds, &style, window, cx);
2489 let result = window.with_element_opacity(style.opacity, |window| {
2490 f(&style, scroll_offset, hitbox, window, cx)
2491 });
2492 (result, element_state)
2493 },
2494 )
2495 })
2496 },
2497 )
2498 }
2499
2500 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2501 self.hitbox_behavior != HitboxBehavior::Normal
2502 || self.window_control.is_some()
2503 || style.mouse_cursor.is_some()
2504 || self.group.is_some()
2505 || self.scroll_offset.is_some()
2506 || self.tracked_focus_handle.is_some()
2507 || self.hover_style.is_some()
2508 || self.group_hover_style.is_some()
2509 || self.hover_listener.is_some()
2510 || !self.mouse_up_listeners.is_empty()
2511 || !self.mouse_pressure_listeners.is_empty()
2512 || !self.mouse_down_listeners.is_empty()
2513 || !self.mouse_move_listeners.is_empty()
2514 || !self.mouse_exit_listeners.is_empty()
2515 || !self.file_drop_exit_listeners.is_empty()
2516 || !self.click_listeners.is_empty()
2517 || !self.aux_click_listeners.is_empty()
2518 || !self.scroll_listeners.is_empty()
2519 || self.has_pinch_listeners()
2520 || !self.back_gesture_listeners.is_empty()
2521 || self.drag_listener.is_some()
2522 || !self.drop_listeners.is_empty()
2523 || !self.drag_over_styles.is_empty()
2524 || self.tooltip_builder.is_some()
2525 || window.is_inspector_picking(cx)
2526 }
2527
2528 fn clamp_scroll_position(
2529 &self,
2530 bounds: Bounds<Pixels>,
2531 style: &Style,
2532 window: &mut Window,
2533 _cx: &mut App,
2534 ) -> Point<Pixels> {
2535 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2536 const ROUNDING_FACTOR: f32 = 100.0;
2537 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2538 }
2539
2540 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2541 let mut scroll_to_bottom = false;
2542 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2543 {
2544 let mut scroll_handle_state = scroll_handle.0.borrow_mut();
2545 scroll_handle_state.overflow = style.overflow;
2546 scroll_handle_state.bounds = bounds;
2550 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2551 }
2552 scroll_handle.scroll_to_active_item();
2553 }
2554 let tracked_scroll_handle = self
2555 .tracked_scroll_handle
2556 .as_ref()
2557 .map(|handle| handle.0.borrow_mut());
2558
2559 let rem_size = window.rem_size();
2560 let padding = style
2565 .padding
2566 .to_pixels(bounds.size.into(), rem_size)
2567 .map(|edge| window.pixel_snap(*edge));
2568 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2569 let padded_content_size = self.content_size + padding_size;
2576 let scroll_max = Point::from(padded_content_size - bounds.size)
2577 .map(round_to_two_decimals)
2578 .max(&Default::default());
2579 let mut scroll_offset = scroll_offset.borrow_mut();
2582
2583 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2584 if scroll_to_bottom {
2585 scroll_offset.y = -scroll_max.y;
2586 } else {
2587 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2588 }
2589
2590 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2591 scroll_handle_state.max_offset = scroll_max;
2592 scroll_handle_state.bounds = bounds;
2593 }
2594
2595 *scroll_offset
2596 } else {
2597 Point::default()
2598 }
2599 }
2600
2601 pub fn paint(
2610 &mut self,
2611 global_id: Option<&GlobalElementId>,
2612 _inspector_id: Option<&InspectorElementId>,
2613 bounds: Bounds<Pixels>,
2614 hitbox: Option<&Hitbox>,
2615 window: &mut Window,
2616 cx: &mut App,
2617 f: impl FnOnce(&Style, &mut Window, &mut App),
2618 ) {
2619 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2620 window.with_optional_element_state::<InteractiveElementState, _>(
2621 global_id,
2622 |element_state, window| {
2623 let mut element_state =
2624 element_state.map(|element_state| element_state.unwrap_or_default());
2625
2626 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2627
2628 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2629 if let Some(debug_selector) = &self.debug_selector {
2630 window
2631 .next_frame
2632 .record_debug_bounds(debug_selector.clone(), bounds);
2633 }
2634
2635 self.paint_hover_group_handler(window, cx);
2636
2637 if style.visibility == Visibility::Hidden {
2638 return ((), element_state);
2639 }
2640
2641 let mut tab_group = None;
2642 if self.tab_group {
2643 tab_group = self.tab_index;
2644 }
2645
2646 window.with_element_opacity(style.opacity, |window| {
2647 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2648 window.with_text_style(style.text_style().cloned(), |window| {
2649 window.with_content_mask(
2650 style.overflow_mask(bounds, window.rem_size()),
2651 |window| {
2652 window.with_tab_group(tab_group, |window| {
2653 if let Some(focus_handle) = &self.tracked_focus_handle {
2662 window.next_frame.tab_stops.insert(focus_handle);
2663 }
2664 if let Some(hitbox) = hitbox {
2665 #[cfg(debug_assertions)]
2666 self.paint_debug_info(
2667 global_id, hitbox, &style, window, cx,
2668 );
2669
2670 if let Some(drag) = cx.active_drag.as_ref() {
2671 if let Some(mouse_cursor) = drag.cursor_style {
2672 window.set_window_cursor_style(mouse_cursor);
2673 }
2674 } else {
2675 if let Some(mouse_cursor) = style.mouse_cursor {
2676 window.set_cursor_style(mouse_cursor, hitbox);
2677 }
2678 }
2679
2680 if let Some(group) = self.group.clone() {
2681 GroupHitboxes::push(group, hitbox.id, cx);
2682 }
2683
2684 if let Some(area) = self.window_control {
2685 window.insert_window_control_hitbox(
2686 area,
2687 hitbox.clone(),
2688 );
2689 }
2690
2691 self.paint_mouse_listeners(
2692 hitbox,
2693 element_state.as_mut(),
2694 window,
2695 cx,
2696 );
2697 self.paint_scroll_listener(hitbox, &style, window, cx);
2698 }
2699
2700 self.paint_keyboard_listeners(window, cx);
2701
2702 if window.a11y.is_active() {
2703 if let Some(global_id) = global_id {
2704 if !self.a11y_action_listeners.is_empty() {
2705 let node_id = global_id.accesskit_node_id();
2706 for (action, listener) in
2707 self.a11y_action_listeners.drain(..)
2708 {
2709 window.on_a11y_action(
2710 node_id, action, listener,
2711 );
2712 }
2713 }
2714 }
2715 }
2716
2717 f(&style, window, cx);
2718
2719 if let Some(_hitbox) = hitbox {
2720 #[cfg(any(feature = "inspector", debug_assertions))]
2721 window.insert_inspector_hitbox(
2722 _hitbox.id,
2723 _inspector_id,
2724 cx,
2725 );
2726
2727 if let Some(group) = self.group.as_ref() {
2728 GroupHitboxes::pop(group, cx);
2729 }
2730 }
2731 })
2732 },
2733 );
2734 });
2735 });
2736 });
2737
2738 ((), element_state)
2739 },
2740 );
2741 }
2742
2743 #[cfg(debug_assertions)]
2744 fn paint_debug_info(
2745 &self,
2746 global_id: Option<&GlobalElementId>,
2747 hitbox: &Hitbox,
2748 style: &Style,
2749 window: &mut Window,
2750 cx: &mut App,
2751 ) {
2752 use crate::{BorderStyle, TextAlign};
2753
2754 if let Some(global_id) = global_id
2755 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2756 && hitbox.is_hovered(window)
2757 {
2758 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2759 let element_id = format!("{global_id:?}");
2760 let str_len = element_id.len();
2761
2762 let render_debug_text = |window: &mut Window| {
2763 if let Some(text) = window
2764 .text_system()
2765 .shape_text(
2766 element_id.into(),
2767 FONT_SIZE,
2768 &[window.text_style().to_run(str_len)],
2769 None,
2770 None,
2771 )
2772 .ok()
2773 .and_then(|mut text| text.pop())
2774 {
2775 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2776 .ok();
2777
2778 let text_bounds = crate::Bounds {
2779 origin: hitbox.origin,
2780 size: text.size(FONT_SIZE),
2781 };
2782 if let Some(source_location) = self.source_location
2783 && text_bounds.contains(&window.mouse_position())
2784 && window.modifiers().secondary(cx)
2785 {
2786 let secondary_held = window.modifiers().secondary(cx);
2787 window.on_key_event({
2788 move |e: &crate::ModifiersChangedEvent, _phase, window, cx| {
2789 if e.modifiers.secondary(cx) != secondary_held
2790 && text_bounds.contains(&window.mouse_position())
2791 {
2792 window.refresh();
2793 }
2794 }
2795 });
2796
2797 let was_hovered = hitbox.is_hovered(window);
2798 let current_view = window.current_view();
2799 window.on_mouse_event({
2800 let hitbox = hitbox.clone();
2801 move |_: &MouseMoveEvent, phase, window, cx| {
2802 if phase == DispatchPhase::Capture {
2803 let hovered = hitbox.is_hovered(window);
2804 if hovered != was_hovered {
2805 cx.notify(current_view)
2806 }
2807 }
2808 }
2809 });
2810
2811 window.on_mouse_event({
2812 let hitbox = hitbox.clone();
2813 move |e: &crate::MouseDownEvent, phase, window, cx| {
2814 if text_bounds.contains(&e.position)
2815 && phase.capture()
2816 && hitbox.is_hovered(window)
2817 {
2818 cx.stop_propagation();
2819 let Ok(dir) = std::env::current_dir() else {
2820 return;
2821 };
2822
2823 eprintln!(
2824 "This element was created at:\n{}:{}:{}",
2825 dir.join(source_location.file()).to_string_lossy(),
2826 source_location.line(),
2827 source_location.column()
2828 );
2829 }
2830 }
2831 });
2832 window.paint_quad(crate::outline(
2833 crate::Bounds {
2834 origin: hitbox.origin
2835 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2836 size: crate::Size {
2837 width: text_bounds.size.width,
2838 height: crate::px(1.),
2839 },
2840 },
2841 crate::red(),
2842 BorderStyle::default(),
2843 ))
2844 }
2845 }
2846 };
2847
2848 window.with_text_style(
2849 Some(crate::TextStyleRefinement {
2850 color: Some(crate::red()),
2851 line_height: Some(FONT_SIZE.into()),
2852 background_color: Some(crate::white()),
2853 ..Default::default()
2854 }),
2855 render_debug_text,
2856 )
2857 }
2858 }
2859
2860 fn paint_mouse_listeners(
2861 &mut self,
2862 hitbox: &Hitbox,
2863 element_state: Option<&mut InteractiveElementState>,
2864 window: &mut Window,
2865 cx: &mut App,
2866 ) {
2867 let is_focused = self
2868 .tracked_focus_handle
2869 .as_ref()
2870 .map(|handle| handle.is_focused(window))
2871 .unwrap_or(false);
2872
2873 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2877 let hitbox = hitbox.clone();
2878 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2879 if phase == DispatchPhase::Bubble
2880 && hitbox.is_hovered(window)
2881 && !window.default_prevented()
2882 {
2883 window.focus(&focus_handle, cx);
2884 window.prevent_default();
2887 }
2888 });
2889 }
2890
2891 for listener in self.mouse_down_listeners.drain(..) {
2892 let hitbox = hitbox.clone();
2893 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2894 listener(event, phase, &hitbox, window, cx);
2895 })
2896 }
2897
2898 for listener in self.mouse_up_listeners.drain(..) {
2899 let hitbox = hitbox.clone();
2900 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2901 listener(event, phase, &hitbox, window, cx);
2902 })
2903 }
2904
2905 for listener in self.mouse_pressure_listeners.drain(..) {
2906 let hitbox = hitbox.clone();
2907 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2908 listener(event, phase, &hitbox, window, cx);
2909 })
2910 }
2911
2912 for listener in self.mouse_move_listeners.drain(..) {
2913 let hitbox = hitbox.clone();
2914 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2915 listener(event, phase, &hitbox, window, cx);
2916 })
2917 }
2918
2919 for listener in self.mouse_exit_listeners.drain(..) {
2920 let hitbox = hitbox.clone();
2921 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2922 listener(event, phase, &hitbox, window, cx);
2923 })
2924 }
2925
2926 for listener in self.file_drop_exit_listeners.drain(..) {
2927 let hitbox = hitbox.clone();
2928 window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
2929 listener(event, phase, &hitbox, window, cx);
2930 })
2931 }
2932
2933 for listener in self.scroll_listeners.drain(..) {
2934 let hitbox = hitbox.clone();
2935 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
2936 listener(event, phase, &hitbox, window, cx);
2937 })
2938 }
2939
2940 for listener in self.pinch_listeners.drain(..) {
2941 let hitbox = hitbox.clone();
2942 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2943 listener(event, phase, &hitbox, window, cx);
2944 })
2945 }
2946
2947 for listener in self.back_gesture_listeners.drain(..) {
2948 let hitbox = hitbox.clone();
2949 window.on_mouse_event(move |event: &BackGestureEvent, phase, window, cx| {
2950 listener(event, phase, &hitbox, window, cx);
2951 })
2952 }
2953
2954 if self.hover_style.is_some()
2955 || self.base_style.mouse_cursor.is_some()
2956 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2957 {
2958 let hitbox = hitbox.clone();
2959 let hover_state = self.hover_style.as_ref().and_then(|_| {
2960 element_state
2961 .as_ref()
2962 .and_then(|state| state.hover_state.as_ref())
2963 .cloned()
2964 });
2965 let current_view = window.current_view();
2966
2967 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2968 let hovered = hitbox.is_hovered(window);
2969 let was_hovered = hover_state
2970 .as_ref()
2971 .is_some_and(|state| state.borrow().element);
2972 if phase == DispatchPhase::Capture && hovered != was_hovered {
2973 if let Some(hover_state) = &hover_state {
2974 hover_state.borrow_mut().element = hovered;
2975 cx.notify(current_view);
2976 }
2977 }
2978 });
2979 }
2980
2981 if let Some(group_hover) = self.group_hover_style.as_ref() {
2982 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2983 let hover_state = element_state
2984 .as_ref()
2985 .and_then(|element| element.hover_state.as_ref())
2986 .cloned();
2987 let current_view = window.current_view();
2988
2989 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2990 let group_hovered = group_hitbox_id.is_hovered(window);
2991 let was_group_hovered = hover_state
2992 .as_ref()
2993 .is_some_and(|state| state.borrow().group);
2994 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2995 if let Some(hover_state) = &hover_state {
2996 hover_state.borrow_mut().group = group_hovered;
2997 cx.notify(current_view);
2998 }
2999 }
3000 });
3001 }
3002 }
3003
3004 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
3005
3006 let mut drag_listener = mem::take(&mut self.drag_listener);
3007 let drop_listeners = mem::take(&mut self.drop_listeners);
3008 let click_listeners = mem::take(&mut self.click_listeners);
3009 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
3010 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
3011
3012 if !drop_listeners.is_empty() {
3013 let hitbox = hitbox.clone();
3014 window.on_mouse_event({
3015 move |_: &MouseUpEvent, phase, window, cx| {
3016 if let Some(drag) = &cx.active_drag
3017 && phase == DispatchPhase::Bubble
3018 && hitbox.is_hovered(window)
3019 {
3020 let drag_state_type = drag.value.as_ref().type_id();
3021 for (drop_state_type, listener) in &drop_listeners {
3022 if *drop_state_type == drag_state_type {
3023 let drag = cx
3024 .active_drag
3025 .take()
3026 .expect("checked for type drag state type above");
3027
3028 let mut can_drop = true;
3029 if let Some(predicate) = &can_drop_predicate {
3030 can_drop = predicate(drag.value.as_ref(), window, cx);
3031 }
3032
3033 if can_drop {
3034 listener(drag.value.as_ref(), window, cx);
3035 window.refresh();
3036 cx.stop_propagation();
3037 }
3038 }
3039 }
3040 }
3041 }
3042 });
3043 }
3044
3045 if let Some(element_state) = element_state {
3046 if !click_listeners.is_empty()
3047 || !aux_click_listeners.is_empty()
3048 || drag_listener.is_some()
3049 {
3050 let pending_mouse_down = element_state
3051 .pending_mouse_down
3052 .get_or_insert_with(Default::default)
3053 .clone();
3054
3055 let pending_keyboard_down = element_state
3056 .pending_keyboard_down
3057 .get_or_insert_with(Default::default)
3058 .clone();
3059
3060 let clicked_state = element_state
3061 .clicked_state
3062 .get_or_insert_with(Default::default)
3063 .clone();
3064
3065 window.on_mouse_event({
3066 let pending_mouse_down = pending_mouse_down.clone();
3067 let hitbox = hitbox.clone();
3068 let has_aux_click_listeners = !aux_click_listeners.is_empty();
3069 move |event: &MouseDownEvent, phase, window, _cx| {
3070 if phase == DispatchPhase::Bubble
3071 && (event.button == MouseButton::Left || has_aux_click_listeners)
3072 && hitbox.is_hovered(window)
3073 {
3074 *pending_mouse_down.borrow_mut() = Some(event.clone());
3075 window.refresh();
3076 }
3077 }
3078 });
3079
3080 window.on_mouse_event({
3081 let pending_mouse_down = pending_mouse_down.clone();
3082 let hitbox = hitbox.clone();
3083 move |event: &MouseMoveEvent, phase, window, cx| {
3084 if phase == DispatchPhase::Capture {
3085 return;
3086 }
3087
3088 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3089 if let Some(mouse_down) = pending_mouse_down.clone()
3090 && !cx.has_active_drag()
3091 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
3092 && let Some(listener) = drag_listener.take()
3093 && mouse_down.button == MouseButton::Left
3094 {
3095 *clicked_state.borrow_mut() = ElementClickedState::default();
3096 let cursor_offset = event.position - hitbox.origin;
3097 let drag = (listener.render)(
3098 listener.value.as_ref(),
3099 cursor_offset,
3100 window,
3101 cx,
3102 );
3103 let external_payload_source =
3104 listener.external_payload.map(|external_payload| {
3105 let value = listener.value.clone();
3106 Box::new(move |window: &mut Window, cx: &mut App| {
3107 external_payload(value.as_ref(), window, cx)
3108 })
3109 as ExternalDragPayloadSource
3110 });
3111 cx.active_drag = Some(AnyDrag {
3112 view: drag,
3113 value: listener.value,
3114 cursor_offset,
3115 cursor_style: drag_cursor_style,
3116 external_payload_source,
3117 });
3118 pending_mouse_down.take();
3119 window.refresh();
3120 cx.stop_propagation();
3121 }
3122 }
3123 });
3124
3125 if is_focused {
3126 window.on_key_event({
3136 let pending_keyboard_down = pending_keyboard_down.clone();
3137 move |event: &KeyDownEvent, phase, window, _cx| {
3138 if phase.bubble() && !window.default_prevented() {
3139 let stroke = &event.keystroke;
3140 let is_activation_key = (stroke.key.eq("enter")
3141 || stroke.key.eq("space"))
3142 && !stroke.modifiers.modified();
3143 *pending_keyboard_down.borrow_mut() =
3144 is_activation_key.then_some(window.focus_generation);
3145 }
3146 }
3147 });
3148
3149 window.on_key_event({
3151 let click_listeners = click_listeners.clone();
3152 let hitbox = hitbox.clone();
3153 move |event: &KeyUpEvent, phase, window, cx| {
3154 if phase.bubble() && !window.default_prevented() {
3155 let stroke = &event.keystroke;
3156 let keyboard_button = if stroke.key.eq("enter") {
3157 Some(KeyboardButton::Enter)
3158 } else if stroke.key.eq("space") {
3159 Some(KeyboardButton::Space)
3160 } else {
3161 None
3162 };
3163
3164 if let Some(button) = keyboard_button
3165 && !stroke.modifiers.modified()
3166 {
3167 let pending =
3168 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
3169 if pending != Some(window.focus_generation) {
3170 return;
3171 }
3172
3173 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
3174 button,
3175 bounds: hitbox.bounds,
3176 });
3177
3178 for listener in &click_listeners {
3179 listener(&click_event, window, cx);
3180 }
3181 } else {
3182 *pending_keyboard_down.borrow_mut() = None;
3186 }
3187 }
3188 }
3189 });
3190 }
3191
3192 window.on_mouse_event({
3193 let mut captured_mouse_down = None;
3194 let hitbox = hitbox.clone();
3195 move |event: &MouseUpEvent, phase, window, cx| match phase {
3196 DispatchPhase::Capture => {
3200 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3201 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
3202 captured_mouse_down = pending_mouse_down.take();
3203 window.refresh();
3204 } else if pending_mouse_down.is_some() {
3205 pending_mouse_down.take();
3211 window.refresh();
3212 }
3213 }
3214 DispatchPhase::Bubble => {
3216 if let Some(mouse_down) = captured_mouse_down.take() {
3217 let btn = mouse_down.button;
3218
3219 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
3220 down: mouse_down,
3221 up: event.clone(),
3222 });
3223
3224 match btn {
3225 MouseButton::Left => {
3226 for listener in &click_listeners {
3227 listener(&mouse_click, window, cx);
3228 }
3229 }
3230 _ => {
3231 for listener in &aux_click_listeners {
3232 listener(&mouse_click, window, cx);
3233 }
3234 }
3235 }
3236 }
3237 }
3238 }
3239 });
3240 }
3241
3242 if let Some(hover_listener) = self.hover_listener.take() {
3243 let was_hovered = element_state
3244 .hover_listener_state
3245 .get_or_insert_with(Default::default)
3246 .clone();
3247 let has_mouse_down = element_state
3248 .pending_mouse_down
3249 .get_or_insert_with(Default::default)
3250 .clone();
3251 let hover_listener = Rc::new(hover_listener);
3252 let hover_listener_state = was_hovered.clone();
3253 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3254 let mut was_hovered = hover_listener_state.borrow_mut();
3255 if is_hovered != *was_hovered {
3256 *was_hovered = is_hovered;
3257 drop(was_hovered);
3258 hover_listener(&is_hovered, window, cx);
3259 }
3260 };
3261 let hover_listener_mode = self.hover_listener_mode;
3262
3263 if has_mouse_down.borrow().is_none() {
3264 let is_hovered =
3265 !cx.has_active_drag() && hover_listener_mode.is_hovered(hitbox, window);
3266 if is_hovered != *was_hovered.borrow() {
3267 let update_hover = update_hover.clone();
3268 window.defer(cx, move |window, cx| {
3269 update_hover(is_hovered, window, cx);
3270 });
3271 }
3272 }
3273
3274 window.on_mouse_event({
3275 let update_hover = update_hover.clone();
3276 let hitbox = hitbox.clone();
3277 move |_: &MouseMoveEvent, phase, window, cx| {
3278 if phase == DispatchPhase::Bubble {
3279 let is_hovered = has_mouse_down.borrow().is_none()
3280 && !cx.has_active_drag()
3281 && hover_listener_mode.is_hovered(&hitbox, window);
3282 update_hover(is_hovered, window, cx);
3283 }
3284 }
3285 });
3286
3287 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3290 if phase == DispatchPhase::Bubble {
3291 update_hover(false, window, cx);
3292 }
3293 });
3294 }
3295
3296 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3297 let active_tooltip = element_state
3298 .active_tooltip
3299 .get_or_insert_with(Default::default)
3300 .clone();
3301 let pending_mouse_down = element_state
3302 .pending_mouse_down
3303 .get_or_insert_with(Default::default)
3304 .clone();
3305 let long_press_tooltip_active = element_state
3306 .long_press_tooltip_active
3307 .get_or_insert_with(Default::default)
3308 .clone();
3309
3310 let tooltip_is_hoverable = tooltip_builder.hoverable;
3311 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3312 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3313 });
3314 let check_is_hovered_during_prepaint = Rc::new({
3316 let pending_mouse_down = pending_mouse_down.clone();
3317 let source_bounds = hitbox.bounds;
3318 move |window: &Window| {
3319 !window.last_input_was_keyboard()
3320 && pending_mouse_down.borrow().is_none()
3321 && source_bounds.contains(&window.mouse_position())
3322 }
3323 });
3324 let check_is_hovered = Rc::new({
3325 let hitbox = hitbox.clone();
3326 move |window: &Window| {
3327 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3328 }
3329 });
3330 register_tooltip_mouse_handlers(
3331 &active_tooltip,
3332 self.tooltip_id,
3333 build_tooltip,
3334 check_is_hovered,
3335 check_is_hovered_during_prepaint,
3336 long_press_tooltip_active,
3337 self.tooltip_show_delay,
3338 window,
3339 );
3340 }
3341
3342 let active_state = element_state
3345 .clicked_state
3346 .get_or_insert_with(Default::default)
3347 .clone();
3348
3349 {
3350 let active_state = active_state.clone();
3351 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3352 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3353 *active_state.borrow_mut() = ElementClickedState::default();
3354 window.refresh();
3355 }
3356 });
3357 }
3358
3359 {
3360 let active_group_hitbox = self
3361 .group_active_style
3362 .as_ref()
3363 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3364 let hitbox = hitbox.clone();
3365 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3366 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3367 let group_hovered = active_group_hitbox
3368 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3369 let element_hovered = hitbox.is_hovered(window);
3370 if group_hovered || element_hovered {
3371 *active_state.borrow_mut() = ElementClickedState {
3372 group: group_hovered,
3373 element: element_hovered,
3374 };
3375 window.refresh();
3376 }
3377 }
3378 });
3379 }
3380 }
3381 }
3382
3383 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3384 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3385 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3386 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3387 let action_listeners = mem::take(&mut self.action_listeners);
3388 if let Some(context) = self.key_context.clone() {
3389 window.set_key_context(context);
3390 }
3391
3392 for listener in key_down_listeners {
3393 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3394 listener(event, phase, window, cx);
3395 })
3396 }
3397
3398 for listener in key_up_listeners {
3399 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3400 listener(event, phase, window, cx);
3401 })
3402 }
3403
3404 for listener in modifiers_changed_listeners {
3405 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3406 listener(event, window, cx);
3407 })
3408 }
3409
3410 for (action_type, listener) in action_listeners {
3411 window.on_action(action_type, listener)
3412 }
3413 }
3414
3415 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3416 let group_hitbox = self
3417 .group_hover_style
3418 .as_ref()
3419 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3420
3421 if let Some(group_hitbox) = group_hitbox {
3422 let was_hovered = group_hitbox.is_hovered(window);
3423 let current_view = window.current_view();
3424 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3425 let hovered = group_hitbox.is_hovered(window);
3426 if phase == DispatchPhase::Capture && hovered != was_hovered {
3427 cx.notify(current_view);
3428 }
3429 });
3430 }
3431 }
3432
3433 fn paint_scroll_listener(
3434 &self,
3435 hitbox: &Hitbox,
3436 style: &Style,
3437 window: &mut Window,
3438 _cx: &mut App,
3439 ) {
3440 if let Some(scroll_offset) = self.scroll_offset.clone() {
3441 let ongoing_scroll = self.ongoing_scroll.clone();
3442 let overflow = style.overflow;
3443 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3444 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3445 let line_height = window.line_height();
3446 let hitbox = hitbox.clone();
3447 let current_view = window.current_view();
3448 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
3449 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3450 let mut scroll_offset = scroll_offset.borrow_mut();
3451 let old_scroll_offset = *scroll_offset;
3452 let mut delta = event.delta.pixel_delta(line_height);
3453
3454 if restrict_scroll_to_axis
3455 && event.delta.precise()
3456 && let Some(ongoing_scroll) = &ongoing_scroll
3457 {
3458 ongoing_scroll
3459 .borrow_mut()
3460 .filter(&mut delta, event.touch_phase);
3461 }
3462
3463 let mut delta_x = match overflow.x {
3464 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3465 Overflow::Scroll
3466 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3467 {
3468 delta.y
3469 }
3470 _ => Pixels::ZERO,
3471 };
3472 let mut delta_y = match overflow.y {
3473 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3474 Overflow::Scroll
3475 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3476 {
3477 delta.x
3478 }
3479 _ => Pixels::ZERO,
3480 };
3481 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3482 if delta_x.abs() > delta_y.abs() {
3483 delta_y = Pixels::ZERO;
3484 } else {
3485 delta_x = Pixels::ZERO;
3486 }
3487 }
3488 scroll_offset.y += delta_y;
3489 scroll_offset.x += delta_x;
3490 if *scroll_offset != old_scroll_offset {
3491 cx.notify(current_view);
3492 }
3493 }
3494 });
3495 }
3496 }
3497
3498 pub fn compute_style(
3500 &self,
3501 global_id: Option<&GlobalElementId>,
3502 hitbox: Option<&Hitbox>,
3503 window: &mut Window,
3504 cx: &mut App,
3505 ) -> Style {
3506 window.with_optional_element_state(global_id, |element_state, window| {
3507 let mut element_state =
3508 element_state.map(|element_state| element_state.unwrap_or_default());
3509 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3510 (style, element_state)
3511 })
3512 }
3513
3514 fn compute_style_internal(
3516 &self,
3517 hitbox: Option<&Hitbox>,
3518 element_state: Option<&mut InteractiveElementState>,
3519 window: &mut Window,
3520 cx: &mut App,
3521 ) -> Style {
3522 let mut style = Style::default();
3523 style.refine(&self.base_style);
3524
3525 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3526 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3527 && focus_handle.within_focused(window, cx)
3528 {
3529 style.refine(in_focus_style);
3530 }
3531
3532 if let Some(focus_style) = self.focus_style.as_ref()
3533 && focus_handle.is_focused(window)
3534 {
3535 style.refine(focus_style);
3536 }
3537
3538 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3539 && focus_handle.is_focused(window)
3540 && window.last_input_was_keyboard()
3541 {
3542 style.refine(focus_visible_style);
3543 }
3544 }
3545
3546 if !cx.has_active_drag() {
3547 if let Some(group_hover) = self.group_hover_style.as_ref() {
3548 let is_group_hovered =
3549 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3550 !window.last_input_was_touch() && group_hitbox_id.is_hovered(window)
3551 } else if let Some(element_state) = element_state.as_ref() {
3552 !window.last_input_was_touch()
3553 && element_state
3554 .hover_state
3555 .as_ref()
3556 .map(|state| state.borrow().group)
3557 .unwrap_or(false)
3558 } else {
3559 false
3560 };
3561
3562 if is_group_hovered {
3563 style.refine(&group_hover.style);
3564 }
3565 }
3566
3567 if let Some(hover_style) = self.hover_style.as_ref() {
3568 let is_hovered = if let Some(hitbox) = hitbox {
3569 !window.last_input_was_touch() && hitbox.is_hovered(window)
3570 } else if let Some(element_state) = element_state.as_ref() {
3571 !window.last_input_was_touch()
3572 && element_state
3573 .hover_state
3574 .as_ref()
3575 .map(|state| state.borrow().element)
3576 .unwrap_or(false)
3577 } else {
3578 false
3579 };
3580
3581 if is_hovered {
3582 style.refine(hover_style);
3583 }
3584 }
3585 }
3586
3587 if let Some(hitbox) = hitbox {
3588 if let Some(drag) = cx.active_drag.take() {
3589 let mut can_drop = true;
3590 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3591 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3592 }
3593
3594 if can_drop {
3595 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3596 if let Some(group_hitbox_id) =
3597 GroupHitboxes::get(&group_drag_style.group, cx)
3598 && *state_type == drag.value.as_ref().type_id()
3599 && group_hitbox_id.is_hovered(window)
3600 {
3601 style.refine(&group_drag_style.style);
3602 }
3603 }
3604
3605 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3606 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3607 {
3608 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3609 }
3610 }
3611 }
3612
3613 style.mouse_cursor = drag.cursor_style;
3614 cx.active_drag = Some(drag);
3615 }
3616 }
3617
3618 if let Some(element_state) = element_state {
3619 let clicked_state = element_state
3620 .clicked_state
3621 .get_or_insert_with(Default::default)
3622 .borrow();
3623 if clicked_state.group
3624 && let Some(group) = self.group_active_style.as_ref()
3625 {
3626 style.refine(&group.style)
3627 }
3628
3629 if let Some(active_style) = self.active_style.as_ref()
3630 && clicked_state.element
3631 {
3632 style.refine(active_style)
3633 }
3634 }
3635
3636 style
3637 }
3638
3639 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3640 if let Some(id) = &self.aria.author_id {
3641 node.set_author_id(id.to_string());
3642 }
3643 if let Some(label) = &self.aria.label {
3644 node.set_label(label.to_string());
3645 }
3646 if let Some(description) = &self.aria.description {
3647 node.set_description(description.to_string());
3648 }
3649 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3650 node.set_keyboard_shortcut(keyshortcuts.to_string());
3651 }
3652 if let Some(selected) = self.aria.selected {
3653 node.set_selected(selected);
3654 }
3655 if let Some(expanded) = self.aria.expanded {
3656 node.set_expanded(expanded);
3657 }
3658 if let Some(toggled) = self.aria.toggled {
3659 node.set_toggled(toggled);
3660 }
3661 if let Some(value) = self.aria.numeric_value {
3662 node.set_numeric_value(value);
3663 }
3664 if let Some(value) = self.aria.min_numeric_value {
3665 node.set_min_numeric_value(value);
3666 }
3667 if let Some(value) = self.aria.max_numeric_value {
3668 node.set_max_numeric_value(value);
3669 }
3670 if let Some(step) = self.aria.numeric_value_step {
3671 node.set_numeric_value_step(step);
3672 }
3673 if let Some(value) = &self.aria.value {
3674 node.set_value(value.to_string());
3675 }
3676 if let Some(placeholder) = &self.aria.placeholder {
3677 node.set_placeholder(placeholder.to_string());
3678 }
3679 if let Some(orientation) = self.aria.orientation {
3680 node.set_orientation(orientation);
3681 }
3682 if let Some(level) = self.aria.level {
3683 node.set_level(level);
3684 }
3685 if let Some(position) = self.aria.position_in_set {
3686 node.set_position_in_set(position);
3687 }
3688 if let Some(size) = self.aria.size_of_set {
3689 node.set_size_of_set(size);
3690 }
3691 if let Some(index) = self.aria.row_index {
3692 node.set_row_index(index);
3693 }
3694 if let Some(index) = self.aria.column_index {
3695 node.set_column_index(index);
3696 }
3697 if let Some(count) = self.aria.row_count {
3698 node.set_row_count(count);
3699 }
3700 if let Some(count) = self.aria.column_count {
3701 node.set_column_count(count);
3702 }
3703 if !self.click_listeners.is_empty() {
3704 node.add_action(accesskit::Action::Click);
3705 }
3706 if self.tracked_focus_handle.is_some() || self.focusable {
3707 node.add_action(accesskit::Action::Focus);
3708 }
3709 for (action, _) in &self.a11y_action_listeners {
3710 node.add_action(*action);
3711 }
3712 }
3713}
3714
3715#[derive(Default)]
3718pub struct InteractiveElementState {
3719 pub(crate) focus_handle: Option<FocusHandle>,
3720 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3721 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3722 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3723 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3724 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3732 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3733 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3734 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3735 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3736}
3737
3738#[derive(Copy, Clone, Default, Eq, PartialEq)]
3740pub struct ElementClickedState {
3741 pub group: bool,
3743
3744 pub element: bool,
3746}
3747
3748impl ElementClickedState {
3749 fn is_clicked(&self) -> bool {
3750 self.group || self.element
3751 }
3752}
3753
3754#[derive(Copy, Clone, Default, Eq, PartialEq)]
3756pub struct ElementHoverState {
3757 pub group: bool,
3759
3760 pub element: bool,
3762}
3763
3764pub(crate) enum ActiveTooltip {
3765 WaitingForShow { _task: Task<()> },
3767 Visible {
3769 tooltip: AnyTooltip,
3770 is_hoverable: bool,
3771 },
3772 WaitingForHide {
3775 tooltip: AnyTooltip,
3776 _task: Task<()>,
3777 },
3778}
3779
3780pub(crate) fn clear_active_tooltip(
3781 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3782 window: &mut Window,
3783) {
3784 match active_tooltip.borrow_mut().take() {
3785 None => {}
3786 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3787 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3788 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3789 }
3790}
3791
3792pub(crate) fn clear_active_tooltip_if_not_hoverable(
3793 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3794 window: &mut Window,
3795) {
3796 let should_clear = match active_tooltip.borrow().as_ref() {
3797 None => false,
3798 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3799 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3800 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3801 };
3802 if should_clear {
3803 active_tooltip.borrow_mut().take();
3804 window.refresh();
3805 }
3806}
3807
3808pub(crate) fn set_tooltip_on_window(
3809 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3810 window: &mut Window,
3811) -> Option<TooltipId> {
3812 let tooltip = match active_tooltip.borrow().as_ref() {
3813 None => return None,
3814 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3815 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3816 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3817 };
3818 Some(window.set_tooltip(tooltip))
3819}
3820
3821pub(crate) fn register_tooltip_mouse_handlers(
3822 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3823 tooltip_id: Option<TooltipId>,
3824 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3825 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3826 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3827 long_press_tooltip_active: Rc<Cell<bool>>,
3828 show_delay: Option<Duration>,
3829 window: &mut Window,
3830) {
3831 let current_view = window.current_view();
3832 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3833
3834 window.on_mouse_event({
3835 let active_tooltip = active_tooltip.clone();
3836 let build_tooltip = build_tooltip.clone();
3837 let check_is_hovered = check_is_hovered.clone();
3838 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3839 move |_: &MouseMoveEvent, phase, window, cx| {
3840 handle_tooltip_mouse_move(
3841 &active_tooltip,
3842 &build_tooltip,
3843 &check_is_hovered,
3844 &check_is_hovered_during_prepaint,
3845 tooltip_id,
3846 current_view,
3847 phase,
3848 show_delay,
3849 window,
3850 cx,
3851 )
3852 }
3853 });
3854
3855 window.on_mouse_event({
3856 let active_tooltip = active_tooltip.clone();
3857 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3858 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3859 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3860 }
3861 }
3862 });
3863
3864 window.on_mouse_event({
3865 let active_tooltip = active_tooltip.clone();
3866 let build_tooltip = build_tooltip.clone();
3867 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3868 move |event: &LongPressEvent, phase, window, cx| {
3869 if !phase.bubble() {
3870 return;
3871 }
3872
3873 match event.phase {
3874 TouchPhase::Started if !window.default_prevented() && check_is_hovered(window) => {
3875 if show_tooltip(
3876 &active_tooltip,
3877 &build_tooltip,
3878 &check_is_hovered_during_prepaint,
3879 Some(long_press_tooltip_active.clone()),
3880 window,
3881 cx,
3882 ) {
3883 long_press_tooltip_active.set(true);
3884 window.prevent_default();
3885 cx.stop_propagation();
3886 }
3887 }
3888 TouchPhase::Ended | TouchPhase::Cancelled
3889 if long_press_tooltip_active.replace(false) =>
3890 {
3891 clear_active_tooltip(&active_tooltip, window);
3892 cx.stop_propagation();
3893 }
3894 TouchPhase::Started
3895 | TouchPhase::Moved
3896 | TouchPhase::Ended
3897 | TouchPhase::Cancelled => {}
3898 }
3899 }
3900 });
3901
3902 window.on_mouse_event({
3903 let active_tooltip = active_tooltip.clone();
3904 move |_: &ScrollEvent, _phase, window: &mut Window, _cx| {
3905 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3906 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3907 }
3908 }
3909 });
3910}
3911
3912fn handle_tooltip_mouse_move(
3924 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3925 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3926 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3927 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3928 tooltip_id: Option<TooltipId>,
3929 current_view: EntityId,
3930 phase: DispatchPhase,
3931 show_delay: Duration,
3932 window: &mut Window,
3933 cx: &mut App,
3934) {
3935 enum Action {
3938 None,
3939 CancelShow,
3940 ScheduleShow,
3941 CheckVisible,
3942 }
3943
3944 let action = match active_tooltip.borrow().as_ref() {
3945 None => {
3946 let is_hovered = check_is_hovered(window);
3947 if is_hovered && phase.bubble() {
3948 Action::ScheduleShow
3949 } else {
3950 Action::None
3951 }
3952 }
3953 Some(ActiveTooltip::WaitingForShow { .. }) => {
3954 let is_hovered = check_is_hovered(window);
3955 if is_hovered {
3956 Action::None
3957 } else {
3958 Action::CancelShow
3959 }
3960 }
3961 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3962 if phase.capture()
3963 && !check_is_hovered(window)
3964 && (!*is_hoverable
3965 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3966 {
3967 Action::CheckVisible
3968 } else {
3969 Action::None
3970 }
3971 }
3972 Some(ActiveTooltip::WaitingForHide { .. }) => {
3973 if phase.capture()
3974 && (check_is_hovered(window)
3975 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3976 {
3977 Action::CheckVisible
3978 } else {
3979 Action::None
3980 }
3981 }
3982 };
3983
3984 match action {
3985 Action::None => {}
3986 Action::CancelShow => {
3987 active_tooltip.borrow_mut().take();
3989 }
3990 Action::ScheduleShow => {
3991 let delayed_show_task = window.spawn(cx, {
3992 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3993 let build_tooltip = build_tooltip.clone();
3994 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3995 async move |cx| {
3996 cx.background_executor().timer(show_delay).await;
3997 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3998 return;
3999 };
4000 cx.update(|window, cx| {
4001 show_tooltip(
4002 &active_tooltip,
4003 &build_tooltip,
4004 &check_is_hovered_during_prepaint,
4005 None,
4006 window,
4007 cx,
4008 );
4009 })
4010 .ok();
4011 }
4012 });
4013 active_tooltip
4014 .borrow_mut()
4015 .replace(ActiveTooltip::WaitingForShow {
4016 _task: delayed_show_task,
4017 });
4018 }
4019 Action::CheckVisible => cx.notify(current_view),
4020 }
4021}
4022
4023fn show_tooltip(
4024 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4025 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4026 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
4027 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
4028 window: &mut Window,
4029 cx: &mut App,
4030) -> bool {
4031 let new_tooltip = build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
4032 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4033 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4034 ActiveTooltip::Visible {
4035 tooltip: AnyTooltip {
4036 view,
4037 mouse_position: window.mouse_position(),
4038 check_visible_and_update: Rc::new(move |tooltip_bounds, window, cx| {
4039 if long_press_tooltip_active
4040 .as_ref()
4041 .is_some_and(|active| active.get())
4042 {
4043 return true;
4044 }
4045 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4046 return false;
4047 };
4048 handle_tooltip_check_visible_and_update(
4049 &active_tooltip,
4050 tooltip_is_hoverable,
4051 &check_is_hovered_during_prepaint,
4052 tooltip_bounds,
4053 window,
4054 cx,
4055 )
4056 }),
4057 },
4058 is_hoverable: tooltip_is_hoverable,
4059 }
4060 });
4061 let did_show = new_tooltip.is_some();
4062 *active_tooltip.borrow_mut() = new_tooltip;
4063 window.refresh();
4064 did_show
4065}
4066
4067fn handle_tooltip_check_visible_and_update(
4071 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4072 tooltip_is_hoverable: bool,
4073 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
4074 tooltip_bounds: Bounds<Pixels>,
4075 window: &mut Window,
4076 cx: &mut App,
4077) -> bool {
4078 enum Action {
4081 None,
4082 Hide,
4083 ScheduleHide(AnyTooltip),
4084 CancelHide(AnyTooltip),
4085 }
4086
4087 let is_hovered = check_is_hovered(window)
4088 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
4089 let action = match active_tooltip.borrow().as_ref() {
4090 Some(ActiveTooltip::Visible { tooltip, .. }) => {
4091 if is_hovered {
4092 Action::None
4093 } else {
4094 if tooltip_is_hoverable {
4095 Action::ScheduleHide(tooltip.clone())
4096 } else {
4097 Action::Hide
4098 }
4099 }
4100 }
4101 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
4102 if is_hovered {
4103 Action::CancelHide(tooltip.clone())
4104 } else {
4105 Action::None
4106 }
4107 }
4108 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
4109 };
4110
4111 match action {
4112 Action::None => {}
4113 Action::Hide => clear_active_tooltip(active_tooltip, window),
4114 Action::ScheduleHide(tooltip) => {
4115 let delayed_hide_task = window.spawn(cx, {
4116 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4117 async move |cx| {
4118 cx.background_executor()
4119 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
4120 .await;
4121 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4122 return;
4123 };
4124 if active_tooltip.borrow_mut().take().is_some() {
4125 cx.update(|window, _cx| window.refresh()).ok();
4126 }
4127 }
4128 });
4129 active_tooltip
4130 .borrow_mut()
4131 .replace(ActiveTooltip::WaitingForHide {
4132 tooltip,
4133 _task: delayed_hide_task,
4134 });
4135 }
4136 Action::CancelHide(tooltip) => {
4137 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
4139 tooltip,
4140 is_hoverable: true,
4141 });
4142 }
4143 }
4144
4145 active_tooltip.borrow().is_some()
4146}
4147
4148#[derive(Default)]
4149pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
4150
4151impl Global for GroupHitboxes {}
4152
4153impl GroupHitboxes {
4154 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
4155 cx.default_global::<Self>()
4156 .0
4157 .get(name)
4158 .and_then(|bounds_stack| bounds_stack.last())
4159 .cloned()
4160 }
4161
4162 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
4163 cx.default_global::<Self>()
4164 .0
4165 .entry(name)
4166 .or_default()
4167 .push(hitbox_id);
4168 }
4169
4170 pub fn pop(name: &SharedString, cx: &mut App) {
4171 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
4172 }
4173}
4174
4175pub struct Stateful<E> {
4177 pub(crate) element: E,
4178}
4179
4180impl<E> Styled for Stateful<E>
4181where
4182 E: Styled,
4183{
4184 fn style(&mut self) -> &mut StyleRefinement {
4185 self.element.style()
4186 }
4187}
4188
4189impl<E> StatefulInteractiveElement for Stateful<E>
4190where
4191 E: Element,
4192 Self: InteractiveElement,
4193{
4194}
4195
4196impl<E> InteractiveElement for Stateful<E>
4197where
4198 E: InteractiveElement,
4199{
4200 fn interactivity(&mut self) -> &mut Interactivity {
4201 self.element.interactivity()
4202 }
4203}
4204
4205impl<E> Element for Stateful<E>
4206where
4207 E: Element,
4208{
4209 type RequestLayoutState = E::RequestLayoutState;
4210 type PrepaintState = E::PrepaintState;
4211
4212 fn id(&self) -> Option<ElementId> {
4213 self.element.id()
4214 }
4215
4216 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4217 self.element.source_location()
4218 }
4219
4220 fn a11y_role(&self) -> Option<accesskit::Role> {
4221 self.element.a11y_role()
4222 }
4223
4224 fn write_a11y_info(&self, node: &mut accesskit::Node) {
4225 self.element.write_a11y_info(node);
4226 }
4227
4228 fn a11y_synthetic_children(
4229 &mut self,
4230 prepaint: &mut Self::PrepaintState,
4231 builder: &mut crate::A11ySubtreeBuilder,
4232 ) {
4233 self.element.a11y_synthetic_children(prepaint, builder);
4234 }
4235
4236 fn request_layout(
4237 &mut self,
4238 id: Option<&GlobalElementId>,
4239 inspector_id: Option<&InspectorElementId>,
4240 window: &mut Window,
4241 cx: &mut App,
4242 ) -> (LayoutId, Self::RequestLayoutState) {
4243 self.element.request_layout(id, inspector_id, window, cx)
4244 }
4245
4246 fn prepaint(
4247 &mut self,
4248 id: Option<&GlobalElementId>,
4249 inspector_id: Option<&InspectorElementId>,
4250 bounds: Bounds<Pixels>,
4251 state: &mut Self::RequestLayoutState,
4252 window: &mut Window,
4253 cx: &mut App,
4254 ) -> E::PrepaintState {
4255 self.element
4256 .prepaint(id, inspector_id, bounds, state, window, cx)
4257 }
4258
4259 fn paint(
4260 &mut self,
4261 id: Option<&GlobalElementId>,
4262 inspector_id: Option<&InspectorElementId>,
4263 bounds: Bounds<Pixels>,
4264 request_layout: &mut Self::RequestLayoutState,
4265 prepaint: &mut Self::PrepaintState,
4266 window: &mut Window,
4267 cx: &mut App,
4268 ) {
4269 self.element.paint(
4270 id,
4271 inspector_id,
4272 bounds,
4273 request_layout,
4274 prepaint,
4275 window,
4276 cx,
4277 );
4278 }
4279}
4280
4281impl<E> ParentElement for Stateful<E>
4282where
4283 E: ParentElement,
4284{
4285 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4286 self.element.extend(elements)
4287 }
4288}
4289
4290#[derive(Clone)]
4293pub struct ScrollAnchor {
4294 handle: ScrollHandle,
4295 last_origin: Rc<RefCell<Point<Pixels>>>,
4296}
4297
4298impl ScrollAnchor {
4299 pub fn for_handle(handle: ScrollHandle) -> Self {
4301 Self {
4302 handle,
4303 last_origin: Default::default(),
4304 }
4305 }
4306 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4308 let this = self.clone();
4309
4310 window.on_next_frame(move |_, _| {
4311 let viewport_bounds = this.handle.bounds();
4312 let self_bounds = *this.last_origin.borrow();
4313 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4314 });
4315 }
4316}
4317
4318#[derive(Default, Debug)]
4319struct ScrollHandleState {
4320 offset: Rc<RefCell<Point<Pixels>>>,
4321 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4322 bounds: Bounds<Pixels>,
4323 max_offset: Point<Pixels>,
4324 child_bounds: Vec<Bounds<Pixels>>,
4325 scroll_to_bottom: bool,
4326 overflow: Point<Overflow>,
4327 active_item: Option<ScrollActiveItem>,
4328}
4329
4330#[derive(Default, Debug, Clone, Copy)]
4331struct ScrollActiveItem {
4332 index: usize,
4333 strategy: ScrollStrategy,
4334}
4335
4336#[derive(Default, Debug, Clone, Copy)]
4337enum ScrollStrategy {
4338 #[default]
4339 FirstVisible,
4340 Top,
4341}
4342
4343#[derive(Clone, Debug)]
4347pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4348
4349impl Default for ScrollHandle {
4350 fn default() -> Self {
4351 Self::new()
4352 }
4353}
4354
4355impl ScrollHandle {
4356 pub fn new() -> Self {
4358 Self(Rc::default())
4359 }
4360
4361 pub fn offset(&self) -> Point<Pixels> {
4363 *self.0.borrow().offset.borrow()
4364 }
4365
4366 pub fn max_offset(&self) -> Point<Pixels> {
4368 self.0.borrow().max_offset
4369 }
4370
4371 pub fn top_item(&self) -> usize {
4373 let state = self.0.borrow();
4374 let top = state.bounds.top() - state.offset.borrow().y;
4375
4376 match state.child_bounds.binary_search_by(|bounds| {
4377 if top < bounds.top() {
4378 Ordering::Greater
4379 } else if top > bounds.bottom() {
4380 Ordering::Less
4381 } else {
4382 Ordering::Equal
4383 }
4384 }) {
4385 Ok(ix) => ix,
4386 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4387 }
4388 }
4389
4390 pub fn bottom_item(&self) -> usize {
4392 let state = self.0.borrow();
4393 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4394
4395 match state.child_bounds.binary_search_by(|bounds| {
4396 if bottom < bounds.top() {
4397 Ordering::Greater
4398 } else if bottom > bounds.bottom() {
4399 Ordering::Less
4400 } else {
4401 Ordering::Equal
4402 }
4403 }) {
4404 Ok(ix) => ix,
4405 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4406 }
4407 }
4408
4409 pub fn bounds(&self) -> Bounds<Pixels> {
4411 self.0.borrow().bounds
4412 }
4413
4414 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4416 self.0.borrow().child_bounds.get(ix).cloned()
4417 }
4418
4419 pub fn scroll_to_item(&self, ix: usize) {
4421 let mut state = self.0.borrow_mut();
4422 state.active_item = Some(ScrollActiveItem {
4423 index: ix,
4424 strategy: ScrollStrategy::default(),
4425 });
4426 }
4427
4428 pub fn scroll_to_top_of_item(&self, ix: usize) {
4431 let mut state = self.0.borrow_mut();
4432 state.active_item = Some(ScrollActiveItem {
4433 index: ix,
4434 strategy: ScrollStrategy::Top,
4435 });
4436 }
4437
4438 fn scroll_to_active_item(&self) {
4442 let mut state = self.0.borrow_mut();
4443
4444 let Some(active_item) = state.active_item else {
4445 return;
4446 };
4447
4448 let active_item = match state.child_bounds.get(active_item.index) {
4449 Some(bounds) => {
4450 let mut scroll_offset = state.offset.borrow_mut();
4451
4452 match active_item.strategy {
4453 ScrollStrategy::FirstVisible => {
4454 if state.overflow.y == Overflow::Scroll {
4455 let child_height = bounds.size.height;
4456 let viewport_height = state.bounds.size.height;
4457 if child_height > viewport_height {
4458 scroll_offset.y = state.bounds.top() - bounds.top();
4459 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4460 scroll_offset.y = state.bounds.top() - bounds.top();
4461 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4462 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4463 }
4464 }
4465 }
4466 ScrollStrategy::Top => {
4467 scroll_offset.y = state.bounds.top() - bounds.top();
4468 }
4469 }
4470
4471 if state.overflow.x == Overflow::Scroll {
4472 let child_width = bounds.size.width;
4473 let viewport_width = state.bounds.size.width;
4474 if child_width > viewport_width {
4475 scroll_offset.x = state.bounds.left() - bounds.left();
4476 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4477 scroll_offset.x = state.bounds.left() - bounds.left();
4478 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4479 scroll_offset.x = state.bounds.right() - bounds.right();
4480 }
4481 }
4482 None
4483 }
4484 None => Some(active_item),
4485 };
4486 state.active_item = active_item;
4487 }
4488
4489 pub fn scroll_to_bottom(&self) {
4491 let mut state = self.0.borrow_mut();
4492 state.scroll_to_bottom = true;
4493 }
4494
4495 pub fn set_offset(&self, position: Point<Pixels>) {
4499 let state = self.0.borrow();
4500 *state.offset.borrow_mut() = position;
4501 }
4502
4503 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4505 let ix = self.top_item();
4506 let state = self.0.borrow();
4507
4508 if let Some(child_bounds) = state.child_bounds.get(ix) {
4509 (
4510 ix,
4511 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4512 )
4513 } else {
4514 (ix, px(0.))
4515 }
4516 }
4517
4518 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4520 let ix = self.bottom_item();
4521 let state = self.0.borrow();
4522
4523 if let Some(child_bounds) = state.child_bounds.get(ix) {
4524 (
4525 ix,
4526 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4527 )
4528 } else {
4529 (ix, px(0.))
4530 }
4531 }
4532
4533 pub fn children_count(&self) -> usize {
4535 self.0.borrow().child_bounds.len()
4536 }
4537}
4538
4539#[cfg(test)]
4540mod tests {
4541 use super::*;
4542 use crate::{
4543 AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, IntoElement,
4544 Keystroke, MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas,
4545 util::FluentBuilder as _,
4546 };
4547 use std::{cell::Cell, rc::Weak};
4548
4549 struct GroupHoverTestView {
4550 render_count: Rc<Cell<usize>>,
4551 anonymous_paint_count: Rc<Cell<usize>>,
4552 stateful_width: Rc<Cell<Pixels>>,
4553 }
4554
4555 impl Render for GroupHoverTestView {
4556 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4557 self.render_count.set(self.render_count.get() + 1);
4558 let anonymous_paint_count = self.anonymous_paint_count.clone();
4559 let stateful_width = self.stateful_width.clone();
4560 div().size_full().child(
4561 div()
4562 .ml(px(20.))
4563 .mt(px(20.))
4564 .size(px(50.))
4565 .relative()
4566 .group("hover-group")
4567 .child(
4568 div()
4569 .absolute()
4570 .size_full()
4571 .invisible()
4572 .group_hover("hover-group", |style| style.visible())
4573 .child(canvas(
4574 |_, _, _| {},
4575 move |_, _, _, _| {
4576 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4577 },
4578 )),
4579 )
4580 .child(
4581 div()
4582 .id("stateful-group-hover-target")
4583 .absolute()
4584 .top_0()
4585 .left_0()
4586 .size(px(10.))
4587 .group_hover("hover-group", |style| style.size(px(20.)))
4588 .child(canvas(
4589 move |bounds, _, _| stateful_width.set(bounds.size.width),
4590 |_, _, _, _| {},
4591 )),
4592 ),
4593 )
4594 }
4595 }
4596
4597 #[gpui::test]
4598 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4599 let render_count = Rc::new(Cell::new(0));
4600 let anonymous_paint_count = Rc::new(Cell::new(0));
4601 let stateful_width = Rc::new(Cell::new(px(0.)));
4602 let window = cx.add_window({
4603 let render_count = render_count.clone();
4604 let anonymous_paint_count = anonymous_paint_count.clone();
4605 let stateful_width = stateful_width.clone();
4606 move |_, _| GroupHoverTestView {
4607 render_count,
4608 anonymous_paint_count,
4609 stateful_width,
4610 }
4611 });
4612 let window = AnyWindowHandle::from(window);
4613
4614 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4615 .unwrap();
4616 assert_eq!(anonymous_paint_count.get(), 0);
4617 assert_eq!(stateful_width.get(), px(10.));
4618
4619 let move_mouse = |cx: &mut TestAppContext, position| {
4620 cx.update_window(window, |_, window, cx| {
4621 window.simulate_mouse_move(position, cx)
4622 })
4623 .unwrap();
4624 };
4625
4626 let initial_render_count = render_count.get();
4627 move_mouse(cx, point(px(25.), px(25.)));
4628 assert_eq!(render_count.get(), initial_render_count + 1);
4629 assert_eq!(anonymous_paint_count.get(), 1);
4630 assert_eq!(stateful_width.get(), px(20.));
4631
4632 move_mouse(cx, point(px(30.), px(30.)));
4633 assert_eq!(render_count.get(), initial_render_count + 1);
4634 assert_eq!(anonymous_paint_count.get(), 1);
4635 assert_eq!(stateful_width.get(), px(20.));
4636
4637 move_mouse(cx, point(px(5.), px(5.)));
4638 assert_eq!(render_count.get(), initial_render_count + 2);
4639 assert_eq!(anonymous_paint_count.get(), 1);
4640 assert_eq!(stateful_width.get(), px(10.));
4641
4642 move_mouse(cx, point(px(10.), px(10.)));
4643 assert_eq!(render_count.get(), initial_render_count + 2);
4644 assert_eq!(anonymous_paint_count.get(), 1);
4645 assert_eq!(stateful_width.get(), px(10.));
4646 }
4647
4648 struct HoverListenerLayoutTestView {
4649 target_left: Pixels,
4650 hover_transitions: Rc<RefCell<Vec<bool>>>,
4651 }
4652
4653 impl Render for HoverListenerLayoutTestView {
4654 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4655 let hover_transitions = self.hover_transitions.clone();
4656 div().relative().size_full().child(
4657 div()
4658 .id("hover-target")
4659 .absolute()
4660 .left(self.target_left)
4661 .top_0()
4662 .size(px(20.))
4663 .on_click(|_, _, _| {})
4664 .on_hover(move |is_hovered, _, _| {
4665 hover_transitions.borrow_mut().push(*is_hovered);
4666 }),
4667 )
4668 }
4669 }
4670
4671 #[gpui::test]
4672 fn default_hover_listener_updates_when_layout_changes_under_stationary_mouse(
4673 cx: &mut TestAppContext,
4674 ) {
4675 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4676 let window = cx.add_window({
4677 let hover_transitions = hover_transitions.clone();
4678 move |_, _| HoverListenerLayoutTestView {
4679 target_left: px(40.),
4680 hover_transitions,
4681 }
4682 });
4683 let any_window = AnyWindowHandle::from(window);
4684
4685 cx.update_window(any_window, |_, window, cx| {
4686 window.draw(cx).clear(cx);
4687 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4688 })
4689 .unwrap();
4690 assert!(hover_transitions.borrow().is_empty());
4691
4692 window
4693 .update(cx, |view, _, cx| {
4694 view.target_left = px(0.);
4695 cx.notify();
4696 })
4697 .unwrap();
4698 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4699 .unwrap();
4700 assert_eq!(*hover_transitions.borrow(), [true]);
4701
4702 window
4703 .update(cx, |view, _, cx| {
4704 view.target_left = px(40.);
4705 cx.notify();
4706 })
4707 .unwrap();
4708 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4709 .unwrap();
4710 assert_eq!(*hover_transitions.borrow(), [true, false]);
4711 }
4712
4713 #[gpui::test]
4714 fn default_hover_listener_ends_after_key_press(cx: &mut TestAppContext) {
4715 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4716 let window = cx.add_window({
4717 let hover_transitions = hover_transitions.clone();
4718 move |_, _| HoverListenerLayoutTestView {
4719 target_left: px(0.),
4720 hover_transitions,
4721 }
4722 });
4723 let any_window = AnyWindowHandle::from(window);
4724
4725 cx.update_window(any_window, |_, window, cx| {
4726 window.draw(cx).clear(cx);
4727 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4728 })
4729 .unwrap();
4730 assert_eq!(*hover_transitions.borrow(), [true]);
4731
4732 key_down(cx, any_window, "a");
4733 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4734 .unwrap();
4735 assert_eq!(*hover_transitions.borrow(), [true, false]);
4736 }
4737
4738 struct HoverListenerModeLayoutTestView {
4739 target_left: Pixels,
4740 hover_transitions: Rc<RefCell<Vec<bool>>>,
4741 }
4742
4743 impl Render for HoverListenerModeLayoutTestView {
4744 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4745 let hover_transitions = self.hover_transitions.clone();
4746 div().relative().size_full().child(
4747 div()
4748 .id("hover-target")
4749 .absolute()
4750 .left(self.target_left)
4751 .top_0()
4752 .size(px(20.))
4753 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
4754 .on_hover(move |is_hovered, _, _| {
4755 hover_transitions.borrow_mut().push(*is_hovered);
4756 }),
4757 )
4758 }
4759 }
4760
4761 #[gpui::test]
4762 fn input_modality_independent_hover_listener_updates_after_key_press(cx: &mut TestAppContext) {
4763 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4764 let window = cx.add_window({
4765 let hover_transitions = hover_transitions.clone();
4766 move |_, _| HoverListenerModeLayoutTestView {
4767 target_left: px(40.),
4768 hover_transitions,
4769 }
4770 });
4771 let any_window = AnyWindowHandle::from(window);
4772 let pointer_position = point(px(10.), px(10.));
4773
4774 cx.update_window(any_window, |_, window, cx| {
4775 window.draw(cx).clear(cx);
4776 window.simulate_mouse_move(pointer_position, cx);
4777 })
4778 .unwrap();
4779 assert!(hover_transitions.borrow().is_empty());
4780
4781 key_down(cx, any_window, "a");
4782 window
4783 .update(cx, |view, _, cx| {
4784 view.target_left = px(0.);
4785 cx.notify();
4786 })
4787 .unwrap();
4788 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4789 .unwrap();
4790 assert_eq!(*hover_transitions.borrow(), [true]);
4791
4792 key_down(cx, any_window, "b");
4793 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4794 .unwrap();
4795 assert_eq!(*hover_transitions.borrow(), [true]);
4796
4797 cx.update_window(any_window, |_, window, cx| {
4798 window.simulate_mouse_move(point(px(30.), px(10.)), cx);
4799 })
4800 .unwrap();
4801 assert_eq!(*hover_transitions.borrow(), [true, false]);
4802
4803 cx.update_window(any_window, |_, window, cx| {
4804 window.simulate_mouse_move(pointer_position, cx);
4805 window.dispatch_event(
4806 MouseExitEvent {
4807 position: pointer_position,
4808 ..Default::default()
4809 }
4810 .to_platform_input(),
4811 cx,
4812 );
4813 })
4814 .unwrap();
4815 assert_eq!(*hover_transitions.borrow(), [true, false, true, false]);
4816 }
4817
4818 #[gpui::test]
4819 fn default_hover_listener_remains_hovered_during_stationary_mouse_press(
4820 cx: &mut TestAppContext,
4821 ) {
4822 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4823 let window = cx.add_window({
4824 let hover_transitions = hover_transitions.clone();
4825 move |_, _| HoverListenerLayoutTestView {
4826 target_left: px(0.),
4827 hover_transitions,
4828 }
4829 });
4830 let any_window = AnyWindowHandle::from(window);
4831 let mouse_position = point(px(10.), px(10.));
4832
4833 cx.update_window(any_window, |_, window, cx| {
4834 window.draw(cx).clear(cx);
4835 window.simulate_mouse_move(mouse_position, cx);
4836 })
4837 .unwrap();
4838 assert_eq!(*hover_transitions.borrow(), [true]);
4839
4840 cx.update_window(any_window, |_, window, cx| {
4841 window.dispatch_event(
4842 MouseDownEvent {
4843 position: mouse_position,
4844 button: MouseButton::Left,
4845 modifiers: Default::default(),
4846 click_count: 1,
4847 first_mouse: false,
4848 }
4849 .to_platform_input(),
4850 cx,
4851 );
4852 window.draw(cx).clear(cx);
4853 })
4854 .unwrap();
4855 assert_eq!(*hover_transitions.borrow(), [true]);
4856
4857 cx.update_window(any_window, |_, window, cx| {
4858 window.dispatch_event(
4859 MouseUpEvent {
4860 position: mouse_position,
4861 button: MouseButton::Left,
4862 modifiers: Default::default(),
4863 click_count: 1,
4864 }
4865 .to_platform_input(),
4866 cx,
4867 );
4868 window.draw(cx).clear(cx);
4869 })
4870 .unwrap();
4871 assert_eq!(*hover_transitions.borrow(), [true]);
4872 }
4873
4874 struct TestTooltipView;
4875
4876 impl Render for TestTooltipView {
4877 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4878 div().w(px(20.)).h(px(20.)).child("tooltip")
4879 }
4880 }
4881
4882 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4883
4884 struct TooltipCaptureElement {
4885 child: AnyElement,
4886 captured_active_tooltip: CapturedActiveTooltip,
4887 }
4888
4889 impl Element for TooltipCaptureElement {
4890 type RequestLayoutState = ();
4891 type PrepaintState = ();
4892
4893 fn id(&self) -> Option<ElementId> {
4894 None
4895 }
4896
4897 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4898 None
4899 }
4900
4901 fn request_layout(
4902 &mut self,
4903 _id: Option<&GlobalElementId>,
4904 _inspector_id: Option<&InspectorElementId>,
4905 window: &mut Window,
4906 cx: &mut App,
4907 ) -> (LayoutId, Self::RequestLayoutState) {
4908 (self.child.request_layout(window, cx), ())
4909 }
4910
4911 fn prepaint(
4912 &mut self,
4913 _id: Option<&GlobalElementId>,
4914 _inspector_id: Option<&InspectorElementId>,
4915 _bounds: Bounds<Pixels>,
4916 _request_layout: &mut Self::RequestLayoutState,
4917 window: &mut Window,
4918 cx: &mut App,
4919 ) -> Self::PrepaintState {
4920 self.child.prepaint(window, cx);
4921 }
4922
4923 fn paint(
4924 &mut self,
4925 _id: Option<&GlobalElementId>,
4926 _inspector_id: Option<&InspectorElementId>,
4927 _bounds: Bounds<Pixels>,
4928 _request_layout: &mut Self::RequestLayoutState,
4929 _prepaint: &mut Self::PrepaintState,
4930 window: &mut Window,
4931 cx: &mut App,
4932 ) {
4933 self.child.paint(window, cx);
4934 window.with_global_id("target".into(), |global_id, window| {
4935 window.with_element_state::<InteractiveElementState, _>(
4936 global_id,
4937 |state, _window| {
4938 let state = state.unwrap();
4939 *self.captured_active_tooltip.borrow_mut() =
4940 state.active_tooltip.as_ref().map(Rc::downgrade);
4941 ((), state)
4942 },
4943 )
4944 });
4945 }
4946 }
4947
4948 struct TooltipOwner {
4949 captured_active_tooltip: CapturedActiveTooltip,
4950 show_delay_override: Option<Duration>,
4951 }
4952
4953 impl Render for TooltipOwner {
4954 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4955 TooltipCaptureElement {
4956 child: div()
4957 .size_full()
4958 .child(
4959 div()
4960 .id("target")
4961 .w(px(50.))
4962 .h(px(50.))
4963 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4964 .when_some(self.show_delay_override, |this, delay| {
4965 this.tooltip_show_delay(delay)
4966 }),
4967 )
4968 .into_any_element(),
4969 captured_active_tooltip: self.captured_active_tooltip.clone(),
4970 }
4971 }
4972 }
4973
4974 #[test]
4975 fn scroll_handle_aligns_wide_children_to_left_edge() {
4976 let handle = ScrollHandle::new();
4977 {
4978 let mut state = handle.0.borrow_mut();
4979 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4980 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4981 state.overflow.x = Overflow::Scroll;
4982 state.active_item = Some(ScrollActiveItem {
4983 index: 0,
4984 strategy: ScrollStrategy::default(),
4985 });
4986 }
4987
4988 handle.scroll_to_active_item();
4989
4990 assert_eq!(handle.offset().x, px(-25.));
4991 }
4992
4993 #[test]
4994 fn scroll_handle_aligns_tall_children_to_top_edge() {
4995 let handle = ScrollHandle::new();
4996 {
4997 let mut state = handle.0.borrow_mut();
4998 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4999 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
5000 state.overflow.y = Overflow::Scroll;
5001 state.active_item = Some(ScrollActiveItem {
5002 index: 0,
5003 strategy: ScrollStrategy::default(),
5004 });
5005 }
5006
5007 handle.scroll_to_active_item();
5008
5009 assert_eq!(handle.offset().y, px(-25.));
5010 }
5011
5012 #[test]
5013 fn long_press_shows_tooltip_until_touch_ends() {
5014 let (mut test_app, any_window, captured_active_tooltip) = create_tooltip_owner_test(None);
5015 let active_tooltip = captured_active_tooltip
5016 .borrow()
5017 .clone()
5018 .unwrap()
5019 .upgrade()
5020 .unwrap();
5021 let touch_id = TouchId(1);
5022 let touch_position = point(px(49.), px(10.));
5023
5024 test_app
5025 .update_window(any_window, |_, window, cx| {
5026 window.dispatch_event(
5027 TouchEvent {
5028 id: touch_id,
5029 phase: TouchPhase::Started,
5030 position: touch_position,
5031 predicted_position: None,
5032 force: None,
5033 }
5034 .to_platform_input(),
5035 cx,
5036 );
5037 })
5038 .unwrap();
5039 test_app
5040 .dispatcher
5041 .advance_clock(GestureTuning::default().long_press_duration + Duration::from_millis(1));
5042 test_app.run_until_parked();
5043
5044 assert!(matches!(
5045 active_tooltip.borrow().as_ref(),
5046 Some(ActiveTooltip::Visible { .. })
5047 ));
5048
5049 let moved_position = point(px(55.), px(10.));
5050 test_app
5051 .update_window(any_window, |_, window, cx| {
5052 window.dispatch_event(
5053 TouchEvent {
5054 id: touch_id,
5055 phase: TouchPhase::Moved,
5056 position: moved_position,
5057 predicted_position: None,
5058 force: None,
5059 }
5060 .to_platform_input(),
5061 cx,
5062 );
5063 window.draw(cx).clear(cx);
5064 })
5065 .unwrap();
5066 assert!(matches!(
5067 active_tooltip.borrow().as_ref(),
5068 Some(ActiveTooltip::Visible { .. })
5069 ));
5070
5071 test_app
5072 .update_window(any_window, |_, window, cx| {
5073 window.dispatch_event(
5074 TouchEvent {
5075 id: touch_id,
5076 phase: TouchPhase::Ended,
5077 position: moved_position,
5078 predicted_position: None,
5079 force: None,
5080 }
5081 .to_platform_input(),
5082 cx,
5083 );
5084 })
5085 .unwrap();
5086
5087 assert!(active_tooltip.borrow().is_none());
5088 }
5089
5090 fn setup_tooltip_owner_test(
5091 show_delay_override: Option<Duration>,
5092 ) -> (
5093 TestAppContext,
5094 crate::AnyWindowHandle,
5095 CapturedActiveTooltip,
5096 ) {
5097 let (mut test_app, any_window, captured_active_tooltip) =
5098 create_tooltip_owner_test(show_delay_override);
5099
5100 test_app
5101 .update_window(any_window, |_, window, cx| {
5102 window.dispatch_event(
5103 MouseMoveEvent {
5104 position: point(px(10.), px(10.)),
5105 modifiers: Default::default(),
5106 pressed_button: None,
5107 }
5108 .to_platform_input(),
5109 cx,
5110 );
5111 })
5112 .unwrap();
5113
5114 test_app
5115 .update_window(any_window, |_, window, cx| {
5116 window.draw(cx).clear(cx);
5117 })
5118 .unwrap();
5119
5120 (test_app, any_window, captured_active_tooltip)
5121 }
5122
5123 fn create_tooltip_owner_test(
5124 show_delay_override: Option<Duration>,
5125 ) -> (
5126 TestAppContext,
5127 crate::AnyWindowHandle,
5128 CapturedActiveTooltip,
5129 ) {
5130 let mut test_app = TestAppContext::single();
5131 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
5132 let window = test_app.add_window({
5133 let captured_active_tooltip = captured_active_tooltip.clone();
5134 move |_, _| TooltipOwner {
5135 captured_active_tooltip,
5136 show_delay_override,
5137 }
5138 });
5139 let any_window = window.into();
5140
5141 test_app
5142 .update_window(any_window, |_, window, cx| {
5143 window.draw(cx).clear(cx);
5144 })
5145 .unwrap();
5146
5147 (test_app, any_window, captured_active_tooltip)
5148 }
5149
5150 #[test]
5151 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
5152 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5153
5154 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5155 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5156 assert!(matches!(
5157 active_tooltip.borrow().as_ref(),
5158 Some(ActiveTooltip::WaitingForShow { .. })
5159 ));
5160
5161 test_app
5162 .update_window(any_window, |_, window, _| {
5163 window.remove_window();
5164 })
5165 .unwrap();
5166 test_app.run_until_parked();
5167 drop(active_tooltip);
5168
5169 assert!(weak_active_tooltip.upgrade().is_none());
5170 }
5171
5172 #[test]
5173 fn tooltip_respects_custom_show_delay() {
5174 let extra_delay = Duration::from_secs(1);
5175 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
5176 let (test_app, _any_window, captured_active_tooltip) =
5177 setup_tooltip_owner_test(Some(show_delay_override));
5178
5179 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5180 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5181
5182 test_app
5183 .dispatcher
5184 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5185 test_app.run_until_parked();
5186
5187 assert!(matches!(
5188 active_tooltip.borrow().as_ref(),
5189 Some(ActiveTooltip::WaitingForShow { .. })
5190 ));
5191
5192 test_app.dispatcher.advance_clock(extra_delay);
5193 test_app.run_until_parked();
5194
5195 assert!(matches!(
5196 active_tooltip.borrow().as_ref(),
5197 Some(ActiveTooltip::Visible { .. })
5198 ));
5199 }
5200
5201 #[test]
5202 fn tooltip_is_released_when_its_owner_disappears() {
5203 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5204
5205 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5206 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5207
5208 test_app
5209 .dispatcher
5210 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5211 test_app.run_until_parked();
5212
5213 assert!(matches!(
5214 active_tooltip.borrow().as_ref(),
5215 Some(ActiveTooltip::Visible { .. })
5216 ));
5217
5218 test_app
5219 .update_window(any_window, |_, window, _| {
5220 window.remove_window();
5221 })
5222 .unwrap();
5223 test_app.run_until_parked();
5224 drop(active_tooltip);
5225
5226 assert!(weak_active_tooltip.upgrade().is_none());
5227 }
5228
5229 #[test]
5230 fn tooltip_hides_after_mouse_leaves_origin() {
5231 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5232
5233 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5234 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5235
5236 test_app
5237 .dispatcher
5238 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5239 test_app.run_until_parked();
5240
5241 assert!(matches!(
5242 active_tooltip.borrow().as_ref(),
5243 Some(ActiveTooltip::Visible { .. })
5244 ));
5245
5246 test_app
5247 .update_window(any_window, |_, window, cx| {
5248 window.dispatch_event(
5249 MouseMoveEvent {
5250 position: point(px(75.), px(75.)),
5251 modifiers: Default::default(),
5252 pressed_button: None,
5253 }
5254 .to_platform_input(),
5255 cx,
5256 );
5257 })
5258 .unwrap();
5259
5260 assert!(active_tooltip.borrow().is_none());
5261 }
5262
5263 struct MouseDownOutOwner {
5264 mouse_down_out_count: Rc<RefCell<usize>>,
5265 }
5266
5267 impl Render for MouseDownOutOwner {
5268 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5269 let mouse_down_out_count = self.mouse_down_out_count.clone();
5270 div()
5271 .size_full()
5272 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
5273 move |_, _, _| {
5274 *mouse_down_out_count.borrow_mut() += 1;
5275 },
5276 ))
5277 }
5278 }
5279
5280 #[test]
5281 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
5282 let mut test_app = TestAppContext::single();
5283 let mouse_down_out_count = Rc::new(RefCell::new(0));
5284 let window = test_app.add_window({
5285 let mouse_down_out_count = mouse_down_out_count.clone();
5286 move |_, _| MouseDownOutOwner {
5287 mouse_down_out_count,
5288 }
5289 });
5290 let any_window: AnyWindowHandle = window.into();
5291
5292 fn dispatch_mouse_down_outside_target(
5293 test_app: &mut TestAppContext,
5294 any_window: AnyWindowHandle,
5295 ) {
5296 test_app
5297 .update_window(any_window, |_, window, cx| {
5298 window.dispatch_event(
5299 MouseDownEvent {
5300 position: point(px(75.), px(75.)),
5301 button: MouseButton::Left,
5302 modifiers: Default::default(),
5303 click_count: 1,
5304 first_mouse: false,
5305 }
5306 .to_platform_input(),
5307 cx,
5308 );
5309 })
5310 .unwrap();
5311 }
5312
5313 test_app
5314 .update_window(any_window, |_, window, cx| {
5315 window.draw(cx).clear(cx);
5316 })
5317 .unwrap();
5318
5319 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5320 assert_eq!(
5321 *mouse_down_out_count.borrow(),
5322 1,
5323 "mouse down outside the element should fire mouse-down-out listeners"
5324 );
5325
5326 test_app
5327 .update_window(any_window, |_, window, cx| {
5328 cx.set_prompt_builder(crate::fallback_prompt_renderer);
5329 let _receiver =
5330 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
5331 assert!(window.has_active_prompt());
5332 window.draw(cx).clear(cx);
5333 })
5334 .unwrap();
5335
5336 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5337 assert_eq!(
5338 *mouse_down_out_count.borrow(),
5339 1,
5340 "mouse down over an active prompt should not fire mouse-down-out listeners"
5341 );
5342 }
5343
5344 #[test]
5345 fn touch_tap_out_fires_once_after_release() {
5346 let mut test_app = TestAppContext::single();
5347 let mouse_down_out_count = Rc::new(RefCell::new(0));
5348 let window = test_app.add_window({
5349 let mouse_down_out_count = mouse_down_out_count.clone();
5350 move |_, _| MouseDownOutOwner {
5351 mouse_down_out_count,
5352 }
5353 });
5354 let any_window: AnyWindowHandle = window.into();
5355
5356 test_app
5357 .update_window(any_window, |_, window, cx| {
5358 window.draw(cx).clear(cx);
5359 let started = TouchEvent {
5360 id: TouchId(1),
5361 phase: TouchPhase::Started,
5362 position: point(px(75.), px(75.)),
5363 force: None,
5364 predicted_position: None,
5365 };
5366 window.dispatch_event(started.clone().to_platform_input(), cx);
5367 assert_eq!(*mouse_down_out_count.borrow(), 0);
5368 window.dispatch_event(
5369 TouchEvent {
5370 phase: TouchPhase::Ended,
5371 ..started
5372 }
5373 .to_platform_input(),
5374 cx,
5375 );
5376 })
5377 .unwrap();
5378
5379 assert_eq!(
5380 *mouse_down_out_count.borrow(),
5381 1,
5382 "a touch tap outside the element should use mouse-down-out listeners"
5383 );
5384 }
5385
5386 #[crate::test]
5387 fn touch_pan_and_cancel_do_not_fire_mouse_down_out(cx: &mut TestAppContext) {
5388 let mouse_down_out_count = Rc::new(RefCell::new(0));
5389 let window = cx.add_window({
5390 let mouse_down_out_count = mouse_down_out_count.clone();
5391 move |_, _| MouseDownOutOwner {
5392 mouse_down_out_count,
5393 }
5394 });
5395 cx.update_window(window.into(), |_, window, cx| {
5396 window.draw(cx).clear(cx);
5397 for (id, samples) in [
5398 (
5399 TouchId(1),
5400 [
5401 (TouchPhase::Started, 100.),
5402 (TouchPhase::Moved, 75.),
5403 (TouchPhase::Ended, 75.),
5404 ],
5405 ),
5406 (
5407 TouchId(2),
5408 [
5409 (TouchPhase::Started, 100.),
5410 (TouchPhase::Moved, 100.),
5411 (TouchPhase::Cancelled, 100.),
5412 ],
5413 ),
5414 ] {
5415 for (phase, vertical_position) in samples {
5416 window.dispatch_event(
5417 TouchEvent {
5418 id,
5419 phase,
5420 position: point(px(75.), px(vertical_position)),
5421 predicted_position: None,
5422 force: None,
5423 }
5424 .to_platform_input(),
5425 cx,
5426 );
5427 }
5428 }
5429 })
5430 .unwrap();
5431 assert_eq!(*mouse_down_out_count.borrow(), 0);
5432 }
5433
5434 #[test]
5435 fn test_accessibility_id_builder_writes_author_id() {
5436 let mut element = div()
5437 .id("buffer-font-size")
5438 .accessibility_id("settings.buffer-font-size");
5439 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5440
5441 element.interactivity().write_a11y_info(&mut node);
5442
5443 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5444 }
5445
5446 #[test]
5447 fn test_write_a11y_info_string_and_numeric_properties() {
5448 let mut interactivity = Interactivity::default();
5449 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
5450 interactivity.aria.label = Some("Buffer Font Size".into());
5451 interactivity.aria.value = Some("15".into());
5452 interactivity.aria.placeholder = Some("Search".into());
5453 interactivity.aria.numeric_value = Some(15.0);
5454 interactivity.aria.min_numeric_value = Some(6.0);
5455 interactivity.aria.max_numeric_value = Some(72.0);
5456 interactivity.aria.numeric_value_step = Some(1.0);
5457
5458 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5459 interactivity.write_a11y_info(&mut node);
5460
5461 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5462 assert_eq!(node.label(), Some("Buffer Font Size"));
5463 assert_eq!(node.value(), Some("15"));
5464 assert_eq!(node.placeholder(), Some("Search"));
5465 assert_eq!(node.numeric_value(), Some(15.0));
5466 assert_eq!(node.min_numeric_value(), Some(6.0));
5467 assert_eq!(node.max_numeric_value(), Some(72.0));
5468 assert_eq!(node.numeric_value_step(), Some(1.0));
5469 }
5470
5471 struct KeyboardActivationTest {
5474 focus_a: FocusHandle,
5475 focus_b: FocusHandle,
5476 clicks: Rc<RefCell<Vec<&'static str>>>,
5477 }
5478
5479 impl Render for KeyboardActivationTest {
5480 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5481 let clicks_a = self.clicks.clone();
5482 let clicks_b = self.clicks.clone();
5483 div()
5484 .size_full()
5485 .child(
5486 div()
5487 .id("a")
5488 .w(px(50.))
5489 .h(px(50.))
5490 .track_focus(&self.focus_a)
5491 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
5492 )
5493 .child(
5494 div()
5495 .id("b")
5496 .w(px(50.))
5497 .h(px(50.))
5498 .track_focus(&self.focus_b)
5499 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
5500 )
5501 }
5502 }
5503
5504 fn setup_keyboard_activation_test() -> (
5505 TestAppContext,
5506 AnyWindowHandle,
5507 Rc<RefCell<Vec<&'static str>>>,
5508 FocusHandle,
5509 FocusHandle,
5510 ) {
5511 let mut cx = TestAppContext::single();
5512 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
5513 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
5514 let window = cx.add_window({
5515 let focus_a = focus_a.clone();
5516 let focus_b = focus_b.clone();
5517 let clicks = clicks.clone();
5518 move |_, _| KeyboardActivationTest {
5519 focus_a,
5520 focus_b,
5521 clicks,
5522 }
5523 });
5524 (cx, window.into(), clicks, focus_a, focus_b)
5525 }
5526
5527 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
5530 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
5531 .unwrap();
5532 cx.run_until_parked();
5533 cx.update_window(window, |_, window, cx| {
5534 window.draw(cx).clear(cx);
5535 })
5536 .unwrap();
5537 }
5538
5539 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5540 let os = cx.read(|cx| cx.platform_info().os);
5541 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5542 cx.update_window(window, |_, window, cx| {
5543 window.dispatch_event(
5544 KeyDownEvent {
5545 keystroke,
5546 is_held: false,
5547 prefer_character_input: false,
5548 }
5549 .to_platform_input(),
5550 cx,
5551 );
5552 })
5553 .unwrap();
5554 }
5555
5556 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5557 let os = cx.read(|cx| cx.platform_info().os);
5558 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5559 cx.update_window(window, |_, window, cx| {
5560 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
5561 })
5562 .unwrap();
5563 }
5564
5565 #[test]
5567 fn keyboard_activation_fires_click_on_same_element() {
5568 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5569
5570 focus_and_draw(&mut cx, window, &focus_a);
5571 key_down(&mut cx, window, "enter");
5572 key_up(&mut cx, window, "enter");
5573
5574 assert_eq!(*clicks.borrow(), vec!["a"]);
5575 }
5576
5577 #[test]
5582 fn keyboard_activation_does_not_leak_across_focus_change() {
5583 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5584
5585 focus_and_draw(&mut cx, window, &focus_a);
5587 key_down(&mut cx, window, "enter");
5588
5589 focus_and_draw(&mut cx, window, &focus_b);
5591 key_up(&mut cx, window, "enter");
5592
5593 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5596 }
5597
5598 #[test]
5603 fn keyboard_activation_does_not_leak_when_focus_returns() {
5604 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5605
5606 focus_and_draw(&mut cx, window, &focus_a);
5608 key_down(&mut cx, window, "enter");
5609
5610 focus_and_draw(&mut cx, window, &focus_b);
5613 focus_and_draw(&mut cx, window, &focus_a);
5614 key_up(&mut cx, window, "enter");
5615
5616 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5618 }
5619
5620 #[test]
5625 fn keyboard_activation_cleared_by_intervening_key_release() {
5626 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5627
5628 focus_and_draw(&mut cx, window, &focus_a);
5629 key_down(&mut cx, window, "escape");
5630 key_down(&mut cx, window, "space");
5631 key_up(&mut cx, window, "escape");
5632 key_up(&mut cx, window, "space");
5633
5634 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5635 }
5636
5637 #[test]
5641 fn keyboard_activation_does_not_distinguish_space_and_enter() {
5642 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5643
5644 focus_and_draw(&mut cx, window, &focus_a);
5645 key_down(&mut cx, window, "space");
5646 key_up(&mut cx, window, "enter");
5647
5648 assert_eq!(*clicks.borrow(), vec!["a"]);
5649 }
5650
5651 #[test]
5654 fn keyboard_activation_cleared_by_intervening_keydown() {
5655 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5656
5657 focus_and_draw(&mut cx, window, &focus_a);
5658 key_down(&mut cx, window, "enter");
5659 key_down(&mut cx, window, "a");
5660 key_up(&mut cx, window, "enter");
5661
5662 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5663 }
5664
5665 #[test]
5668 fn keyboard_activation_ignores_modified_keys() {
5669 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5670
5671 focus_and_draw(&mut cx, window, &focus_a);
5672 key_down(&mut cx, window, "cmd-enter");
5673 key_up(&mut cx, window, "cmd-enter");
5674
5675 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5676 }
5677
5678 struct TabGroupFocus {
5682 group_a: FocusHandle,
5683 item_a: FocusHandle,
5684 group_b: FocusHandle,
5685 item_b: FocusHandle,
5686 }
5687
5688 impl Render for TabGroupFocus {
5689 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5690 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
5691 div()
5692 .track_focus(container)
5693 .tab_group()
5694 .child(div().track_focus(item))
5695 }
5696 div()
5697 .child(group(&self.group_a, &self.item_a))
5698 .child(group(&self.group_b, &self.item_b))
5699 }
5700 }
5701
5702 #[test]
5706 fn focus_next_from_tab_group_container_enters_that_group() {
5707 let mut cx = TestAppContext::single();
5708 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
5709 (
5710 cx.focus_handle(),
5711 cx.focus_handle().tab_stop(true),
5712 cx.focus_handle(),
5713 cx.focus_handle().tab_stop(true),
5714 )
5715 });
5716 let window: AnyWindowHandle = cx
5717 .add_window({
5718 let (group_a, item_a, group_b, item_b) =
5719 (group_a, item_a, group_b.clone(), item_b.clone());
5720 move |_, _| TabGroupFocus {
5721 group_a,
5722 item_a,
5723 group_b,
5724 item_b,
5725 }
5726 })
5727 .into();
5728 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5729 .unwrap();
5730
5731 let focused = cx
5733 .update_window(window, |_, window, cx| {
5734 window.focus(&group_b, cx);
5735 window.focus_next(cx);
5736 window.focused(cx).map(|handle| handle.id)
5737 })
5738 .unwrap();
5739
5740 assert_eq!(focused, Some(item_b.id));
5741 }
5742
5743 #[gpui::test]
5744 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5745 cx: &mut TestAppContext,
5746 ) {
5747 struct PaddedContainer {
5748 scroll_handle: ScrollHandle,
5749 }
5750
5751 impl Render for PaddedContainer {
5752 fn render(
5753 &mut self,
5754 _window: &mut Window,
5755 _cx: &mut Context<Self>,
5756 ) -> impl IntoElement {
5757 div().size_full().child(
5760 div()
5761 .id("container")
5762 .h(px(50.))
5763 .w(px(100.))
5764 .py(px(4.25))
5765 .overflow_y_scroll()
5766 .track_scroll(&self.scroll_handle)
5767 .child(div().w_full().h(px(42.))),
5768 )
5769 }
5770 }
5771
5772 let scroll_handle = ScrollHandle::new();
5773 let window: AnyWindowHandle = cx
5774 .add_window({
5775 let scroll_handle = scroll_handle.clone();
5776 move |_, _| PaddedContainer { scroll_handle }
5777 })
5778 .into();
5779 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5780 .unwrap();
5781
5782 assert_eq!(scroll_handle.max_offset().y, px(0.));
5783 }
5784
5785 #[gpui::test]
5786 fn test_scrolls_to_an_item_requested_before_the_first_frame(cx: &mut TestAppContext) {
5787 struct Strip {
5788 scroll_handle: ScrollHandle,
5789 }
5790
5791 impl Render for Strip {
5792 fn render(
5793 &mut self,
5794 _window: &mut Window,
5795 _cx: &mut Context<Self>,
5796 ) -> impl IntoElement {
5797 div().size_full().child(
5798 div()
5799 .id("strip")
5800 .flex()
5801 .h(px(20.))
5802 .w(px(100.))
5803 .overflow_x_scroll()
5804 .track_scroll(&self.scroll_handle)
5805 .children((0..5).map(|_| div().flex_none().w(px(40.)).h_full())),
5806 )
5807 }
5808 }
5809
5810 let scroll_handle = ScrollHandle::new();
5813 scroll_handle.scroll_to_item(4);
5814 let window: AnyWindowHandle = cx
5815 .add_window({
5816 let scroll_handle = scroll_handle.clone();
5817 move |_, _| Strip { scroll_handle }
5818 })
5819 .into();
5820 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5821 .unwrap();
5822
5823 assert_eq!(scroll_handle.offset().x, px(-100.));
5825 }
5826
5827 struct ContentSizedGrid;
5828
5829 impl Render for ContentSizedGrid {
5830 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5831 let widths = [px(100.), px(200.), px(50.)];
5832 div().size_full().child(
5833 div()
5834 .w_full()
5835 .grid()
5836 .grid_cols_max_content(widths.len() as u16)
5837 .children(widths.into_iter().enumerate().map(|(index, width)| {
5838 div()
5839 .debug_selector(move || format!("cell-{index}"))
5840 .w(width)
5841 .h(px(10.))
5842 })),
5843 )
5844 }
5845 }
5846
5847 #[gpui::test]
5848 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
5849 let window = cx.add_window(|_, _| ContentSizedGrid);
5850 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
5851 .unwrap();
5852
5853 let mut bounds = |selector: &'static str| {
5854 cx.update_window(window.into(), |_, window, _| {
5855 window.rendered_frame.debug_bounds.get(selector).copied()
5856 })
5857 .unwrap()
5858 .unwrap_or_else(|| panic!("{selector} was not rendered"))
5859 };
5860
5861 assert_eq!(bounds("cell-0").origin.x, px(0.));
5862 assert_eq!(bounds("cell-1").origin.x, px(100.));
5863 assert_eq!(bounds("cell-2").origin.x, px(300.));
5864 }
5865}