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 pub(crate) 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 window.with_text_style(style.text_style().cloned(), |window| {
2466 window.with_content_mask(
2467 style.overflow_mask(bounds, window.rem_size()),
2468 |window| {
2469 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2470 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2471 } else {
2472 None
2473 };
2474
2475 let scroll_offset =
2476 self.clamp_scroll_position(bounds, &style, window, cx);
2477 let result = window.with_element_opacity(style.opacity, |window| {
2478 f(&style, scroll_offset, hitbox, window, cx)
2479 });
2480 (result, element_state)
2481 },
2482 )
2483 })
2484 },
2485 )
2486 }
2487
2488 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2489 self.hitbox_behavior != HitboxBehavior::Normal
2490 || self.window_control.is_some()
2491 || style.mouse_cursor.is_some()
2492 || self.group.is_some()
2493 || self.scroll_offset.is_some()
2494 || self.tracked_focus_handle.is_some()
2495 || self.hover_style.is_some()
2496 || self.group_hover_style.is_some()
2497 || self.hover_listener.is_some()
2498 || !self.mouse_up_listeners.is_empty()
2499 || !self.mouse_pressure_listeners.is_empty()
2500 || !self.mouse_down_listeners.is_empty()
2501 || !self.mouse_move_listeners.is_empty()
2502 || !self.mouse_exit_listeners.is_empty()
2503 || !self.file_drop_exit_listeners.is_empty()
2504 || !self.click_listeners.is_empty()
2505 || !self.aux_click_listeners.is_empty()
2506 || !self.scroll_listeners.is_empty()
2507 || self.has_pinch_listeners()
2508 || !self.back_gesture_listeners.is_empty()
2509 || self.drag_listener.is_some()
2510 || !self.drop_listeners.is_empty()
2511 || !self.drag_over_styles.is_empty()
2512 || self.tooltip_builder.is_some()
2513 || window.is_inspector_picking(cx)
2514 }
2515
2516 fn clamp_scroll_position(
2517 &self,
2518 bounds: Bounds<Pixels>,
2519 style: &Style,
2520 window: &mut Window,
2521 _cx: &mut App,
2522 ) -> Point<Pixels> {
2523 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2524 const ROUNDING_FACTOR: f32 = 100.0;
2525 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2526 }
2527
2528 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2529 let mut scroll_to_bottom = false;
2530 let mut tracked_scroll_handle = self
2531 .tracked_scroll_handle
2532 .as_ref()
2533 .map(|handle| handle.0.borrow_mut());
2534 if let Some(scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2535 scroll_handle_state.overflow = style.overflow;
2536 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2537 }
2538
2539 let rem_size = window.rem_size();
2540 let padding = style
2545 .padding
2546 .to_pixels(bounds.size.into(), rem_size)
2547 .map(|edge| window.pixel_snap(*edge));
2548 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2549 let padded_content_size = self.content_size + padding_size;
2556 let scroll_max = Point::from(padded_content_size - bounds.size)
2557 .map(round_to_two_decimals)
2558 .max(&Default::default());
2559 let mut scroll_offset = scroll_offset.borrow_mut();
2562
2563 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2564 if scroll_to_bottom {
2565 scroll_offset.y = -scroll_max.y;
2566 } else {
2567 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2568 }
2569
2570 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2571 scroll_handle_state.max_offset = scroll_max;
2572 scroll_handle_state.bounds = bounds;
2573 }
2574
2575 *scroll_offset
2576 } else {
2577 Point::default()
2578 }
2579 }
2580
2581 pub fn paint(
2590 &mut self,
2591 global_id: Option<&GlobalElementId>,
2592 _inspector_id: Option<&InspectorElementId>,
2593 bounds: Bounds<Pixels>,
2594 hitbox: Option<&Hitbox>,
2595 window: &mut Window,
2596 cx: &mut App,
2597 f: impl FnOnce(&Style, &mut Window, &mut App),
2598 ) {
2599 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2600 window.with_optional_element_state::<InteractiveElementState, _>(
2601 global_id,
2602 |element_state, window| {
2603 let mut element_state =
2604 element_state.map(|element_state| element_state.unwrap_or_default());
2605
2606 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2607
2608 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2609 if let Some(debug_selector) = &self.debug_selector {
2610 window
2611 .next_frame
2612 .record_debug_bounds(debug_selector.clone(), bounds);
2613 }
2614
2615 self.paint_hover_group_handler(window, cx);
2616
2617 if style.visibility == Visibility::Hidden {
2618 return ((), element_state);
2619 }
2620
2621 let mut tab_group = None;
2622 if self.tab_group {
2623 tab_group = self.tab_index;
2624 }
2625
2626 window.with_element_opacity(style.opacity, |window| {
2627 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2628 window.with_text_style(style.text_style().cloned(), |window| {
2629 window.with_content_mask(
2630 style.overflow_mask(bounds, window.rem_size()),
2631 |window| {
2632 window.with_tab_group(tab_group, |window| {
2633 if let Some(focus_handle) = &self.tracked_focus_handle {
2642 window.next_frame.tab_stops.insert(focus_handle);
2643 }
2644 if let Some(hitbox) = hitbox {
2645 #[cfg(debug_assertions)]
2646 self.paint_debug_info(
2647 global_id, hitbox, &style, window, cx,
2648 );
2649
2650 if let Some(drag) = cx.active_drag.as_ref() {
2651 if let Some(mouse_cursor) = drag.cursor_style {
2652 window.set_window_cursor_style(mouse_cursor);
2653 }
2654 } else {
2655 if let Some(mouse_cursor) = style.mouse_cursor {
2656 window.set_cursor_style(mouse_cursor, hitbox);
2657 }
2658 }
2659
2660 if let Some(group) = self.group.clone() {
2661 GroupHitboxes::push(group, hitbox.id, cx);
2662 }
2663
2664 if let Some(area) = self.window_control {
2665 window.insert_window_control_hitbox(
2666 area,
2667 hitbox.clone(),
2668 );
2669 }
2670
2671 self.paint_mouse_listeners(
2672 hitbox,
2673 element_state.as_mut(),
2674 window,
2675 cx,
2676 );
2677 self.paint_scroll_listener(hitbox, &style, window, cx);
2678 }
2679
2680 self.paint_keyboard_listeners(window, cx);
2681
2682 if window.a11y.is_active() {
2683 if let Some(global_id) = global_id {
2684 if !self.a11y_action_listeners.is_empty() {
2685 let node_id = global_id.accesskit_node_id();
2686 for (action, listener) in
2687 self.a11y_action_listeners.drain(..)
2688 {
2689 window.on_a11y_action(
2690 node_id, action, listener,
2691 );
2692 }
2693 }
2694 }
2695 }
2696
2697 f(&style, window, cx);
2698
2699 if let Some(_hitbox) = hitbox {
2700 #[cfg(any(feature = "inspector", debug_assertions))]
2701 window.insert_inspector_hitbox(
2702 _hitbox.id,
2703 _inspector_id,
2704 cx,
2705 );
2706
2707 if let Some(group) = self.group.as_ref() {
2708 GroupHitboxes::pop(group, cx);
2709 }
2710 }
2711 })
2712 },
2713 );
2714 });
2715 });
2716 });
2717
2718 ((), element_state)
2719 },
2720 );
2721 }
2722
2723 #[cfg(debug_assertions)]
2724 fn paint_debug_info(
2725 &self,
2726 global_id: Option<&GlobalElementId>,
2727 hitbox: &Hitbox,
2728 style: &Style,
2729 window: &mut Window,
2730 cx: &mut App,
2731 ) {
2732 use crate::{BorderStyle, TextAlign};
2733
2734 if let Some(global_id) = global_id
2735 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2736 && hitbox.is_hovered(window)
2737 {
2738 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2739 let element_id = format!("{global_id:?}");
2740 let str_len = element_id.len();
2741
2742 let render_debug_text = |window: &mut Window| {
2743 if let Some(text) = window
2744 .text_system()
2745 .shape_text(
2746 element_id.into(),
2747 FONT_SIZE,
2748 &[window.text_style().to_run(str_len)],
2749 None,
2750 None,
2751 )
2752 .ok()
2753 .and_then(|mut text| text.pop())
2754 {
2755 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2756 .ok();
2757
2758 let text_bounds = crate::Bounds {
2759 origin: hitbox.origin,
2760 size: text.size(FONT_SIZE),
2761 };
2762 if let Some(source_location) = self.source_location
2763 && text_bounds.contains(&window.mouse_position())
2764 && window.modifiers().secondary(cx)
2765 {
2766 let secondary_held = window.modifiers().secondary(cx);
2767 window.on_key_event({
2768 move |e: &crate::ModifiersChangedEvent, _phase, window, cx| {
2769 if e.modifiers.secondary(cx) != secondary_held
2770 && text_bounds.contains(&window.mouse_position())
2771 {
2772 window.refresh();
2773 }
2774 }
2775 });
2776
2777 let was_hovered = hitbox.is_hovered(window);
2778 let current_view = window.current_view();
2779 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
2780 window.on_mouse_event({
2781 let hitbox = hitbox.clone();
2782 move |_: &MouseMoveEvent, phase, window, cx| {
2783 if phase == DispatchPhase::Capture {
2784 let hovered = hitbox.is_hovered(window);
2785 if hovered != was_hovered {
2786 crate::fast::retained::invalidate_retained_subtrees(
2787 window, &subtrees,
2788 );
2789 cx.notify(current_view)
2790 }
2791 }
2792 }
2793 });
2794
2795 window.on_mouse_event({
2796 let hitbox = hitbox.clone();
2797 move |e: &crate::MouseDownEvent, phase, window, cx| {
2798 if text_bounds.contains(&e.position)
2799 && phase.capture()
2800 && hitbox.is_hovered(window)
2801 {
2802 cx.stop_propagation();
2803 let Ok(dir) = std::env::current_dir() else {
2804 return;
2805 };
2806
2807 eprintln!(
2808 "This element was created at:\n{}:{}:{}",
2809 dir.join(source_location.file()).to_string_lossy(),
2810 source_location.line(),
2811 source_location.column()
2812 );
2813 }
2814 }
2815 });
2816 window.paint_quad(crate::outline(
2817 crate::Bounds {
2818 origin: hitbox.origin
2819 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2820 size: crate::Size {
2821 width: text_bounds.size.width,
2822 height: crate::px(1.),
2823 },
2824 },
2825 crate::red(),
2826 BorderStyle::default(),
2827 ))
2828 }
2829 }
2830 };
2831
2832 window.with_text_style(
2833 Some(crate::TextStyleRefinement {
2834 color: Some(crate::red()),
2835 line_height: Some(FONT_SIZE.into()),
2836 background_color: Some(crate::white()),
2837 ..Default::default()
2838 }),
2839 render_debug_text,
2840 )
2841 }
2842 }
2843
2844 fn paint_mouse_listeners(
2845 &mut self,
2846 hitbox: &Hitbox,
2847 element_state: Option<&mut InteractiveElementState>,
2848 window: &mut Window,
2849 cx: &mut App,
2850 ) {
2851 let is_focused = self
2852 .tracked_focus_handle
2853 .as_ref()
2854 .map(|handle| handle.is_focused(window))
2855 .unwrap_or(false);
2856
2857 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2861 let hitbox = hitbox.clone();
2862 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2863 if phase == DispatchPhase::Bubble
2864 && hitbox.is_hovered(window)
2865 && !window.default_prevented()
2866 {
2867 window.focus(&focus_handle, cx);
2868 window.prevent_default();
2871 }
2872 });
2873 }
2874
2875 for listener in self.mouse_down_listeners.drain(..) {
2876 let hitbox = hitbox.clone();
2877 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2878 listener(event, phase, &hitbox, window, cx);
2879 })
2880 }
2881
2882 for listener in self.mouse_up_listeners.drain(..) {
2883 let hitbox = hitbox.clone();
2884 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2885 listener(event, phase, &hitbox, window, cx);
2886 })
2887 }
2888
2889 for listener in self.mouse_pressure_listeners.drain(..) {
2890 let hitbox = hitbox.clone();
2891 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2892 listener(event, phase, &hitbox, window, cx);
2893 })
2894 }
2895
2896 for listener in self.mouse_move_listeners.drain(..) {
2897 let hitbox = hitbox.clone();
2898 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2899 listener(event, phase, &hitbox, window, cx);
2900 })
2901 }
2902
2903 for listener in self.mouse_exit_listeners.drain(..) {
2904 let hitbox = hitbox.clone();
2905 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2906 listener(event, phase, &hitbox, window, cx);
2907 })
2908 }
2909
2910 for listener in self.file_drop_exit_listeners.drain(..) {
2911 let hitbox = hitbox.clone();
2912 window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
2913 listener(event, phase, &hitbox, window, cx);
2914 })
2915 }
2916
2917 for listener in self.scroll_listeners.drain(..) {
2918 let hitbox = hitbox.clone();
2919 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
2920 listener(event, phase, &hitbox, window, cx);
2921 })
2922 }
2923
2924 for listener in self.pinch_listeners.drain(..) {
2925 let hitbox = hitbox.clone();
2926 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2927 listener(event, phase, &hitbox, window, cx);
2928 })
2929 }
2930
2931 for listener in self.back_gesture_listeners.drain(..) {
2932 let hitbox = hitbox.clone();
2933 window.on_mouse_event(move |event: &BackGestureEvent, phase, window, cx| {
2934 listener(event, phase, &hitbox, window, cx);
2935 })
2936 }
2937
2938 if self.hover_style.is_some()
2939 || self.base_style.mouse_cursor.is_some()
2940 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2941 {
2942 let hitbox = hitbox.clone();
2943 let hover_state = self.hover_style.as_ref().and_then(|_| {
2944 element_state
2945 .as_ref()
2946 .and_then(|state| state.hover_state.as_ref())
2947 .cloned()
2948 });
2949 let current_view = window.current_view();
2950 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
2951
2952 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2953 let hovered = hitbox.is_hovered(window);
2954 let was_hovered = hover_state
2955 .as_ref()
2956 .is_some_and(|state| state.borrow().element);
2957 if phase == DispatchPhase::Capture && hovered != was_hovered {
2958 if let Some(hover_state) = &hover_state {
2959 hover_state.borrow_mut().element = hovered;
2960 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
2961 cx.notify(current_view);
2962 }
2963 }
2964 });
2965 }
2966
2967 if let Some(group_hover) = self.group_hover_style.as_ref() {
2968 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2969 let hover_state = element_state
2970 .as_ref()
2971 .and_then(|element| element.hover_state.as_ref())
2972 .cloned();
2973 let current_view = window.current_view();
2974 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
2975
2976 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2977 let group_hovered = group_hitbox_id.is_hovered(window);
2978 let was_group_hovered = hover_state
2979 .as_ref()
2980 .is_some_and(|state| state.borrow().group);
2981 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2982 if let Some(hover_state) = &hover_state {
2983 hover_state.borrow_mut().group = group_hovered;
2984 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
2985 cx.notify(current_view);
2986 }
2987 }
2988 });
2989 }
2990 }
2991
2992 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2993
2994 let mut drag_listener = mem::take(&mut self.drag_listener);
2995 let drop_listeners = mem::take(&mut self.drop_listeners);
2996 let click_listeners = mem::take(&mut self.click_listeners);
2997 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2998 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2999
3000 if !drop_listeners.is_empty() {
3001 let hitbox = hitbox.clone();
3002 window.on_mouse_event({
3003 move |_: &MouseUpEvent, phase, window, cx| {
3004 if let Some(drag) = &cx.active_drag
3005 && phase == DispatchPhase::Bubble
3006 && hitbox.is_hovered(window)
3007 {
3008 let drag_state_type = drag.value.as_ref().type_id();
3009 for (drop_state_type, listener) in &drop_listeners {
3010 if *drop_state_type == drag_state_type {
3011 let drag = cx
3012 .active_drag
3013 .take()
3014 .expect("checked for type drag state type above");
3015
3016 let mut can_drop = true;
3017 if let Some(predicate) = &can_drop_predicate {
3018 can_drop = predicate(drag.value.as_ref(), window, cx);
3019 }
3020
3021 if can_drop {
3022 listener(drag.value.as_ref(), window, cx);
3023 window.refresh();
3024 cx.stop_propagation();
3025 }
3026 }
3027 }
3028 }
3029 }
3030 });
3031 }
3032
3033 if let Some(element_state) = element_state {
3034 if !click_listeners.is_empty()
3035 || !aux_click_listeners.is_empty()
3036 || drag_listener.is_some()
3037 {
3038 let pending_mouse_down = element_state
3039 .pending_mouse_down
3040 .get_or_insert_with(Default::default)
3041 .clone();
3042
3043 let pending_keyboard_down = element_state
3044 .pending_keyboard_down
3045 .get_or_insert_with(Default::default)
3046 .clone();
3047
3048 let clicked_state = element_state
3049 .clicked_state
3050 .get_or_insert_with(Default::default)
3051 .clone();
3052
3053 window.on_mouse_event({
3054 let pending_mouse_down = pending_mouse_down.clone();
3055 let hitbox = hitbox.clone();
3056 let has_aux_click_listeners = !aux_click_listeners.is_empty();
3057 move |event: &MouseDownEvent, phase, window, _cx| {
3058 if phase == DispatchPhase::Bubble
3059 && (event.button == MouseButton::Left || has_aux_click_listeners)
3060 && hitbox.is_hovered(window)
3061 {
3062 *pending_mouse_down.borrow_mut() = Some(event.clone());
3063 window.refresh();
3064 }
3065 }
3066 });
3067
3068 window.on_mouse_event({
3069 let pending_mouse_down = pending_mouse_down.clone();
3070 let hitbox = hitbox.clone();
3071 move |event: &MouseMoveEvent, phase, window, cx| {
3072 if phase == DispatchPhase::Capture {
3073 return;
3074 }
3075
3076 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3077 if let Some(mouse_down) = pending_mouse_down.clone()
3078 && !cx.has_active_drag()
3079 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
3080 && let Some(listener) = drag_listener.take()
3081 && mouse_down.button == MouseButton::Left
3082 {
3083 *clicked_state.borrow_mut() = ElementClickedState::default();
3084 let cursor_offset = event.position - hitbox.origin;
3085 let drag = (listener.render)(
3086 listener.value.as_ref(),
3087 cursor_offset,
3088 window,
3089 cx,
3090 );
3091 let external_payload_source =
3092 listener.external_payload.map(|external_payload| {
3093 let value = listener.value.clone();
3094 Box::new(move |window: &mut Window, cx: &mut App| {
3095 external_payload(value.as_ref(), window, cx)
3096 })
3097 as ExternalDragPayloadSource
3098 });
3099 cx.active_drag = Some(AnyDrag {
3100 view: drag,
3101 value: listener.value,
3102 cursor_offset,
3103 cursor_style: drag_cursor_style,
3104 external_payload_source,
3105 });
3106 pending_mouse_down.take();
3107 window.refresh();
3108 cx.stop_propagation();
3109 }
3110 }
3111 });
3112
3113 if is_focused {
3114 window.on_key_event({
3124 let pending_keyboard_down = pending_keyboard_down.clone();
3125 move |event: &KeyDownEvent, phase, window, _cx| {
3126 if phase.bubble() && !window.default_prevented() {
3127 let stroke = &event.keystroke;
3128 let is_activation_key = (stroke.key.eq("enter")
3129 || stroke.key.eq("space"))
3130 && !stroke.modifiers.modified();
3131 *pending_keyboard_down.borrow_mut() =
3132 is_activation_key.then_some(window.focus_generation);
3133 }
3134 }
3135 });
3136
3137 window.on_key_event({
3139 let click_listeners = click_listeners.clone();
3140 let hitbox = hitbox.clone();
3141 move |event: &KeyUpEvent, phase, window, cx| {
3142 if phase.bubble() && !window.default_prevented() {
3143 let stroke = &event.keystroke;
3144 let keyboard_button = if stroke.key.eq("enter") {
3145 Some(KeyboardButton::Enter)
3146 } else if stroke.key.eq("space") {
3147 Some(KeyboardButton::Space)
3148 } else {
3149 None
3150 };
3151
3152 if let Some(button) = keyboard_button
3153 && !stroke.modifiers.modified()
3154 {
3155 let pending =
3156 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
3157 if pending != Some(window.focus_generation) {
3158 return;
3159 }
3160
3161 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
3162 button,
3163 bounds: hitbox.bounds,
3164 });
3165
3166 for listener in &click_listeners {
3167 listener(&click_event, window, cx);
3168 }
3169 } else {
3170 *pending_keyboard_down.borrow_mut() = None;
3174 }
3175 }
3176 }
3177 });
3178 }
3179
3180 window.on_mouse_event({
3181 let mut captured_mouse_down = None;
3182 let hitbox = hitbox.clone();
3183 move |event: &MouseUpEvent, phase, window, cx| match phase {
3184 DispatchPhase::Capture => {
3188 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3189 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
3190 captured_mouse_down = pending_mouse_down.take();
3191 window.refresh();
3192 } else if pending_mouse_down.is_some() {
3193 pending_mouse_down.take();
3199 window.refresh();
3200 }
3201 }
3202 DispatchPhase::Bubble => {
3204 if let Some(mouse_down) = captured_mouse_down.take() {
3205 let btn = mouse_down.button;
3206
3207 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
3208 down: mouse_down,
3209 up: event.clone(),
3210 });
3211
3212 match btn {
3213 MouseButton::Left => {
3214 for listener in &click_listeners {
3215 listener(&mouse_click, window, cx);
3216 }
3217 }
3218 _ => {
3219 for listener in &aux_click_listeners {
3220 listener(&mouse_click, window, cx);
3221 }
3222 }
3223 }
3224 }
3225 }
3226 }
3227 });
3228 }
3229
3230 if let Some(hover_listener) = self.hover_listener.take() {
3231 let was_hovered = element_state
3232 .hover_listener_state
3233 .get_or_insert_with(Default::default)
3234 .clone();
3235 let has_mouse_down = element_state
3236 .pending_mouse_down
3237 .get_or_insert_with(Default::default)
3238 .clone();
3239 let hover_listener = crate::fast::layers::hover_freeze::track_listener(
3240 window,
3241 &was_hovered,
3242 &has_mouse_down,
3243 hover_listener,
3244 hitbox,
3245 self.hover_listener_mode,
3246 );
3247 let hover_listener_state = was_hovered.clone();
3248 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3249 let mut was_hovered = hover_listener_state.borrow_mut();
3250 if is_hovered != *was_hovered {
3251 *was_hovered = is_hovered;
3252 drop(was_hovered);
3253 hover_listener(&is_hovered, window, cx);
3254 }
3255 };
3256 let hover_listener_mode = self.hover_listener_mode;
3257
3258 if has_mouse_down.borrow().is_none()
3259 && !crate::fast::layers::hover_freeze::holds_listeners(window)
3260 {
3261 let is_hovered =
3262 !cx.has_active_drag() && hover_listener_mode.is_hovered(hitbox, window);
3263 if is_hovered != *was_hovered.borrow() {
3264 let update_hover = update_hover.clone();
3265 window.defer(cx, move |window, cx| {
3266 update_hover(is_hovered, window, cx);
3267 });
3268 }
3269 }
3270
3271 window.on_mouse_event({
3272 let update_hover = update_hover.clone();
3273 let hitbox = hitbox.clone();
3274 move |_: &MouseMoveEvent, phase, window, cx| {
3275 if phase == DispatchPhase::Bubble {
3276 let is_hovered = has_mouse_down.borrow().is_none()
3277 && !cx.has_active_drag()
3278 && hover_listener_mode.is_hovered(&hitbox, window);
3279 update_hover(is_hovered, window, cx);
3280 }
3281 }
3282 });
3283
3284 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3287 if phase == DispatchPhase::Bubble {
3288 update_hover(false, window, cx);
3289 }
3290 });
3291 }
3292
3293 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3294 let active_tooltip = element_state
3295 .active_tooltip
3296 .get_or_insert_with(Default::default)
3297 .clone();
3298 let pending_mouse_down = element_state
3299 .pending_mouse_down
3300 .get_or_insert_with(Default::default)
3301 .clone();
3302 let long_press_tooltip_active = element_state
3303 .long_press_tooltip_active
3304 .get_or_insert_with(Default::default)
3305 .clone();
3306
3307 let tooltip_is_hoverable = tooltip_builder.hoverable;
3308 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3309 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3310 });
3311 let check_is_hovered_during_prepaint = Rc::new({
3313 let pending_mouse_down = pending_mouse_down.clone();
3314 let source_bounds = hitbox.bounds;
3315 move |window: &Window| {
3316 !window.last_input_was_keyboard()
3317 && pending_mouse_down.borrow().is_none()
3318 && source_bounds.contains(&window.mouse_position())
3319 }
3320 });
3321 let check_is_hovered = Rc::new({
3322 let hitbox = hitbox.clone();
3323 move |window: &Window| {
3324 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3325 }
3326 });
3327 register_tooltip_mouse_handlers(
3328 &active_tooltip,
3329 self.tooltip_id,
3330 build_tooltip,
3331 check_is_hovered,
3332 check_is_hovered_during_prepaint,
3333 long_press_tooltip_active,
3334 self.tooltip_show_delay,
3335 window,
3336 );
3337 }
3338
3339 let active_state = element_state
3342 .clicked_state
3343 .get_or_insert_with(Default::default)
3344 .clone();
3345
3346 {
3347 let active_state = active_state.clone();
3348 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3349 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3350 *active_state.borrow_mut() = ElementClickedState::default();
3351 window.refresh();
3352 }
3353 });
3354 }
3355
3356 {
3357 let active_group_hitbox = self
3358 .group_active_style
3359 .as_ref()
3360 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3361 let hitbox = hitbox.clone();
3362 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3363 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3364 let group_hovered = active_group_hitbox
3365 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3366 let element_hovered = hitbox.is_hovered(window);
3367 if group_hovered || element_hovered {
3368 *active_state.borrow_mut() = ElementClickedState {
3369 group: group_hovered,
3370 element: element_hovered,
3371 };
3372 window.refresh();
3373 }
3374 }
3375 });
3376 }
3377 }
3378 }
3379
3380 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3381 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3382 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3383 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3384 let action_listeners = mem::take(&mut self.action_listeners);
3385 if let Some(context) = self.key_context.clone() {
3386 window.set_key_context(context);
3387 }
3388
3389 for listener in key_down_listeners {
3390 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3391 listener(event, phase, window, cx);
3392 })
3393 }
3394
3395 for listener in key_up_listeners {
3396 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3397 listener(event, phase, window, cx);
3398 })
3399 }
3400
3401 for listener in modifiers_changed_listeners {
3402 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3403 listener(event, window, cx);
3404 })
3405 }
3406
3407 for (action_type, listener) in action_listeners {
3408 window.on_action(action_type, listener)
3409 }
3410 }
3411
3412 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3413 let group_hitbox = self
3414 .group_hover_style
3415 .as_ref()
3416 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3417
3418 if let Some(group_hitbox) = group_hitbox {
3419 let was_hovered = group_hitbox.is_hovered(window);
3420 let current_view = window.current_view();
3421 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
3422 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3423 let hovered = group_hitbox.is_hovered(window);
3424 if phase == DispatchPhase::Capture && hovered != was_hovered {
3425 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
3426 cx.notify(current_view);
3427 }
3428 });
3429 }
3430 }
3431
3432 fn paint_scroll_listener(
3433 &self,
3434 hitbox: &Hitbox,
3435 style: &Style,
3436 window: &mut Window,
3437 _cx: &mut App,
3438 ) {
3439 if let Some(scroll_offset) = self.scroll_offset.clone() {
3440 let ongoing_scroll = self.ongoing_scroll.clone();
3441 let overflow = style.overflow;
3442 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3443 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3444 let line_height = window.line_height();
3445 let fast_scroll_max =
3446 crate::fast::layers::wheel::scroll_max(self, hitbox.bounds, style, window);
3447 let hitbox = hitbox.clone();
3448 let current_view = window.current_view();
3449 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
3450 let fast_container = crate::fast::layers::invalidate::painted_container(window, self);
3451 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
3452 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3453 let mut scroll_offset = scroll_offset.borrow_mut();
3454 let old_scroll_offset = *scroll_offset;
3455 let mut delta = event.delta.pixel_delta(line_height);
3456
3457 if restrict_scroll_to_axis
3458 && event.delta.precise()
3459 && let Some(ongoing_scroll) = &ongoing_scroll
3460 {
3461 ongoing_scroll
3462 .borrow_mut()
3463 .filter(&mut delta, event.touch_phase);
3464 }
3465
3466 let mut delta_x = match overflow.x {
3467 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3468 Overflow::Scroll
3469 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3470 {
3471 delta.y
3472 }
3473 _ => Pixels::ZERO,
3474 };
3475 let mut delta_y = match overflow.y {
3476 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3477 Overflow::Scroll
3478 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3479 {
3480 delta.x
3481 }
3482 _ => Pixels::ZERO,
3483 };
3484 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3485 if delta_x.abs() > delta_y.abs() {
3486 delta_y = Pixels::ZERO;
3487 } else {
3488 delta_x = Pixels::ZERO;
3489 }
3490 }
3491 if !crate::fast::layers::wheel::moves(
3492 old_scroll_offset,
3493 point(delta_x, delta_y),
3494 fast_scroll_max,
3495 ) {
3496 return;
3497 }
3498 scroll_offset.y += delta_y;
3499 scroll_offset.x += delta_x;
3500 if *scroll_offset != old_scroll_offset {
3501 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
3502 crate::fast::layers::invalidate::note_scrolled(window, &fast_container);
3503 cx.notify(current_view);
3504 }
3505 }
3506 });
3507 }
3508 }
3509
3510 pub fn compute_style(
3512 &self,
3513 global_id: Option<&GlobalElementId>,
3514 hitbox: Option<&Hitbox>,
3515 window: &mut Window,
3516 cx: &mut App,
3517 ) -> Style {
3518 window.with_optional_element_state(global_id, |element_state, window| {
3519 let mut element_state =
3520 element_state.map(|element_state| element_state.unwrap_or_default());
3521 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3522 (style, element_state)
3523 })
3524 }
3525
3526 fn compute_style_internal(
3528 &self,
3529 hitbox: Option<&Hitbox>,
3530 element_state: Option<&mut InteractiveElementState>,
3531 window: &mut Window,
3532 cx: &mut App,
3533 ) -> Style {
3534 let mut style = Style::default();
3535 style.refine(&self.base_style);
3536
3537 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3538 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3539 && focus_handle.within_focused(window, cx)
3540 {
3541 style.refine(in_focus_style);
3542 }
3543
3544 if let Some(focus_style) = self.focus_style.as_ref()
3545 && focus_handle.is_focused(window)
3546 {
3547 style.refine(focus_style);
3548 }
3549
3550 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3551 && focus_handle.is_focused(window)
3552 && window.last_input_was_keyboard()
3553 {
3554 style.refine(focus_visible_style);
3555 }
3556 }
3557
3558 if !cx.has_active_drag() {
3559 if let Some(group_hover) = self.group_hover_style.as_ref() {
3560 let is_group_hovered =
3561 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3562 !window.last_input_was_touch() && group_hitbox_id.is_hovered(window)
3563 } else if let Some(element_state) = element_state.as_ref() {
3564 !window.last_input_was_touch()
3565 && element_state
3566 .hover_state
3567 .as_ref()
3568 .map(|state| state.borrow().group)
3569 .unwrap_or(false)
3570 } else {
3571 false
3572 };
3573
3574 if is_group_hovered {
3575 style.refine(&group_hover.style);
3576 }
3577 }
3578
3579 if let Some(hover_style) = self.hover_style.as_ref() {
3580 let is_hovered = if let Some(hitbox) = hitbox {
3581 !window.last_input_was_touch() && hitbox.is_hovered(window)
3582 } else if let Some(element_state) = element_state.as_ref() {
3583 !window.last_input_was_touch()
3584 && element_state
3585 .hover_state
3586 .as_ref()
3587 .map(|state| state.borrow().element)
3588 .unwrap_or(false)
3589 } else {
3590 false
3591 };
3592
3593 if is_hovered {
3594 style.refine(hover_style);
3595 }
3596 }
3597 }
3598
3599 if let Some(hitbox) = hitbox {
3600 if let Some(drag) = cx.active_drag.take() {
3601 let mut can_drop = true;
3602 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3603 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3604 }
3605
3606 if can_drop {
3607 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3608 if let Some(group_hitbox_id) =
3609 GroupHitboxes::get(&group_drag_style.group, cx)
3610 && *state_type == drag.value.as_ref().type_id()
3611 && group_hitbox_id.is_hovered(window)
3612 {
3613 style.refine(&group_drag_style.style);
3614 }
3615 }
3616
3617 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3618 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3619 {
3620 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3621 }
3622 }
3623 }
3624
3625 style.mouse_cursor = drag.cursor_style;
3626 cx.active_drag = Some(drag);
3627 }
3628 }
3629
3630 if let Some(element_state) = element_state {
3631 let clicked_state = element_state
3632 .clicked_state
3633 .get_or_insert_with(Default::default)
3634 .borrow();
3635 if clicked_state.group
3636 && let Some(group) = self.group_active_style.as_ref()
3637 {
3638 style.refine(&group.style)
3639 }
3640
3641 if let Some(active_style) = self.active_style.as_ref()
3642 && clicked_state.element
3643 {
3644 style.refine(active_style)
3645 }
3646 }
3647
3648 style
3649 }
3650
3651 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3652 if let Some(id) = &self.aria.author_id {
3653 node.set_author_id(id.to_string());
3654 }
3655 if let Some(label) = &self.aria.label {
3656 node.set_label(label.to_string());
3657 }
3658 if let Some(description) = &self.aria.description {
3659 node.set_description(description.to_string());
3660 }
3661 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3662 node.set_keyboard_shortcut(keyshortcuts.to_string());
3663 }
3664 if let Some(selected) = self.aria.selected {
3665 node.set_selected(selected);
3666 }
3667 if let Some(expanded) = self.aria.expanded {
3668 node.set_expanded(expanded);
3669 }
3670 if let Some(toggled) = self.aria.toggled {
3671 node.set_toggled(toggled);
3672 }
3673 if let Some(value) = self.aria.numeric_value {
3674 node.set_numeric_value(value);
3675 }
3676 if let Some(value) = self.aria.min_numeric_value {
3677 node.set_min_numeric_value(value);
3678 }
3679 if let Some(value) = self.aria.max_numeric_value {
3680 node.set_max_numeric_value(value);
3681 }
3682 if let Some(step) = self.aria.numeric_value_step {
3683 node.set_numeric_value_step(step);
3684 }
3685 if let Some(value) = &self.aria.value {
3686 node.set_value(value.to_string());
3687 }
3688 if let Some(placeholder) = &self.aria.placeholder {
3689 node.set_placeholder(placeholder.to_string());
3690 }
3691 if let Some(orientation) = self.aria.orientation {
3692 node.set_orientation(orientation);
3693 }
3694 if let Some(level) = self.aria.level {
3695 node.set_level(level);
3696 }
3697 if let Some(position) = self.aria.position_in_set {
3698 node.set_position_in_set(position);
3699 }
3700 if let Some(size) = self.aria.size_of_set {
3701 node.set_size_of_set(size);
3702 }
3703 if let Some(index) = self.aria.row_index {
3704 node.set_row_index(index);
3705 }
3706 if let Some(index) = self.aria.column_index {
3707 node.set_column_index(index);
3708 }
3709 if let Some(count) = self.aria.row_count {
3710 node.set_row_count(count);
3711 }
3712 if let Some(count) = self.aria.column_count {
3713 node.set_column_count(count);
3714 }
3715 if !self.click_listeners.is_empty() {
3716 node.add_action(accesskit::Action::Click);
3717 }
3718 if self.tracked_focus_handle.is_some() || self.focusable {
3719 node.add_action(accesskit::Action::Focus);
3720 }
3721 for (action, _) in &self.a11y_action_listeners {
3722 node.add_action(*action);
3723 }
3724 }
3725}
3726
3727#[derive(Default)]
3730pub struct InteractiveElementState {
3731 pub(crate) focus_handle: Option<FocusHandle>,
3732 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3733 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3734 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3735 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3736 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3744 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3745 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3746 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3747 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3748}
3749
3750#[derive(Copy, Clone, Default, Eq, PartialEq)]
3752pub struct ElementClickedState {
3753 pub group: bool,
3755
3756 pub element: bool,
3758}
3759
3760impl ElementClickedState {
3761 fn is_clicked(&self) -> bool {
3762 self.group || self.element
3763 }
3764}
3765
3766#[derive(Copy, Clone, Default, Eq, PartialEq)]
3768pub struct ElementHoverState {
3769 pub group: bool,
3771
3772 pub element: bool,
3774}
3775
3776pub(crate) enum ActiveTooltip {
3777 WaitingForShow { _task: Task<()> },
3779 Visible {
3781 tooltip: AnyTooltip,
3782 is_hoverable: bool,
3783 },
3784 WaitingForHide {
3787 tooltip: AnyTooltip,
3788 _task: Task<()>,
3789 },
3790}
3791
3792pub(crate) fn clear_active_tooltip(
3793 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3794 window: &mut Window,
3795) {
3796 match active_tooltip.borrow_mut().take() {
3797 None => {}
3798 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3799 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3800 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3801 }
3802}
3803
3804pub(crate) fn clear_active_tooltip_if_not_hoverable(
3805 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3806 window: &mut Window,
3807) {
3808 let should_clear = match active_tooltip.borrow().as_ref() {
3809 None => false,
3810 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3811 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3812 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3813 };
3814 if should_clear {
3815 active_tooltip.borrow_mut().take();
3816 window.refresh();
3817 }
3818}
3819
3820pub(crate) fn set_tooltip_on_window(
3821 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3822 window: &mut Window,
3823) -> Option<TooltipId> {
3824 let tooltip = match active_tooltip.borrow().as_ref() {
3825 None => return None,
3826 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3827 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3828 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3829 };
3830 Some(window.set_tooltip(tooltip))
3831}
3832
3833pub(crate) fn register_tooltip_mouse_handlers(
3834 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3835 tooltip_id: Option<TooltipId>,
3836 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3837 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3838 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3839 long_press_tooltip_active: Rc<Cell<bool>>,
3840 show_delay: Option<Duration>,
3841 window: &mut Window,
3842) {
3843 let current_view = window.current_view();
3844 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3845
3846 window.on_mouse_event({
3847 let active_tooltip = active_tooltip.clone();
3848 let build_tooltip = build_tooltip.clone();
3849 let check_is_hovered = check_is_hovered.clone();
3850 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3851 move |_: &MouseMoveEvent, phase, window, cx| {
3852 handle_tooltip_mouse_move(
3853 &active_tooltip,
3854 &build_tooltip,
3855 &check_is_hovered,
3856 &check_is_hovered_during_prepaint,
3857 tooltip_id,
3858 current_view,
3859 phase,
3860 show_delay,
3861 window,
3862 cx,
3863 )
3864 }
3865 });
3866
3867 window.on_mouse_event({
3868 let active_tooltip = active_tooltip.clone();
3869 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3870 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3871 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3872 }
3873 }
3874 });
3875
3876 window.on_mouse_event({
3877 let active_tooltip = active_tooltip.clone();
3878 let build_tooltip = build_tooltip.clone();
3879 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3880 move |event: &LongPressEvent, phase, window, cx| {
3881 if !phase.bubble() {
3882 return;
3883 }
3884
3885 match event.phase {
3886 TouchPhase::Started if !window.default_prevented() && check_is_hovered(window) => {
3887 if show_tooltip(
3888 &active_tooltip,
3889 &build_tooltip,
3890 &check_is_hovered_during_prepaint,
3891 Some(long_press_tooltip_active.clone()),
3892 window,
3893 cx,
3894 ) {
3895 long_press_tooltip_active.set(true);
3896 window.prevent_default();
3897 cx.stop_propagation();
3898 }
3899 }
3900 TouchPhase::Ended | TouchPhase::Cancelled
3901 if long_press_tooltip_active.replace(false) =>
3902 {
3903 clear_active_tooltip(&active_tooltip, window);
3904 cx.stop_propagation();
3905 }
3906 TouchPhase::Started
3907 | TouchPhase::Moved
3908 | TouchPhase::Ended
3909 | TouchPhase::Cancelled => {}
3910 }
3911 }
3912 });
3913
3914 window.on_mouse_event({
3915 let active_tooltip = active_tooltip.clone();
3916 move |_: &ScrollEvent, _phase, window: &mut Window, _cx| {
3917 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3918 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3919 }
3920 }
3921 });
3922}
3923
3924fn handle_tooltip_mouse_move(
3936 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3937 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3938 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3939 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3940 tooltip_id: Option<TooltipId>,
3941 current_view: EntityId,
3942 phase: DispatchPhase,
3943 show_delay: Duration,
3944 window: &mut Window,
3945 cx: &mut App,
3946) {
3947 enum Action {
3950 None,
3951 CancelShow,
3952 ScheduleShow,
3953 CheckVisible,
3954 }
3955
3956 let action = match active_tooltip.borrow().as_ref() {
3957 None => {
3958 let is_hovered = check_is_hovered(window);
3959 if is_hovered && phase.bubble() {
3960 Action::ScheduleShow
3961 } else {
3962 Action::None
3963 }
3964 }
3965 Some(ActiveTooltip::WaitingForShow { .. }) => {
3966 let is_hovered = check_is_hovered(window);
3967 if is_hovered {
3968 Action::None
3969 } else {
3970 Action::CancelShow
3971 }
3972 }
3973 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3974 if phase.capture()
3975 && !check_is_hovered(window)
3976 && (!*is_hoverable
3977 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3978 {
3979 Action::CheckVisible
3980 } else {
3981 Action::None
3982 }
3983 }
3984 Some(ActiveTooltip::WaitingForHide { .. }) => {
3985 if phase.capture()
3986 && (check_is_hovered(window)
3987 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3988 {
3989 Action::CheckVisible
3990 } else {
3991 Action::None
3992 }
3993 }
3994 };
3995
3996 match action {
3997 Action::None => {}
3998 Action::CancelShow => {
3999 active_tooltip.borrow_mut().take();
4001 }
4002 Action::ScheduleShow => {
4003 let delayed_show_task = window.spawn(cx, {
4004 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4005 let build_tooltip = build_tooltip.clone();
4006 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4007 async move |cx| {
4008 cx.background_executor().timer(show_delay).await;
4009 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4010 return;
4011 };
4012 cx.update(|window, cx| {
4013 show_tooltip(
4014 &active_tooltip,
4015 &build_tooltip,
4016 &check_is_hovered_during_prepaint,
4017 None,
4018 window,
4019 cx,
4020 );
4021 })
4022 .ok();
4023 }
4024 });
4025 active_tooltip
4026 .borrow_mut()
4027 .replace(ActiveTooltip::WaitingForShow {
4028 _task: delayed_show_task,
4029 });
4030 }
4031 Action::CheckVisible => cx.notify(current_view),
4032 }
4033}
4034
4035fn show_tooltip(
4036 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4037 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4038 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
4039 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
4040 window: &mut Window,
4041 cx: &mut App,
4042) -> bool {
4043 let new_tooltip = build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
4044 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4045 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4046 ActiveTooltip::Visible {
4047 tooltip: AnyTooltip {
4048 view,
4049 mouse_position: window.mouse_position(),
4050 check_visible_and_update: Rc::new(move |tooltip_bounds, window, cx| {
4051 if long_press_tooltip_active
4052 .as_ref()
4053 .is_some_and(|active| active.get())
4054 {
4055 return true;
4056 }
4057 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4058 return false;
4059 };
4060 handle_tooltip_check_visible_and_update(
4061 &active_tooltip,
4062 tooltip_is_hoverable,
4063 &check_is_hovered_during_prepaint,
4064 tooltip_bounds,
4065 window,
4066 cx,
4067 )
4068 }),
4069 },
4070 is_hoverable: tooltip_is_hoverable,
4071 }
4072 });
4073 let did_show = new_tooltip.is_some();
4074 *active_tooltip.borrow_mut() = new_tooltip;
4075 window.refresh();
4076 did_show
4077}
4078
4079fn handle_tooltip_check_visible_and_update(
4083 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4084 tooltip_is_hoverable: bool,
4085 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
4086 tooltip_bounds: Bounds<Pixels>,
4087 window: &mut Window,
4088 cx: &mut App,
4089) -> bool {
4090 enum Action {
4093 None,
4094 Hide,
4095 ScheduleHide(AnyTooltip),
4096 CancelHide(AnyTooltip),
4097 }
4098
4099 let is_hovered = check_is_hovered(window)
4100 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
4101 let action = match active_tooltip.borrow().as_ref() {
4102 Some(ActiveTooltip::Visible { tooltip, .. }) => {
4103 if is_hovered {
4104 Action::None
4105 } else {
4106 if tooltip_is_hoverable {
4107 Action::ScheduleHide(tooltip.clone())
4108 } else {
4109 Action::Hide
4110 }
4111 }
4112 }
4113 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
4114 if is_hovered {
4115 Action::CancelHide(tooltip.clone())
4116 } else {
4117 Action::None
4118 }
4119 }
4120 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
4121 };
4122
4123 match action {
4124 Action::None => {}
4125 Action::Hide => clear_active_tooltip(active_tooltip, window),
4126 Action::ScheduleHide(tooltip) => {
4127 let delayed_hide_task = window.spawn(cx, {
4128 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4129 async move |cx| {
4130 cx.background_executor()
4131 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
4132 .await;
4133 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4134 return;
4135 };
4136 if active_tooltip.borrow_mut().take().is_some() {
4137 cx.update(|window, _cx| window.refresh()).ok();
4138 }
4139 }
4140 });
4141 active_tooltip
4142 .borrow_mut()
4143 .replace(ActiveTooltip::WaitingForHide {
4144 tooltip,
4145 _task: delayed_hide_task,
4146 });
4147 }
4148 Action::CancelHide(tooltip) => {
4149 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
4151 tooltip,
4152 is_hoverable: true,
4153 });
4154 }
4155 }
4156
4157 active_tooltip.borrow().is_some()
4158}
4159
4160#[derive(Default)]
4161pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
4162
4163impl Global for GroupHitboxes {}
4164
4165impl GroupHitboxes {
4166 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
4167 cx.default_global::<Self>()
4168 .0
4169 .get(name)
4170 .and_then(|bounds_stack| bounds_stack.last())
4171 .cloned()
4172 }
4173
4174 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
4175 cx.default_global::<Self>()
4176 .0
4177 .entry(name)
4178 .or_default()
4179 .push(hitbox_id);
4180 }
4181
4182 pub fn pop(name: &SharedString, cx: &mut App) {
4183 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
4184 }
4185}
4186
4187pub struct Stateful<E> {
4189 pub(crate) element: E,
4190}
4191
4192impl<E> Styled for Stateful<E>
4193where
4194 E: Styled,
4195{
4196 fn style(&mut self) -> &mut StyleRefinement {
4197 self.element.style()
4198 }
4199}
4200
4201impl<E> StatefulInteractiveElement for Stateful<E>
4202where
4203 E: Element,
4204 Self: InteractiveElement,
4205{
4206}
4207
4208impl<E> InteractiveElement for Stateful<E>
4209where
4210 E: InteractiveElement,
4211{
4212 fn interactivity(&mut self) -> &mut Interactivity {
4213 self.element.interactivity()
4214 }
4215}
4216
4217impl<E> Element for Stateful<E>
4218where
4219 E: Element,
4220{
4221 type RequestLayoutState = E::RequestLayoutState;
4222 type PrepaintState = E::PrepaintState;
4223
4224 fn id(&self) -> Option<ElementId> {
4225 self.element.id()
4226 }
4227
4228 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4229 self.element.source_location()
4230 }
4231
4232 fn a11y_role(&self) -> Option<accesskit::Role> {
4233 self.element.a11y_role()
4234 }
4235
4236 fn write_a11y_info(&self, node: &mut accesskit::Node) {
4237 self.element.write_a11y_info(node);
4238 }
4239
4240 fn a11y_synthetic_children(
4241 &mut self,
4242 prepaint: &mut Self::PrepaintState,
4243 builder: &mut crate::A11ySubtreeBuilder,
4244 ) {
4245 self.element.a11y_synthetic_children(prepaint, builder);
4246 }
4247
4248 fn request_layout(
4249 &mut self,
4250 id: Option<&GlobalElementId>,
4251 inspector_id: Option<&InspectorElementId>,
4252 window: &mut Window,
4253 cx: &mut App,
4254 ) -> (LayoutId, Self::RequestLayoutState) {
4255 self.element.request_layout(id, inspector_id, window, cx)
4256 }
4257
4258 fn prepaint(
4259 &mut self,
4260 id: Option<&GlobalElementId>,
4261 inspector_id: Option<&InspectorElementId>,
4262 bounds: Bounds<Pixels>,
4263 state: &mut Self::RequestLayoutState,
4264 window: &mut Window,
4265 cx: &mut App,
4266 ) -> E::PrepaintState {
4267 self.element
4268 .prepaint(id, inspector_id, bounds, state, window, cx)
4269 }
4270
4271 fn paint(
4272 &mut self,
4273 id: Option<&GlobalElementId>,
4274 inspector_id: Option<&InspectorElementId>,
4275 bounds: Bounds<Pixels>,
4276 request_layout: &mut Self::RequestLayoutState,
4277 prepaint: &mut Self::PrepaintState,
4278 window: &mut Window,
4279 cx: &mut App,
4280 ) {
4281 self.element.paint(
4282 id,
4283 inspector_id,
4284 bounds,
4285 request_layout,
4286 prepaint,
4287 window,
4288 cx,
4289 );
4290 }
4291}
4292
4293impl<E> IntoElement for Stateful<E>
4294where
4295 E: Element,
4296{
4297 type Element = Self;
4298
4299 fn into_element(self) -> Self::Element {
4300 self
4301 }
4302}
4303
4304impl<E> ParentElement for Stateful<E>
4305where
4306 E: ParentElement,
4307{
4308 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4309 self.element.extend(elements)
4310 }
4311}
4312
4313#[derive(Clone)]
4316pub struct ScrollAnchor {
4317 handle: ScrollHandle,
4318 last_origin: Rc<RefCell<Point<Pixels>>>,
4319}
4320
4321impl ScrollAnchor {
4322 pub fn for_handle(handle: ScrollHandle) -> Self {
4324 Self {
4325 handle,
4326 last_origin: Default::default(),
4327 }
4328 }
4329 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4331 let this = self.clone();
4332
4333 window.on_next_frame(move |_, _| {
4334 let viewport_bounds = this.handle.bounds();
4335 let self_bounds = *this.last_origin.borrow();
4336 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4337 });
4338 }
4339}
4340
4341#[derive(Default, Debug)]
4342pub(crate) struct ScrollHandleState {
4343 pub(crate) offset: Rc<RefCell<Point<Pixels>>>,
4344 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4345 bounds: Bounds<Pixels>,
4346 pub(crate) max_offset: Point<Pixels>,
4347 child_bounds: Vec<Bounds<Pixels>>,
4348 pub(crate) scroll_to_bottom: bool,
4349 overflow: Point<Overflow>,
4350 active_item: Option<ScrollActiveItem>,
4351 pub(crate) version: crate::fast::dependencies::StateVersion,
4352}
4353
4354#[derive(Default, Debug, Clone, Copy)]
4355struct ScrollActiveItem {
4356 index: usize,
4357 strategy: ScrollStrategy,
4358}
4359
4360#[derive(Default, Debug, Clone, Copy)]
4361enum ScrollStrategy {
4362 #[default]
4363 FirstVisible,
4364 Top,
4365}
4366
4367#[derive(Clone, Debug)]
4371pub struct ScrollHandle(pub(crate) Rc<RefCell<ScrollHandleState>>);
4372
4373impl Default for ScrollHandle {
4374 fn default() -> Self {
4375 Self::new()
4376 }
4377}
4378
4379impl ScrollHandle {
4380 pub fn new() -> Self {
4382 Self(Rc::default())
4383 }
4384
4385 pub fn offset(&self) -> Point<Pixels> {
4387 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
4388 *self.0.borrow().offset.borrow()
4389 }
4390
4391 pub fn max_offset(&self) -> Point<Pixels> {
4393 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
4394 self.0.borrow().max_offset
4395 }
4396
4397 pub fn top_item(&self) -> usize {
4399 let state = self.0.borrow();
4400 crate::fast::layers::invalidate::note_offset_read(&state.version);
4401 let top = state.bounds.top() - state.offset.borrow().y;
4402
4403 match state.child_bounds.binary_search_by(|bounds| {
4404 if top < bounds.top() {
4405 Ordering::Greater
4406 } else if top > bounds.bottom() {
4407 Ordering::Less
4408 } else {
4409 Ordering::Equal
4410 }
4411 }) {
4412 Ok(ix) => ix,
4413 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4414 }
4415 }
4416
4417 pub fn bottom_item(&self) -> usize {
4419 let state = self.0.borrow();
4420 crate::fast::layers::invalidate::note_offset_read(&state.version);
4421 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4422
4423 match state.child_bounds.binary_search_by(|bounds| {
4424 if bottom < bounds.top() {
4425 Ordering::Greater
4426 } else if bottom > bounds.bottom() {
4427 Ordering::Less
4428 } else {
4429 Ordering::Equal
4430 }
4431 }) {
4432 Ok(ix) => ix,
4433 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4434 }
4435 }
4436
4437 pub fn bounds(&self) -> Bounds<Pixels> {
4439 crate::fast::layers::input::moved(&self.0, Some(self.0.borrow().bounds)).unwrap_or_default()
4440 }
4441
4442 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4444 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
4445 crate::fast::layers::input::moved(&self.0, self.0.borrow().child_bounds.get(ix).cloned())
4446 }
4447
4448 pub fn scroll_to_item(&self, ix: usize) {
4450 let mut state = self.0.borrow_mut();
4451 crate::fast::dependencies::StateVersion::bump(&state.version);
4452 state.active_item = Some(ScrollActiveItem {
4453 index: ix,
4454 strategy: ScrollStrategy::default(),
4455 });
4456 }
4457
4458 pub fn scroll_to_top_of_item(&self, ix: usize) {
4461 let mut state = self.0.borrow_mut();
4462 crate::fast::dependencies::StateVersion::bump(&state.version);
4463 state.active_item = Some(ScrollActiveItem {
4464 index: ix,
4465 strategy: ScrollStrategy::Top,
4466 });
4467 }
4468
4469 fn scroll_to_active_item(&self) {
4473 let mut state = self.0.borrow_mut();
4474
4475 let Some(active_item) = state.active_item else {
4476 return;
4477 };
4478
4479 let active_item = match state.child_bounds.get(active_item.index) {
4480 Some(bounds) => {
4481 let mut scroll_offset = state.offset.borrow_mut();
4482
4483 match active_item.strategy {
4484 ScrollStrategy::FirstVisible => {
4485 if state.overflow.y == Overflow::Scroll {
4486 let child_height = bounds.size.height;
4487 let viewport_height = state.bounds.size.height;
4488 if child_height > viewport_height {
4489 scroll_offset.y = state.bounds.top() - bounds.top();
4490 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4491 scroll_offset.y = state.bounds.top() - bounds.top();
4492 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4493 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4494 }
4495 }
4496 }
4497 ScrollStrategy::Top => {
4498 scroll_offset.y = state.bounds.top() - bounds.top();
4499 }
4500 }
4501
4502 if state.overflow.x == Overflow::Scroll {
4503 let child_width = bounds.size.width;
4504 let viewport_width = state.bounds.size.width;
4505 if child_width > viewport_width {
4506 scroll_offset.x = state.bounds.left() - bounds.left();
4507 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4508 scroll_offset.x = state.bounds.left() - bounds.left();
4509 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4510 scroll_offset.x = state.bounds.right() - bounds.right();
4511 }
4512 }
4513 None
4514 }
4515 None => Some(active_item),
4516 };
4517 state.active_item = active_item;
4518 }
4519
4520 pub fn scroll_to_bottom(&self) {
4522 let mut state = self.0.borrow_mut();
4523 crate::fast::layers::scroll_to_bottom::note_scroll_to_bottom(self, &state);
4524 state.scroll_to_bottom = true;
4525 }
4526
4527 pub fn set_offset(&self, position: Point<Pixels>) {
4531 let state = self.0.borrow();
4532 crate::fast::layers::invalidate::offset_set(
4533 &state.version,
4534 *state.offset.borrow() != position,
4535 );
4536 *state.offset.borrow_mut() = position;
4537 }
4538
4539 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4541 let ix = self.top_item();
4542 let state = self.0.borrow();
4543
4544 if let Some(child_bounds) = state.child_bounds.get(ix) {
4545 (
4546 ix,
4547 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4548 )
4549 } else {
4550 (ix, px(0.))
4551 }
4552 }
4553
4554 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4556 let ix = self.bottom_item();
4557 let state = self.0.borrow();
4558
4559 if let Some(child_bounds) = state.child_bounds.get(ix) {
4560 (
4561 ix,
4562 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4563 )
4564 } else {
4565 (ix, px(0.))
4566 }
4567 }
4568
4569 pub fn children_count(&self) -> usize {
4571 self.0.borrow().child_bounds.len()
4572 }
4573}
4574
4575#[cfg(test)]
4576mod tests {
4577 use super::*;
4578 use crate::{
4579 AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, Keystroke,
4580 MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas, util::FluentBuilder as _,
4581 };
4582 use std::{cell::Cell, rc::Weak};
4583
4584 struct GroupHoverTestView {
4585 render_count: Rc<Cell<usize>>,
4586 anonymous_paint_count: Rc<Cell<usize>>,
4587 stateful_width: Rc<Cell<Pixels>>,
4588 }
4589
4590 impl Render for GroupHoverTestView {
4591 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4592 self.render_count.set(self.render_count.get() + 1);
4593 let anonymous_paint_count = self.anonymous_paint_count.clone();
4594 let stateful_width = self.stateful_width.clone();
4595 div().size_full().child(
4596 div()
4597 .ml(px(20.))
4598 .mt(px(20.))
4599 .size(px(50.))
4600 .relative()
4601 .group("hover-group")
4602 .child(
4603 div()
4604 .absolute()
4605 .size_full()
4606 .invisible()
4607 .group_hover("hover-group", |style| style.visible())
4608 .child(canvas(
4609 |_, _, _| {},
4610 move |_, _, _, _| {
4611 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4612 },
4613 )),
4614 )
4615 .child(
4616 div()
4617 .id("stateful-group-hover-target")
4618 .absolute()
4619 .top_0()
4620 .left_0()
4621 .size(px(10.))
4622 .group_hover("hover-group", |style| style.size(px(20.)))
4623 .child(canvas(
4624 move |bounds, _, _| stateful_width.set(bounds.size.width),
4625 |_, _, _, _| {},
4626 )),
4627 ),
4628 )
4629 }
4630 }
4631
4632 #[gpui::test]
4633 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4634 let render_count = Rc::new(Cell::new(0));
4635 let anonymous_paint_count = Rc::new(Cell::new(0));
4636 let stateful_width = Rc::new(Cell::new(px(0.)));
4637 let window = cx.add_window({
4638 let render_count = render_count.clone();
4639 let anonymous_paint_count = anonymous_paint_count.clone();
4640 let stateful_width = stateful_width.clone();
4641 move |_, _| GroupHoverTestView {
4642 render_count,
4643 anonymous_paint_count,
4644 stateful_width,
4645 }
4646 });
4647 let window = AnyWindowHandle::from(window);
4648
4649 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4650 .unwrap();
4651 assert_eq!(anonymous_paint_count.get(), 0);
4652 assert_eq!(stateful_width.get(), px(10.));
4653
4654 let move_mouse = |cx: &mut TestAppContext, position| {
4655 cx.update_window(window, |_, window, cx| {
4656 window.simulate_mouse_move(position, cx)
4657 })
4658 .unwrap();
4659 };
4660
4661 let initial_render_count = render_count.get();
4662 move_mouse(cx, point(px(25.), px(25.)));
4663 assert_eq!(render_count.get(), initial_render_count + 1);
4664 assert_eq!(anonymous_paint_count.get(), 1);
4665 assert_eq!(stateful_width.get(), px(20.));
4666
4667 move_mouse(cx, point(px(30.), px(30.)));
4668 assert_eq!(render_count.get(), initial_render_count + 1);
4669 assert_eq!(anonymous_paint_count.get(), 1);
4670 assert_eq!(stateful_width.get(), px(20.));
4671
4672 move_mouse(cx, point(px(5.), px(5.)));
4673 assert_eq!(render_count.get(), initial_render_count + 2);
4674 assert_eq!(anonymous_paint_count.get(), 1);
4675 assert_eq!(stateful_width.get(), px(10.));
4676
4677 move_mouse(cx, point(px(10.), px(10.)));
4678 assert_eq!(render_count.get(), initial_render_count + 2);
4679 assert_eq!(anonymous_paint_count.get(), 1);
4680 assert_eq!(stateful_width.get(), px(10.));
4681 }
4682
4683 struct HoverListenerLayoutTestView {
4684 target_left: Pixels,
4685 hover_transitions: Rc<RefCell<Vec<bool>>>,
4686 }
4687
4688 impl Render for HoverListenerLayoutTestView {
4689 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4690 let hover_transitions = self.hover_transitions.clone();
4691 div().relative().size_full().child(
4692 div()
4693 .id("hover-target")
4694 .absolute()
4695 .left(self.target_left)
4696 .top_0()
4697 .size(px(20.))
4698 .on_click(|_, _, _| {})
4699 .on_hover(move |is_hovered, _, _| {
4700 hover_transitions.borrow_mut().push(*is_hovered);
4701 }),
4702 )
4703 }
4704 }
4705
4706 #[gpui::test]
4707 fn default_hover_listener_updates_when_layout_changes_under_stationary_mouse(
4708 cx: &mut TestAppContext,
4709 ) {
4710 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4711 let window = cx.add_window({
4712 let hover_transitions = hover_transitions.clone();
4713 move |_, _| HoverListenerLayoutTestView {
4714 target_left: px(40.),
4715 hover_transitions,
4716 }
4717 });
4718 let any_window = AnyWindowHandle::from(window);
4719
4720 cx.update_window(any_window, |_, window, cx| {
4721 window.draw(cx).clear(cx);
4722 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4723 })
4724 .unwrap();
4725 assert!(hover_transitions.borrow().is_empty());
4726
4727 window
4728 .update(cx, |view, _, cx| {
4729 view.target_left = px(0.);
4730 cx.notify();
4731 })
4732 .unwrap();
4733 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4734 .unwrap();
4735 assert_eq!(*hover_transitions.borrow(), [true]);
4736
4737 window
4738 .update(cx, |view, _, cx| {
4739 view.target_left = px(40.);
4740 cx.notify();
4741 })
4742 .unwrap();
4743 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4744 .unwrap();
4745 assert_eq!(*hover_transitions.borrow(), [true, false]);
4746 }
4747
4748 #[gpui::test]
4749 fn default_hover_listener_ends_after_key_press(cx: &mut TestAppContext) {
4750 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4751 let window = cx.add_window({
4752 let hover_transitions = hover_transitions.clone();
4753 move |_, _| HoverListenerLayoutTestView {
4754 target_left: px(0.),
4755 hover_transitions,
4756 }
4757 });
4758 let any_window = AnyWindowHandle::from(window);
4759
4760 cx.update_window(any_window, |_, window, cx| {
4761 window.draw(cx).clear(cx);
4762 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4763 })
4764 .unwrap();
4765 assert_eq!(*hover_transitions.borrow(), [true]);
4766
4767 key_down(cx, any_window, "a");
4768 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4769 .unwrap();
4770 assert_eq!(*hover_transitions.borrow(), [true, false]);
4771 }
4772
4773 struct HoverListenerModeLayoutTestView {
4774 target_left: Pixels,
4775 hover_transitions: Rc<RefCell<Vec<bool>>>,
4776 }
4777
4778 impl Render for HoverListenerModeLayoutTestView {
4779 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4780 let hover_transitions = self.hover_transitions.clone();
4781 div().relative().size_full().child(
4782 div()
4783 .id("hover-target")
4784 .absolute()
4785 .left(self.target_left)
4786 .top_0()
4787 .size(px(20.))
4788 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
4789 .on_hover(move |is_hovered, _, _| {
4790 hover_transitions.borrow_mut().push(*is_hovered);
4791 }),
4792 )
4793 }
4794 }
4795
4796 #[gpui::test]
4797 fn input_modality_independent_hover_listener_updates_after_key_press(cx: &mut TestAppContext) {
4798 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4799 let window = cx.add_window({
4800 let hover_transitions = hover_transitions.clone();
4801 move |_, _| HoverListenerModeLayoutTestView {
4802 target_left: px(40.),
4803 hover_transitions,
4804 }
4805 });
4806 let any_window = AnyWindowHandle::from(window);
4807 let pointer_position = point(px(10.), px(10.));
4808
4809 cx.update_window(any_window, |_, window, cx| {
4810 window.draw(cx).clear(cx);
4811 window.simulate_mouse_move(pointer_position, cx);
4812 })
4813 .unwrap();
4814 assert!(hover_transitions.borrow().is_empty());
4815
4816 key_down(cx, any_window, "a");
4817 window
4818 .update(cx, |view, _, cx| {
4819 view.target_left = px(0.);
4820 cx.notify();
4821 })
4822 .unwrap();
4823 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4824 .unwrap();
4825 assert_eq!(*hover_transitions.borrow(), [true]);
4826
4827 key_down(cx, any_window, "b");
4828 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4829 .unwrap();
4830 assert_eq!(*hover_transitions.borrow(), [true]);
4831
4832 cx.update_window(any_window, |_, window, cx| {
4833 window.simulate_mouse_move(point(px(30.), px(10.)), cx);
4834 })
4835 .unwrap();
4836 assert_eq!(*hover_transitions.borrow(), [true, false]);
4837
4838 cx.update_window(any_window, |_, window, cx| {
4839 window.simulate_mouse_move(pointer_position, cx);
4840 window.dispatch_event(
4841 MouseExitEvent {
4842 position: pointer_position,
4843 ..Default::default()
4844 }
4845 .to_platform_input(),
4846 cx,
4847 );
4848 })
4849 .unwrap();
4850 assert_eq!(*hover_transitions.borrow(), [true, false, true, false]);
4851 }
4852
4853 #[gpui::test]
4854 fn default_hover_listener_remains_hovered_during_stationary_mouse_press(
4855 cx: &mut TestAppContext,
4856 ) {
4857 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4858 let window = cx.add_window({
4859 let hover_transitions = hover_transitions.clone();
4860 move |_, _| HoverListenerLayoutTestView {
4861 target_left: px(0.),
4862 hover_transitions,
4863 }
4864 });
4865 let any_window = AnyWindowHandle::from(window);
4866 let mouse_position = point(px(10.), px(10.));
4867
4868 cx.update_window(any_window, |_, window, cx| {
4869 window.draw(cx).clear(cx);
4870 window.simulate_mouse_move(mouse_position, 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 MouseDownEvent {
4878 position: mouse_position,
4879 button: MouseButton::Left,
4880 modifiers: Default::default(),
4881 click_count: 1,
4882 first_mouse: false,
4883 }
4884 .to_platform_input(),
4885 cx,
4886 );
4887 window.draw(cx).clear(cx);
4888 })
4889 .unwrap();
4890 assert_eq!(*hover_transitions.borrow(), [true]);
4891
4892 cx.update_window(any_window, |_, window, cx| {
4893 window.dispatch_event(
4894 MouseUpEvent {
4895 position: mouse_position,
4896 button: MouseButton::Left,
4897 modifiers: Default::default(),
4898 click_count: 1,
4899 }
4900 .to_platform_input(),
4901 cx,
4902 );
4903 window.draw(cx).clear(cx);
4904 })
4905 .unwrap();
4906 assert_eq!(*hover_transitions.borrow(), [true]);
4907 }
4908
4909 struct TestTooltipView;
4910
4911 impl Render for TestTooltipView {
4912 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4913 div().w(px(20.)).h(px(20.)).child("tooltip")
4914 }
4915 }
4916
4917 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4918
4919 struct TooltipCaptureElement {
4920 child: AnyElement,
4921 captured_active_tooltip: CapturedActiveTooltip,
4922 }
4923
4924 impl IntoElement for TooltipCaptureElement {
4925 type Element = Self;
4926
4927 fn into_element(self) -> Self::Element {
4928 self
4929 }
4930 }
4931
4932 impl Element for TooltipCaptureElement {
4933 type RequestLayoutState = ();
4934 type PrepaintState = ();
4935
4936 fn id(&self) -> Option<ElementId> {
4937 None
4938 }
4939
4940 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4941 None
4942 }
4943
4944 fn request_layout(
4945 &mut self,
4946 _id: Option<&GlobalElementId>,
4947 _inspector_id: Option<&InspectorElementId>,
4948 window: &mut Window,
4949 cx: &mut App,
4950 ) -> (LayoutId, Self::RequestLayoutState) {
4951 (self.child.request_layout(window, cx), ())
4952 }
4953
4954 fn prepaint(
4955 &mut self,
4956 _id: Option<&GlobalElementId>,
4957 _inspector_id: Option<&InspectorElementId>,
4958 _bounds: Bounds<Pixels>,
4959 _request_layout: &mut Self::RequestLayoutState,
4960 window: &mut Window,
4961 cx: &mut App,
4962 ) -> Self::PrepaintState {
4963 self.child.prepaint(window, cx);
4964 }
4965
4966 fn paint(
4967 &mut self,
4968 _id: Option<&GlobalElementId>,
4969 _inspector_id: Option<&InspectorElementId>,
4970 _bounds: Bounds<Pixels>,
4971 _request_layout: &mut Self::RequestLayoutState,
4972 _prepaint: &mut Self::PrepaintState,
4973 window: &mut Window,
4974 cx: &mut App,
4975 ) {
4976 self.child.paint(window, cx);
4977 window.with_global_id("target".into(), |global_id, window| {
4978 window.with_element_state::<InteractiveElementState, _>(
4979 global_id,
4980 |state, _window| {
4981 let state = state.unwrap();
4982 *self.captured_active_tooltip.borrow_mut() =
4983 state.active_tooltip.as_ref().map(Rc::downgrade);
4984 ((), state)
4985 },
4986 )
4987 });
4988 }
4989 }
4990
4991 struct TooltipOwner {
4992 captured_active_tooltip: CapturedActiveTooltip,
4993 show_delay_override: Option<Duration>,
4994 }
4995
4996 impl Render for TooltipOwner {
4997 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4998 TooltipCaptureElement {
4999 child: div()
5000 .size_full()
5001 .child(
5002 div()
5003 .id("target")
5004 .w(px(50.))
5005 .h(px(50.))
5006 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
5007 .when_some(self.show_delay_override, |this, delay| {
5008 this.tooltip_show_delay(delay)
5009 }),
5010 )
5011 .into_any_element(),
5012 captured_active_tooltip: self.captured_active_tooltip.clone(),
5013 }
5014 }
5015 }
5016
5017 #[test]
5018 fn scroll_handle_aligns_wide_children_to_left_edge() {
5019 let handle = ScrollHandle::new();
5020 {
5021 let mut state = handle.0.borrow_mut();
5022 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
5023 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
5024 state.overflow.x = Overflow::Scroll;
5025 state.active_item = Some(ScrollActiveItem {
5026 index: 0,
5027 strategy: ScrollStrategy::default(),
5028 });
5029 }
5030
5031 handle.scroll_to_active_item();
5032
5033 assert_eq!(handle.offset().x, px(-25.));
5034 }
5035
5036 #[test]
5037 fn scroll_handle_aligns_tall_children_to_top_edge() {
5038 let handle = ScrollHandle::new();
5039 {
5040 let mut state = handle.0.borrow_mut();
5041 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
5042 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
5043 state.overflow.y = Overflow::Scroll;
5044 state.active_item = Some(ScrollActiveItem {
5045 index: 0,
5046 strategy: ScrollStrategy::default(),
5047 });
5048 }
5049
5050 handle.scroll_to_active_item();
5051
5052 assert_eq!(handle.offset().y, px(-25.));
5053 }
5054
5055 #[test]
5056 fn long_press_shows_tooltip_until_touch_ends() {
5057 let (mut test_app, any_window, captured_active_tooltip) = create_tooltip_owner_test(None);
5058 let active_tooltip = captured_active_tooltip
5059 .borrow()
5060 .clone()
5061 .unwrap()
5062 .upgrade()
5063 .unwrap();
5064 let touch_id = TouchId(1);
5065 let touch_position = point(px(49.), px(10.));
5066
5067 test_app
5068 .update_window(any_window, |_, window, cx| {
5069 window.dispatch_event(
5070 TouchEvent {
5071 id: touch_id,
5072 phase: TouchPhase::Started,
5073 position: touch_position,
5074 predicted_position: None,
5075 force: None,
5076 }
5077 .to_platform_input(),
5078 cx,
5079 );
5080 })
5081 .unwrap();
5082 test_app
5083 .dispatcher
5084 .advance_clock(GestureTuning::default().long_press_duration + Duration::from_millis(1));
5085 test_app.run_until_parked();
5086
5087 assert!(matches!(
5088 active_tooltip.borrow().as_ref(),
5089 Some(ActiveTooltip::Visible { .. })
5090 ));
5091
5092 let moved_position = point(px(55.), px(10.));
5093 test_app
5094 .update_window(any_window, |_, window, cx| {
5095 window.dispatch_event(
5096 TouchEvent {
5097 id: touch_id,
5098 phase: TouchPhase::Moved,
5099 position: moved_position,
5100 predicted_position: None,
5101 force: None,
5102 }
5103 .to_platform_input(),
5104 cx,
5105 );
5106 window.draw(cx).clear(cx);
5107 })
5108 .unwrap();
5109 assert!(matches!(
5110 active_tooltip.borrow().as_ref(),
5111 Some(ActiveTooltip::Visible { .. })
5112 ));
5113
5114 test_app
5115 .update_window(any_window, |_, window, cx| {
5116 window.dispatch_event(
5117 TouchEvent {
5118 id: touch_id,
5119 phase: TouchPhase::Ended,
5120 position: moved_position,
5121 predicted_position: None,
5122 force: None,
5123 }
5124 .to_platform_input(),
5125 cx,
5126 );
5127 })
5128 .unwrap();
5129
5130 assert!(active_tooltip.borrow().is_none());
5131 }
5132
5133 fn setup_tooltip_owner_test(
5134 show_delay_override: Option<Duration>,
5135 ) -> (
5136 TestAppContext,
5137 crate::AnyWindowHandle,
5138 CapturedActiveTooltip,
5139 ) {
5140 let (mut test_app, any_window, captured_active_tooltip) =
5141 create_tooltip_owner_test(show_delay_override);
5142
5143 test_app
5144 .update_window(any_window, |_, window, cx| {
5145 window.dispatch_event(
5146 MouseMoveEvent {
5147 position: point(px(10.), px(10.)),
5148 modifiers: Default::default(),
5149 pressed_button: None,
5150 }
5151 .to_platform_input(),
5152 cx,
5153 );
5154 })
5155 .unwrap();
5156
5157 test_app
5158 .update_window(any_window, |_, window, cx| {
5159 window.draw(cx).clear(cx);
5160 })
5161 .unwrap();
5162
5163 (test_app, any_window, captured_active_tooltip)
5164 }
5165
5166 fn create_tooltip_owner_test(
5167 show_delay_override: Option<Duration>,
5168 ) -> (
5169 TestAppContext,
5170 crate::AnyWindowHandle,
5171 CapturedActiveTooltip,
5172 ) {
5173 let mut test_app = TestAppContext::single();
5174 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
5175 let window = test_app.add_window({
5176 let captured_active_tooltip = captured_active_tooltip.clone();
5177 move |_, _| TooltipOwner {
5178 captured_active_tooltip,
5179 show_delay_override,
5180 }
5181 });
5182 let any_window = window.into();
5183
5184 test_app
5185 .update_window(any_window, |_, window, cx| {
5186 window.draw(cx).clear(cx);
5187 })
5188 .unwrap();
5189
5190 (test_app, any_window, captured_active_tooltip)
5191 }
5192
5193 #[test]
5194 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
5195 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5196
5197 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5198 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5199 assert!(matches!(
5200 active_tooltip.borrow().as_ref(),
5201 Some(ActiveTooltip::WaitingForShow { .. })
5202 ));
5203
5204 test_app
5205 .update_window(any_window, |_, window, _| {
5206 window.remove_window();
5207 })
5208 .unwrap();
5209 test_app.run_until_parked();
5210 drop(active_tooltip);
5211
5212 assert!(weak_active_tooltip.upgrade().is_none());
5213 }
5214
5215 #[test]
5216 fn tooltip_respects_custom_show_delay() {
5217 let extra_delay = Duration::from_secs(1);
5218 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
5219 let (test_app, _any_window, captured_active_tooltip) =
5220 setup_tooltip_owner_test(Some(show_delay_override));
5221
5222 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5223 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5224
5225 test_app
5226 .dispatcher
5227 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5228 test_app.run_until_parked();
5229
5230 assert!(matches!(
5231 active_tooltip.borrow().as_ref(),
5232 Some(ActiveTooltip::WaitingForShow { .. })
5233 ));
5234
5235 test_app.dispatcher.advance_clock(extra_delay);
5236 test_app.run_until_parked();
5237
5238 assert!(matches!(
5239 active_tooltip.borrow().as_ref(),
5240 Some(ActiveTooltip::Visible { .. })
5241 ));
5242 }
5243
5244 #[test]
5245 fn tooltip_is_released_when_its_owner_disappears() {
5246 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5247
5248 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5249 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5250
5251 test_app
5252 .dispatcher
5253 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5254 test_app.run_until_parked();
5255
5256 assert!(matches!(
5257 active_tooltip.borrow().as_ref(),
5258 Some(ActiveTooltip::Visible { .. })
5259 ));
5260
5261 test_app
5262 .update_window(any_window, |_, window, _| {
5263 window.remove_window();
5264 })
5265 .unwrap();
5266 test_app.run_until_parked();
5267 drop(active_tooltip);
5268
5269 assert!(weak_active_tooltip.upgrade().is_none());
5270 }
5271
5272 #[test]
5273 fn tooltip_hides_after_mouse_leaves_origin() {
5274 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5275
5276 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5277 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5278
5279 test_app
5280 .dispatcher
5281 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5282 test_app.run_until_parked();
5283
5284 assert!(matches!(
5285 active_tooltip.borrow().as_ref(),
5286 Some(ActiveTooltip::Visible { .. })
5287 ));
5288
5289 test_app
5290 .update_window(any_window, |_, window, cx| {
5291 window.dispatch_event(
5292 MouseMoveEvent {
5293 position: point(px(75.), px(75.)),
5294 modifiers: Default::default(),
5295 pressed_button: None,
5296 }
5297 .to_platform_input(),
5298 cx,
5299 );
5300 })
5301 .unwrap();
5302
5303 assert!(active_tooltip.borrow().is_none());
5304 }
5305
5306 struct MouseDownOutOwner {
5307 mouse_down_out_count: Rc<RefCell<usize>>,
5308 }
5309
5310 impl Render for MouseDownOutOwner {
5311 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5312 let mouse_down_out_count = self.mouse_down_out_count.clone();
5313 div()
5314 .size_full()
5315 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
5316 move |_, _, _| {
5317 *mouse_down_out_count.borrow_mut() += 1;
5318 },
5319 ))
5320 }
5321 }
5322
5323 #[test]
5324 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
5325 let mut test_app = TestAppContext::single();
5326 let mouse_down_out_count = Rc::new(RefCell::new(0));
5327 let window = test_app.add_window({
5328 let mouse_down_out_count = mouse_down_out_count.clone();
5329 move |_, _| MouseDownOutOwner {
5330 mouse_down_out_count,
5331 }
5332 });
5333 let any_window: AnyWindowHandle = window.into();
5334
5335 fn dispatch_mouse_down_outside_target(
5336 test_app: &mut TestAppContext,
5337 any_window: AnyWindowHandle,
5338 ) {
5339 test_app
5340 .update_window(any_window, |_, window, cx| {
5341 window.dispatch_event(
5342 MouseDownEvent {
5343 position: point(px(75.), px(75.)),
5344 button: MouseButton::Left,
5345 modifiers: Default::default(),
5346 click_count: 1,
5347 first_mouse: false,
5348 }
5349 .to_platform_input(),
5350 cx,
5351 );
5352 })
5353 .unwrap();
5354 }
5355
5356 test_app
5357 .update_window(any_window, |_, window, cx| {
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 outside the element should fire mouse-down-out listeners"
5367 );
5368
5369 test_app
5370 .update_window(any_window, |_, window, cx| {
5371 cx.set_prompt_builder(crate::fallback_prompt_renderer);
5372 let _receiver =
5373 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
5374 assert!(window.has_active_prompt());
5375 window.draw(cx).clear(cx);
5376 })
5377 .unwrap();
5378
5379 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5380 assert_eq!(
5381 *mouse_down_out_count.borrow(),
5382 1,
5383 "mouse down over an active prompt should not fire mouse-down-out listeners"
5384 );
5385 }
5386
5387 #[test]
5388 fn touch_tap_out_fires_once_after_release() {
5389 let mut test_app = TestAppContext::single();
5390 let mouse_down_out_count = Rc::new(RefCell::new(0));
5391 let window = test_app.add_window({
5392 let mouse_down_out_count = mouse_down_out_count.clone();
5393 move |_, _| MouseDownOutOwner {
5394 mouse_down_out_count,
5395 }
5396 });
5397 let any_window: AnyWindowHandle = window.into();
5398
5399 test_app
5400 .update_window(any_window, |_, window, cx| {
5401 window.draw(cx).clear(cx);
5402 let started = TouchEvent {
5403 id: TouchId(1),
5404 phase: TouchPhase::Started,
5405 position: point(px(75.), px(75.)),
5406 force: None,
5407 predicted_position: None,
5408 };
5409 window.dispatch_event(started.clone().to_platform_input(), cx);
5410 assert_eq!(*mouse_down_out_count.borrow(), 0);
5411 window.dispatch_event(
5412 TouchEvent {
5413 phase: TouchPhase::Ended,
5414 ..started
5415 }
5416 .to_platform_input(),
5417 cx,
5418 );
5419 })
5420 .unwrap();
5421
5422 assert_eq!(
5423 *mouse_down_out_count.borrow(),
5424 1,
5425 "a touch tap outside the element should use mouse-down-out listeners"
5426 );
5427 }
5428
5429 #[crate::test]
5430 fn touch_pan_and_cancel_do_not_fire_mouse_down_out(cx: &mut TestAppContext) {
5431 let mouse_down_out_count = Rc::new(RefCell::new(0));
5432 let window = cx.add_window({
5433 let mouse_down_out_count = mouse_down_out_count.clone();
5434 move |_, _| MouseDownOutOwner {
5435 mouse_down_out_count,
5436 }
5437 });
5438 cx.update_window(window.into(), |_, window, cx| {
5439 window.draw(cx).clear(cx);
5440 for (id, samples) in [
5441 (
5442 TouchId(1),
5443 [
5444 (TouchPhase::Started, 100.),
5445 (TouchPhase::Moved, 75.),
5446 (TouchPhase::Ended, 75.),
5447 ],
5448 ),
5449 (
5450 TouchId(2),
5451 [
5452 (TouchPhase::Started, 100.),
5453 (TouchPhase::Moved, 100.),
5454 (TouchPhase::Cancelled, 100.),
5455 ],
5456 ),
5457 ] {
5458 for (phase, vertical_position) in samples {
5459 window.dispatch_event(
5460 TouchEvent {
5461 id,
5462 phase,
5463 position: point(px(75.), px(vertical_position)),
5464 predicted_position: None,
5465 force: None,
5466 }
5467 .to_platform_input(),
5468 cx,
5469 );
5470 }
5471 }
5472 })
5473 .unwrap();
5474 assert_eq!(*mouse_down_out_count.borrow(), 0);
5475 }
5476
5477 #[test]
5478 fn test_accessibility_id_builder_writes_author_id() {
5479 let mut element = div()
5480 .id("buffer-font-size")
5481 .accessibility_id("settings.buffer-font-size");
5482 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5483
5484 element.interactivity().write_a11y_info(&mut node);
5485
5486 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5487 }
5488
5489 #[test]
5490 fn test_write_a11y_info_string_and_numeric_properties() {
5491 let mut interactivity = Interactivity::default();
5492 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
5493 interactivity.aria.label = Some("Buffer Font Size".into());
5494 interactivity.aria.value = Some("15".into());
5495 interactivity.aria.placeholder = Some("Search".into());
5496 interactivity.aria.numeric_value = Some(15.0);
5497 interactivity.aria.min_numeric_value = Some(6.0);
5498 interactivity.aria.max_numeric_value = Some(72.0);
5499 interactivity.aria.numeric_value_step = Some(1.0);
5500
5501 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5502 interactivity.write_a11y_info(&mut node);
5503
5504 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5505 assert_eq!(node.label(), Some("Buffer Font Size"));
5506 assert_eq!(node.value(), Some("15"));
5507 assert_eq!(node.placeholder(), Some("Search"));
5508 assert_eq!(node.numeric_value(), Some(15.0));
5509 assert_eq!(node.min_numeric_value(), Some(6.0));
5510 assert_eq!(node.max_numeric_value(), Some(72.0));
5511 assert_eq!(node.numeric_value_step(), Some(1.0));
5512 }
5513
5514 struct KeyboardActivationTest {
5517 focus_a: FocusHandle,
5518 focus_b: FocusHandle,
5519 clicks: Rc<RefCell<Vec<&'static str>>>,
5520 }
5521
5522 impl Render for KeyboardActivationTest {
5523 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5524 let clicks_a = self.clicks.clone();
5525 let clicks_b = self.clicks.clone();
5526 div()
5527 .size_full()
5528 .child(
5529 div()
5530 .id("a")
5531 .w(px(50.))
5532 .h(px(50.))
5533 .track_focus(&self.focus_a)
5534 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
5535 )
5536 .child(
5537 div()
5538 .id("b")
5539 .w(px(50.))
5540 .h(px(50.))
5541 .track_focus(&self.focus_b)
5542 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
5543 )
5544 }
5545 }
5546
5547 fn setup_keyboard_activation_test() -> (
5548 TestAppContext,
5549 AnyWindowHandle,
5550 Rc<RefCell<Vec<&'static str>>>,
5551 FocusHandle,
5552 FocusHandle,
5553 ) {
5554 let mut cx = TestAppContext::single();
5555 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
5556 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
5557 let window = cx.add_window({
5558 let focus_a = focus_a.clone();
5559 let focus_b = focus_b.clone();
5560 let clicks = clicks.clone();
5561 move |_, _| KeyboardActivationTest {
5562 focus_a,
5563 focus_b,
5564 clicks,
5565 }
5566 });
5567 (cx, window.into(), clicks, focus_a, focus_b)
5568 }
5569
5570 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
5573 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
5574 .unwrap();
5575 cx.run_until_parked();
5576 cx.update_window(window, |_, window, cx| {
5577 window.draw(cx).clear(cx);
5578 })
5579 .unwrap();
5580 }
5581
5582 fn key_down(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(
5587 KeyDownEvent {
5588 keystroke,
5589 is_held: false,
5590 prefer_character_input: false,
5591 }
5592 .to_platform_input(),
5593 cx,
5594 );
5595 })
5596 .unwrap();
5597 }
5598
5599 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5600 let os = cx.read(|cx| cx.platform_info().os);
5601 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5602 cx.update_window(window, |_, window, cx| {
5603 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
5604 })
5605 .unwrap();
5606 }
5607
5608 #[test]
5610 fn keyboard_activation_fires_click_on_same_element() {
5611 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5612
5613 focus_and_draw(&mut cx, window, &focus_a);
5614 key_down(&mut cx, window, "enter");
5615 key_up(&mut cx, window, "enter");
5616
5617 assert_eq!(*clicks.borrow(), vec!["a"]);
5618 }
5619
5620 #[test]
5625 fn keyboard_activation_does_not_leak_across_focus_change() {
5626 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5627
5628 focus_and_draw(&mut cx, window, &focus_a);
5630 key_down(&mut cx, window, "enter");
5631
5632 focus_and_draw(&mut cx, window, &focus_b);
5634 key_up(&mut cx, window, "enter");
5635
5636 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5639 }
5640
5641 #[test]
5646 fn keyboard_activation_does_not_leak_when_focus_returns() {
5647 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5648
5649 focus_and_draw(&mut cx, window, &focus_a);
5651 key_down(&mut cx, window, "enter");
5652
5653 focus_and_draw(&mut cx, window, &focus_b);
5656 focus_and_draw(&mut cx, window, &focus_a);
5657 key_up(&mut cx, window, "enter");
5658
5659 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5661 }
5662
5663 #[test]
5668 fn keyboard_activation_cleared_by_intervening_key_release() {
5669 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5670
5671 focus_and_draw(&mut cx, window, &focus_a);
5672 key_down(&mut cx, window, "escape");
5673 key_down(&mut cx, window, "space");
5674 key_up(&mut cx, window, "escape");
5675 key_up(&mut cx, window, "space");
5676
5677 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5678 }
5679
5680 #[test]
5684 fn keyboard_activation_does_not_distinguish_space_and_enter() {
5685 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5686
5687 focus_and_draw(&mut cx, window, &focus_a);
5688 key_down(&mut cx, window, "space");
5689 key_up(&mut cx, window, "enter");
5690
5691 assert_eq!(*clicks.borrow(), vec!["a"]);
5692 }
5693
5694 #[test]
5697 fn keyboard_activation_cleared_by_intervening_keydown() {
5698 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5699
5700 focus_and_draw(&mut cx, window, &focus_a);
5701 key_down(&mut cx, window, "enter");
5702 key_down(&mut cx, window, "a");
5703 key_up(&mut cx, window, "enter");
5704
5705 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5706 }
5707
5708 #[test]
5711 fn keyboard_activation_ignores_modified_keys() {
5712 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5713
5714 focus_and_draw(&mut cx, window, &focus_a);
5715 key_down(&mut cx, window, "cmd-enter");
5716 key_up(&mut cx, window, "cmd-enter");
5717
5718 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5719 }
5720
5721 struct TabGroupFocus {
5725 group_a: FocusHandle,
5726 item_a: FocusHandle,
5727 group_b: FocusHandle,
5728 item_b: FocusHandle,
5729 }
5730
5731 impl Render for TabGroupFocus {
5732 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5733 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
5734 div()
5735 .track_focus(container)
5736 .tab_group()
5737 .child(div().track_focus(item))
5738 }
5739 div()
5740 .child(group(&self.group_a, &self.item_a))
5741 .child(group(&self.group_b, &self.item_b))
5742 }
5743 }
5744
5745 #[test]
5749 fn focus_next_from_tab_group_container_enters_that_group() {
5750 let mut cx = TestAppContext::single();
5751 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
5752 (
5753 cx.focus_handle(),
5754 cx.focus_handle().tab_stop(true),
5755 cx.focus_handle(),
5756 cx.focus_handle().tab_stop(true),
5757 )
5758 });
5759 let window: AnyWindowHandle = cx
5760 .add_window({
5761 let (group_a, item_a, group_b, item_b) =
5762 (group_a, item_a, group_b.clone(), item_b.clone());
5763 move |_, _| TabGroupFocus {
5764 group_a,
5765 item_a,
5766 group_b,
5767 item_b,
5768 }
5769 })
5770 .into();
5771 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5772 .unwrap();
5773
5774 let focused = cx
5776 .update_window(window, |_, window, cx| {
5777 window.focus(&group_b, cx);
5778 window.focus_next(cx);
5779 window.focused(cx).map(|handle| handle.id)
5780 })
5781 .unwrap();
5782
5783 assert_eq!(focused, Some(item_b.id));
5784 }
5785
5786 #[gpui::test]
5787 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5788 cx: &mut TestAppContext,
5789 ) {
5790 struct PaddedContainer {
5791 scroll_handle: ScrollHandle,
5792 }
5793
5794 impl Render for PaddedContainer {
5795 fn render(
5796 &mut self,
5797 _window: &mut Window,
5798 _cx: &mut Context<Self>,
5799 ) -> impl IntoElement {
5800 div().size_full().child(
5803 div()
5804 .id("container")
5805 .h(px(50.))
5806 .w(px(100.))
5807 .py(px(4.25))
5808 .overflow_y_scroll()
5809 .track_scroll(&self.scroll_handle)
5810 .child(div().w_full().h(px(42.))),
5811 )
5812 }
5813 }
5814
5815 let scroll_handle = ScrollHandle::new();
5816 let window: AnyWindowHandle = cx
5817 .add_window({
5818 let scroll_handle = scroll_handle.clone();
5819 move |_, _| PaddedContainer { scroll_handle }
5820 })
5821 .into();
5822 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5823 .unwrap();
5824
5825 assert_eq!(scroll_handle.max_offset().y, px(0.));
5826 }
5827
5828 struct ContentSizedGrid;
5829
5830 impl Render for ContentSizedGrid {
5831 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5832 let widths = [px(100.), px(200.), px(50.)];
5833 div().size_full().child(
5834 div()
5835 .w_full()
5836 .grid()
5837 .grid_cols_max_content(widths.len() as u16)
5838 .children(widths.into_iter().enumerate().map(|(index, width)| {
5839 div()
5840 .debug_selector(move || format!("cell-{index}"))
5841 .w(width)
5842 .h(px(10.))
5843 })),
5844 )
5845 }
5846 }
5847
5848 #[gpui::test]
5849 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
5850 let window = cx.add_window(|_, _| ContentSizedGrid);
5851 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
5852 .unwrap();
5853
5854 let mut bounds = |selector: &'static str| {
5855 cx.update_window(window.into(), |_, window, _| {
5856 window.rendered_frame.debug_bounds.get(selector).copied()
5857 })
5858 .unwrap()
5859 .unwrap_or_else(|| panic!("{selector} was not rendered"))
5860 };
5861
5862 assert_eq!(bounds("cell-0").origin.x, px(0.));
5863 assert_eq!(bounds("cell-1").origin.x, px(100.));
5864 assert_eq!(bounds("cell-2").origin.x, px(300.));
5865 }
5866}