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