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, IsZero, KeyContext, KeyDownEvent, KeyUpEvent,
24 KeyboardButton, KeyboardClickEvent, LayoutId, LongPressEvent, ModifiersChangedEvent,
25 MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent, MouseMoveEvent,
26 MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels,
27 Point, Render, ScrollEvent, SharedString, Size, Style, StyleRefinement, Styled, Task,
28 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 #[allow(unused_mut)]
1848 let mut interactivity = InteractivityBox::new();
1849 #[cfg(any(feature = "inspector", debug_assertions))]
1850 {
1851 interactivity.source_location = Some(core::panic::Location::caller());
1852 }
1853 Div {
1854 interactivity,
1855 children: SmallVec::default(),
1856 prepaint_listener: None,
1857 image_cache: None,
1858 prepaint_order_fn: None,
1859 }
1860}
1861
1862enum InteractivityBox {
1866 Arena(crate::ArenaBox<Interactivity>),
1867 Heap(Box<Interactivity>),
1868}
1869
1870impl InteractivityBox {
1871 #[inline]
1873 fn new() -> Self {
1874 if crate::window::draw_in_progress() {
1875 Self::Arena(crate::window::with_element_arena(|arena| {
1876 arena.alloc(Interactivity::default)
1877 }))
1878 } else {
1879 Self::Heap(Box::default())
1880 }
1881 }
1882}
1883
1884impl std::ops::Deref for InteractivityBox {
1885 type Target = Interactivity;
1886
1887 #[inline]
1888 fn deref(&self) -> &Interactivity {
1889 match self {
1890 Self::Arena(interactivity) => interactivity,
1891 Self::Heap(interactivity) => interactivity,
1892 }
1893 }
1894}
1895
1896impl std::ops::DerefMut for InteractivityBox {
1897 #[inline]
1898 fn deref_mut(&mut self) -> &mut Interactivity {
1899 match self {
1900 Self::Arena(interactivity) => interactivity,
1901 Self::Heap(interactivity) => interactivity,
1902 }
1903 }
1904}
1905
1906pub struct Div {
1908 interactivity: InteractivityBox,
1911 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1912 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1913 image_cache: Option<Box<dyn ImageCacheProvider>>,
1914 prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1915}
1916
1917impl Div {
1918 pub fn on_children_prepainted(
1921 mut self,
1922 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1923 ) -> Self {
1924 self.prepaint_listener = Some(Box::new(listener));
1925 self
1926 }
1927
1928 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1930 self.image_cache = Some(Box::new(cache));
1931 self
1932 }
1933
1934 pub fn with_dynamic_prepaint_order(
1943 mut self,
1944 order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1945 ) -> Self {
1946 self.prepaint_order_fn = Some(Box::new(order_fn));
1947 self
1948 }
1949}
1950
1951pub struct DivFrameState {
1958 child_layout_ids: SmallVec<[LayoutId; 2]>,
1959}
1960
1961#[derive(Clone)]
1963pub struct DivInspectorState {
1964 #[cfg(any(feature = "inspector", debug_assertions))]
1968 pub base_style: Box<StyleRefinement>,
1969 pub bounds: Bounds<Pixels>,
1971 pub content_size: Size<Pixels>,
1973}
1974
1975impl Styled for Div {
1976 fn style(&mut self) -> &mut StyleRefinement {
1977 &mut self.interactivity.base_style
1978 }
1979}
1980
1981impl InteractiveElement for Div {
1982 fn interactivity(&mut self) -> &mut Interactivity {
1983 &mut self.interactivity
1984 }
1985}
1986
1987impl ParentElement for Div {
1988 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1989 #[cfg(feature = "stacker")]
1990 self.children
1991 .extend(elements.into_iter().map(StackSafe::new));
1992 #[cfg(not(feature = "stacker"))]
1993 self.children.extend(elements);
1994 }
1995}
1996
1997impl Element for Div {
1998 type RequestLayoutState = DivFrameState;
1999 type PrepaintState = Option<Hitbox>;
2000
2001 fn id(&self) -> Option<ElementId> {
2002 self.interactivity.element_id.clone()
2003 }
2004
2005 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
2006 self.interactivity.source_location()
2007 }
2008
2009 fn a11y_role(&self) -> Option<accesskit::Role> {
2010 self.interactivity
2013 .override_role
2014 .filter(|role| *role != accesskit::Role::GenericContainer)
2015 }
2016
2017 fn write_a11y_info(&self, node: &mut accesskit::Node) {
2018 self.interactivity.write_a11y_info(node);
2019 }
2020
2021 fn a11y_synthetic_children(
2022 &mut self,
2023 _prepaint: &mut Self::PrepaintState,
2024 builder: &mut crate::A11ySubtreeBuilder,
2025 ) {
2026 if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
2027 f(builder);
2028 }
2029 }
2030
2031 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2032 fn request_layout(
2033 &mut self,
2034 global_id: Option<&GlobalElementId>,
2035 inspector_id: Option<&InspectorElementId>,
2036 window: &mut Window,
2037 cx: &mut App,
2038 ) -> (LayoutId, Self::RequestLayoutState) {
2039 let mut child_layout_ids = SmallVec::new();
2040 let image_cache = self
2041 .image_cache
2042 .as_mut()
2043 .map(|provider| provider.provide(window, cx));
2044
2045 let layout_id = window.with_image_cache(image_cache, |window| {
2046 self.interactivity.request_layout(
2047 global_id,
2048 inspector_id,
2049 window,
2050 cx,
2051 |style, window, cx| {
2052 window.with_text_style(style.text_style().cloned(), |window| {
2053 child_layout_ids = self
2054 .children
2055 .iter_mut()
2056 .map(|child| child.request_layout(window, cx))
2057 .collect::<SmallVec<_>>();
2058 crate::fast::layout::request_layout(window, &style, &child_layout_ids)
2059 })
2060 },
2061 )
2062 });
2063
2064 (layout_id, DivFrameState { child_layout_ids })
2065 }
2066
2067 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2068 fn prepaint(
2069 &mut self,
2070 global_id: Option<&GlobalElementId>,
2071 inspector_id: Option<&InspectorElementId>,
2072 bounds: Bounds<Pixels>,
2073 request_layout: &mut Self::RequestLayoutState,
2074 window: &mut Window,
2075 cx: &mut App,
2076 ) -> Option<Hitbox> {
2077 let image_cache = self
2078 .image_cache
2079 .as_mut()
2080 .map(|provider| provider.provide(window, cx));
2081
2082 let has_prepaint_listener = self.prepaint_listener.is_some();
2083 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
2084 request_layout.child_layout_ids.len()
2085 } else {
2086 0
2087 });
2088
2089 let mut child_min = point(Pixels::MAX, Pixels::MAX);
2090 let mut child_max = Point::default();
2091 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
2092 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
2093 }
2094 let content_size = if request_layout.child_layout_ids.is_empty() {
2095 bounds.size
2096 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2097 crate::fast::layers::input::track_handle(window, &scroll_handle.0);
2098 let mut state = scroll_handle.0.borrow_mut();
2099 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
2100 for child_layout_id in &request_layout.child_layout_ids {
2101 let child_bounds = window.layout_bounds(*child_layout_id);
2102 child_min = child_min.min(&child_bounds.origin);
2103 child_max = child_max.max(&child_bounds.bottom_right());
2104 state.child_bounds.push(child_bounds);
2105 }
2106 (child_max - child_min).into()
2107 } else {
2108 for child_layout_id in &request_layout.child_layout_ids {
2109 let child_bounds = window.layout_bounds(*child_layout_id);
2110 child_min = child_min.min(&child_bounds.origin);
2111 child_max = child_max.max(&child_bounds.bottom_right());
2112
2113 if has_prepaint_listener {
2114 children_bounds.push(child_bounds);
2115 }
2116 }
2117 (child_max - child_min).into()
2118 };
2119
2120 if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2121 scroll_handle.scroll_to_active_item();
2122 }
2123
2124 self.interactivity.prepaint(
2125 global_id,
2126 inspector_id,
2127 bounds,
2128 content_size,
2129 window,
2130 cx,
2131 |style, scroll_offset, hitbox, window, cx| {
2132 if style.display == Display::None {
2134 return hitbox;
2135 }
2136
2137 window.with_image_cache(image_cache, |window| {
2138 let fast_layer = crate::fast::layers::paint::begin_children(
2139 window,
2140 cx,
2141 global_id,
2142 bounds,
2143 child_min,
2144 content_size,
2145 scroll_offset,
2146 style,
2147 );
2148 crate::fast::layers::paint::prepaint_children(window, fast_layer, |window| {
2149 if let Some(order_fn) = &self.prepaint_order_fn {
2150 let order = order_fn(window, cx);
2151 for idx in order {
2152 if let Some(child) = self.children.get_mut(idx) {
2153 child.prepaint(window, cx);
2154 }
2155 }
2156 } else {
2157 for child in &mut self.children {
2158 child.prepaint(window, cx);
2159 }
2160 }
2161 });
2162 crate::fast::layers::paint::end_children(window, cx, fast_layer);
2163
2164 if let Some(listener) = self.prepaint_listener.as_ref() {
2165 crate::fast::layers::invalidate::note_uncarried(window);
2166 listener(children_bounds, window, cx);
2167 }
2168 });
2169
2170 hitbox
2171 },
2172 )
2173 }
2174
2175 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2176 fn paint(
2177 &mut self,
2178 global_id: Option<&GlobalElementId>,
2179 inspector_id: Option<&InspectorElementId>,
2180 bounds: Bounds<Pixels>,
2181 _request_layout: &mut Self::RequestLayoutState,
2182 hitbox: &mut Option<Hitbox>,
2183 window: &mut Window,
2184 cx: &mut App,
2185 ) {
2186 let image_cache = self
2187 .image_cache
2188 .as_mut()
2189 .map(|provider| provider.provide(window, cx));
2190
2191 window.with_image_cache(image_cache, |window| {
2192 self.interactivity.paint(
2193 global_id,
2194 inspector_id,
2195 bounds,
2196 hitbox.as_ref(),
2197 window,
2198 cx,
2199 |style, window, cx| {
2200 if style.display == Display::None {
2202 return;
2203 }
2204
2205 crate::fast::layers::paint::paint_children(
2206 window,
2207 cx,
2208 global_id,
2209 |window, cx| {
2210 for child in &mut self.children {
2211 child.paint(window, cx);
2212 }
2213 },
2214 );
2215 },
2216 )
2217 });
2218 }
2219}
2220
2221#[derive(Default)]
2222pub(crate) struct AriaProperties {
2223 pub(crate) author_id: Option<SharedString>,
2224 pub(crate) label: Option<SharedString>,
2225 pub(crate) description: Option<SharedString>,
2226 pub(crate) keyshortcuts: Option<SharedString>,
2227 pub(crate) selected: Option<bool>,
2228 pub(crate) expanded: Option<bool>,
2229 pub(crate) toggled: Option<accesskit::Toggled>,
2230 pub(crate) numeric_value: Option<f64>,
2231 pub(crate) min_numeric_value: Option<f64>,
2232 pub(crate) max_numeric_value: Option<f64>,
2233 pub(crate) numeric_value_step: Option<f64>,
2234 pub(crate) value: Option<SharedString>,
2235 pub(crate) placeholder: Option<SharedString>,
2236 pub(crate) orientation: Option<accesskit::Orientation>,
2237 pub(crate) level: Option<usize>,
2238 pub(crate) position_in_set: Option<usize>,
2239 pub(crate) size_of_set: Option<usize>,
2240 pub(crate) row_index: Option<usize>,
2241 pub(crate) column_index: Option<usize>,
2242 pub(crate) row_count: Option<usize>,
2243 pub(crate) column_count: Option<usize>,
2244}
2245
2246#[derive(Default)]
2249pub struct Interactivity {
2250 pub element_id: Option<ElementId>,
2252 pub active: Option<bool>,
2254 pub hovered: Option<bool>,
2257 pub(crate) tooltip_id: Option<TooltipId>,
2258 pub(crate) content_size: Size<Pixels>,
2259 pub(crate) key_context: Option<KeyContext>,
2260 pub(crate) focusable: bool,
2261 pub(crate) tracked_focus_handle: Option<FocusHandle>,
2262 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2263 pub(crate) scroll_anchor: crate::fast::interactivity::Rare<ScrollAnchor>,
2264 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2265 pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2266 pub(crate) group: Option<SharedString>,
2267 pub base_style: Box<StyleRefinement>,
2270 pub(crate) focus_style: Option<Box<StyleRefinement>>,
2271 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2272 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2273 pub(crate) hover_style: Option<Box<StyleRefinement>>,
2274 pub(crate) group_hover_style: crate::fast::interactivity::Rare<GroupStyle>,
2275 pub(crate) active_style: Option<Box<StyleRefinement>>,
2276 pub(crate) group_active_style: crate::fast::interactivity::Rare<GroupStyle>,
2277 pub(crate) drag_over_styles: crate::fast::interactivity::LazyVec<(
2278 TypeId,
2279 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2280 )>,
2281 pub(crate) group_drag_over_styles: crate::fast::interactivity::LazyVec<(TypeId, GroupStyle)>,
2282 pub(crate) mouse_down_listeners: crate::fast::interactivity::LazyVec<MouseDownListener>,
2283 pub(crate) mouse_up_listeners: crate::fast::interactivity::LazyVec<MouseUpListener>,
2284 pub(crate) mouse_pressure_listeners: crate::fast::interactivity::LazyVec<MousePressureListener>,
2285 pub(crate) mouse_move_listeners: crate::fast::interactivity::LazyVec<MouseMoveListener>,
2286 pub(crate) mouse_exit_listeners: crate::fast::interactivity::LazyVec<MouseExitListener>,
2287 pub(crate) file_drop_exit_listeners: crate::fast::interactivity::LazyVec<FileDropExitListener>,
2288 pub(crate) scroll_listeners: crate::fast::interactivity::LazyVec<ScrollListener>,
2289 pub(crate) pinch_listeners: crate::fast::interactivity::LazyVec<PinchListener>,
2290 pub(crate) back_gesture_listeners: crate::fast::interactivity::LazyVec<BackGestureListener>,
2291 pub(crate) key_down_listeners: crate::fast::interactivity::LazyVec<KeyDownListener>,
2292 pub(crate) key_up_listeners: crate::fast::interactivity::LazyVec<KeyUpListener>,
2293 pub(crate) modifiers_changed_listeners:
2294 crate::fast::interactivity::LazyVec<ModifiersChangedListener>,
2295 pub(crate) action_listeners: crate::fast::interactivity::LazyVec<(TypeId, ActionListener)>,
2296 pub(crate) drop_listeners: crate::fast::interactivity::LazyVec<(TypeId, DropListener)>,
2297 pub(crate) can_drop_predicate: crate::fast::interactivity::Rare<CanDropPredicate>,
2298 pub(crate) click_listeners: crate::fast::interactivity::LazyVec<ClickListener>,
2299 pub(crate) aux_click_listeners: crate::fast::interactivity::LazyVec<ClickListener>,
2300 pub(crate) drag_listener: crate::fast::interactivity::Rare<DragListener>,
2301 pub(crate) hover_listener:
2302 crate::fast::interactivity::Rare<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2303 pub(crate) hover_listener_mode: HoverListenerMode,
2304 pub(crate) tooltip_builder: crate::fast::interactivity::Rare<TooltipBuilder>,
2305 pub(crate) tooltip_show_delay: Option<Duration>,
2306 pub(crate) window_control: Option<WindowControlArea>,
2307 pub(crate) hitbox_behavior: HitboxBehavior,
2308 pub(crate) tab_index: Option<isize>,
2309 pub(crate) tab_group: bool,
2310 pub(crate) tab_stop: bool,
2311
2312 pub(crate) a11y_action_listeners: crate::fast::interactivity::LazyVec<(
2313 accesskit::Action,
2314 crate::window::a11y::A11yActionListener,
2315 )>,
2316 pub(crate) a11y_synthetic_children:
2317 crate::fast::interactivity::Rare<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2318 pub(crate) report_active_descendant_focus: bool,
2319 pub(crate) override_role: Option<accesskit::Role>,
2320 pub(crate) aria: crate::fast::interactivity::Aria,
2321
2322 #[cfg(any(feature = "inspector", debug_assertions))]
2323 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2324
2325 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2326 pub(crate) debug_selector: Option<String>,
2327}
2328
2329impl Interactivity {
2330 pub fn request_layout(
2332 &mut self,
2333 global_id: Option<&GlobalElementId>,
2334 _inspector_id: Option<&InspectorElementId>,
2335 window: &mut Window,
2336 cx: &mut App,
2337 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2338 ) -> LayoutId {
2339 #[cfg(any(feature = "inspector", debug_assertions))]
2340 window.with_inspector_state(
2341 _inspector_id,
2342 cx,
2343 |inspector_state: &mut Option<DivInspectorState>, _window| {
2344 if let Some(inspector_state) = inspector_state {
2345 self.base_style = inspector_state.base_style.clone();
2346 } else {
2347 *inspector_state = Some(DivInspectorState {
2348 base_style: self.base_style.clone(),
2349 bounds: Default::default(),
2350 content_size: Default::default(),
2351 })
2352 }
2353 },
2354 );
2355
2356 window.with_optional_element_state::<InteractiveElementState, _>(
2357 global_id,
2358 |element_state, window| {
2359 let mut element_state =
2360 element_state.map(|element_state| element_state.unwrap_or_default());
2361
2362 if let Some(element_state) = element_state.as_ref()
2363 && cx.has_active_drag()
2364 {
2365 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2366 *pending_mouse_down.borrow_mut() = None;
2367 }
2368 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2369 *clicked_state.borrow_mut() = ElementClickedState::default();
2370 }
2371 }
2372
2373 if self.focusable
2378 && self.tracked_focus_handle.is_none()
2379 && let Some(element_state) = element_state.as_mut()
2380 {
2381 let mut handle = element_state
2382 .focus_handle
2383 .get_or_insert_with(|| cx.focus_handle())
2384 .clone()
2385 .tab_stop(self.tab_stop);
2386
2387 if let Some(index) = self.tab_index {
2388 handle = handle.tab_index(index);
2389 }
2390
2391 self.tracked_focus_handle = Some(handle);
2392 }
2393
2394 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2395 let scroll_handle_state = scroll_handle.0.borrow();
2396 crate::fast::dependencies::note_state_read(cx, &scroll_handle_state.version);
2397 self.scroll_offset = Some(scroll_handle_state.offset.clone());
2398 self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2399 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2400 || self.base_style.overflow.y == Some(Overflow::Scroll))
2401 && let Some(element_state) = element_state.as_mut()
2402 {
2403 self.scroll_offset = Some(
2404 element_state
2405 .scroll_offset
2406 .get_or_insert_with(Rc::default)
2407 .clone(),
2408 );
2409 self.ongoing_scroll = Some(
2410 element_state
2411 .ongoing_scroll
2412 .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2413 .clone(),
2414 );
2415 }
2416
2417 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2418 let layout_id = f(style, window, cx);
2419 (layout_id, element_state)
2420 },
2421 )
2422 }
2423
2424 pub fn prepaint<R>(
2426 &mut self,
2427 global_id: Option<&GlobalElementId>,
2428 _inspector_id: Option<&InspectorElementId>,
2429 bounds: Bounds<Pixels>,
2430 content_size: Size<Pixels>,
2431 window: &mut Window,
2432 cx: &mut App,
2433 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2434 ) -> R {
2435 self.content_size = content_size;
2436
2437 #[cfg(any(feature = "inspector", debug_assertions))]
2438 window.with_inspector_state(
2439 _inspector_id,
2440 cx,
2441 |inspector_state: &mut Option<DivInspectorState>, _window| {
2442 if let Some(inspector_state) = inspector_state {
2443 inspector_state.bounds = bounds;
2444 inspector_state.content_size = content_size;
2445 }
2446 },
2447 );
2448
2449 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2450 window.set_focus_handle(focus_handle, cx);
2451
2452 if window.a11y.is_active() {
2453 if let Some(global_id) = global_id {
2454 let node_id = global_id.accesskit_node_id();
2455 window.a11y.set_focusable(node_id, focus_handle.id);
2456 if focus_handle.is_focused(window) {
2457 window.a11y.set_focus(node_id);
2458 }
2459 } else if focus_handle.is_focused(window) {
2460 window
2464 .a11y
2465 .note_focus_without_node(focus_handle.id, "it has no element id");
2466 }
2467 }
2468 }
2469
2470 if self.report_active_descendant_focus && window.a11y.is_active() {
2471 if let Some(global_id) = global_id {
2472 window
2473 .a11y
2474 .set_active_descendant(global_id.accesskit_node_id());
2475 }
2476 }
2477 window.with_optional_element_state::<InteractiveElementState, _>(
2478 global_id,
2479 |element_state, window| {
2480 let mut element_state =
2481 element_state.map(|element_state| element_state.unwrap_or_default());
2482 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2483
2484 if let Some(element_state) = element_state.as_mut() {
2485 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2486 let clicked_state = clicked_state.borrow();
2487 self.active = Some(clicked_state.element);
2488 }
2489 if self.hover_style.is_some() || self.group_hover_style.is_some() {
2490 element_state
2491 .hover_state
2492 .get_or_insert_with(Default::default);
2493 }
2494 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2495 if self.tooltip_builder.is_some() {
2496 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2497 } else {
2498 if let Some(long_press_tooltip_active) =
2500 element_state.long_press_tooltip_active.as_ref()
2501 {
2502 long_press_tooltip_active.set(false);
2503 }
2504 element_state.active_tooltip.take();
2505 }
2506 }
2507 }
2508
2509 window.with_text_style(style.text_style().cloned(), |window| {
2510 window.with_content_mask(
2511 style.overflow_mask(bounds, window.rem_size()),
2512 |window| {
2513 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2514 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2515 } else {
2516 None
2517 };
2518
2519 let scroll_offset =
2520 self.clamp_scroll_position(bounds, &style, window, cx);
2521 let result = window.with_element_opacity(style.opacity, |window| {
2522 f(&style, scroll_offset, hitbox, window, cx)
2523 });
2524 (result, element_state)
2525 },
2526 )
2527 })
2528 },
2529 )
2530 }
2531
2532 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2533 self.hitbox_behavior != HitboxBehavior::Normal
2534 || self.window_control.is_some()
2535 || style.mouse_cursor.is_some()
2536 || self.group.is_some()
2537 || self.scroll_offset.is_some()
2538 || self.tracked_focus_handle.is_some()
2539 || self.hover_style.is_some()
2540 || self.group_hover_style.is_some()
2541 || self.hover_listener.is_some()
2542 || !self.mouse_up_listeners.is_empty()
2543 || !self.mouse_pressure_listeners.is_empty()
2544 || !self.mouse_down_listeners.is_empty()
2545 || !self.mouse_move_listeners.is_empty()
2546 || !self.mouse_exit_listeners.is_empty()
2547 || !self.file_drop_exit_listeners.is_empty()
2548 || !self.click_listeners.is_empty()
2549 || !self.aux_click_listeners.is_empty()
2550 || !self.scroll_listeners.is_empty()
2551 || self.has_pinch_listeners()
2552 || !self.back_gesture_listeners.is_empty()
2553 || self.drag_listener.is_some()
2554 || !self.drop_listeners.is_empty()
2555 || !self.drag_over_styles.is_empty()
2556 || self.tooltip_builder.is_some()
2557 || window.is_inspector_picking(cx)
2558 }
2559
2560 fn clamp_scroll_position(
2561 &self,
2562 bounds: Bounds<Pixels>,
2563 style: &Style,
2564 window: &mut Window,
2565 _cx: &mut App,
2566 ) -> Point<Pixels> {
2567 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2568 const ROUNDING_FACTOR: f32 = 100.0;
2569 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2570 }
2571
2572 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2573 let mut scroll_to_bottom = false;
2574 let mut tracked_scroll_handle = self
2575 .tracked_scroll_handle
2576 .as_ref()
2577 .map(|handle| handle.0.borrow_mut());
2578 if let Some(scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2579 scroll_handle_state.overflow = style.overflow;
2580 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2581 }
2582
2583 let rem_size = window.rem_size();
2584 let padding = style
2589 .padding
2590 .to_pixels(bounds.size.into(), rem_size)
2591 .map(|edge| window.pixel_snap(*edge));
2592 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2593 let padded_content_size = self.content_size + padding_size;
2600 let scroll_max = Point::from(padded_content_size - bounds.size)
2601 .map(round_to_two_decimals)
2602 .max(&Default::default());
2603 let mut scroll_offset = scroll_offset.borrow_mut();
2606
2607 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2608 if scroll_to_bottom {
2609 scroll_offset.y = -scroll_max.y;
2610 } else {
2611 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2612 }
2613
2614 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2615 scroll_handle_state.max_offset = scroll_max;
2616 scroll_handle_state.bounds = bounds;
2617 }
2618
2619 *scroll_offset
2620 } else {
2621 Point::default()
2622 }
2623 }
2624
2625 pub fn paint(
2634 &mut self,
2635 global_id: Option<&GlobalElementId>,
2636 _inspector_id: Option<&InspectorElementId>,
2637 bounds: Bounds<Pixels>,
2638 hitbox: Option<&Hitbox>,
2639 window: &mut Window,
2640 cx: &mut App,
2641 f: impl FnOnce(&Style, &mut Window, &mut App),
2642 ) {
2643 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2644 window.with_optional_element_state::<InteractiveElementState, _>(
2645 global_id,
2646 |element_state, window| {
2647 let mut element_state =
2648 element_state.map(|element_state| element_state.unwrap_or_default());
2649
2650 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2651
2652 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2653 if let Some(debug_selector) = &self.debug_selector {
2654 window
2655 .next_frame
2656 .record_debug_bounds(debug_selector.clone(), bounds);
2657 }
2658
2659 self.paint_hover_group_handler(window, cx);
2660
2661 if style.visibility == Visibility::Hidden {
2662 return ((), element_state);
2663 }
2664
2665 let mut tab_group = None;
2666 if self.tab_group {
2667 tab_group = self.tab_index;
2668 }
2669
2670 window.with_element_opacity(style.opacity, |window| {
2671 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2672 window.with_text_style(style.text_style().cloned(), |window| {
2673 window.with_content_mask(
2674 style.overflow_mask(bounds, window.rem_size()),
2675 |window| {
2676 window.with_tab_group(tab_group, |window| {
2677 if let Some(focus_handle) = &self.tracked_focus_handle {
2686 window.next_frame.tab_stops.insert(focus_handle);
2687 }
2688 if let Some(hitbox) = hitbox {
2689 #[cfg(debug_assertions)]
2690 self.paint_debug_info(
2691 global_id, hitbox, &style, window, cx,
2692 );
2693
2694 if let Some(drag) = cx.active_drag.as_ref() {
2695 if let Some(mouse_cursor) = drag.cursor_style {
2696 window.set_window_cursor_style(mouse_cursor);
2697 }
2698 } else {
2699 if let Some(mouse_cursor) = style.mouse_cursor {
2700 window.set_cursor_style(mouse_cursor, hitbox);
2701 }
2702 }
2703
2704 if let Some(group) = self.group.clone() {
2705 GroupHitboxes::push(group, hitbox.id, cx);
2706 }
2707
2708 if let Some(area) = self.window_control {
2709 window.insert_window_control_hitbox(
2710 area,
2711 hitbox.clone(),
2712 );
2713 }
2714
2715 self.paint_mouse_listeners(
2716 hitbox,
2717 element_state.as_mut(),
2718 window,
2719 cx,
2720 );
2721 self.paint_scroll_listener(hitbox, &style, window, cx);
2722 }
2723
2724 self.paint_keyboard_listeners(window, cx);
2725
2726 if window.a11y.is_active() {
2727 if let Some(global_id) = global_id {
2728 if !self.a11y_action_listeners.is_empty() {
2729 let node_id = global_id.accesskit_node_id();
2730 for (action, listener) in
2731 self.a11y_action_listeners.drain(..)
2732 {
2733 window.on_a11y_action(
2734 node_id, action, listener,
2735 );
2736 }
2737 }
2738 }
2739 }
2740
2741 f(&style, window, cx);
2742
2743 if let Some(_hitbox) = hitbox {
2744 #[cfg(any(feature = "inspector", debug_assertions))]
2745 window.insert_inspector_hitbox(
2746 _hitbox.id,
2747 _inspector_id,
2748 cx,
2749 );
2750
2751 if let Some(group) = self.group.as_ref() {
2752 GroupHitboxes::pop(group, cx);
2753 }
2754 }
2755 })
2756 },
2757 );
2758 });
2759 });
2760 });
2761
2762 ((), element_state)
2763 },
2764 );
2765 }
2766
2767 #[cfg(debug_assertions)]
2768 fn paint_debug_info(
2769 &self,
2770 global_id: Option<&GlobalElementId>,
2771 hitbox: &Hitbox,
2772 style: &Style,
2773 window: &mut Window,
2774 cx: &mut App,
2775 ) {
2776 use crate::{BorderStyle, TextAlign};
2777
2778 if let Some(global_id) = global_id
2779 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2780 && hitbox.is_hovered(window)
2781 {
2782 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2783 let element_id = format!("{global_id:?}");
2784 let str_len = element_id.len();
2785
2786 let render_debug_text = |window: &mut Window| {
2787 if let Some(text) = window
2788 .text_system()
2789 .shape_text(
2790 element_id.into(),
2791 FONT_SIZE,
2792 &[window.text_style().to_run(str_len)],
2793 None,
2794 None,
2795 )
2796 .ok()
2797 .and_then(|mut text| text.pop())
2798 {
2799 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2800 .ok();
2801
2802 let text_bounds = crate::Bounds {
2803 origin: hitbox.origin,
2804 size: text.size(FONT_SIZE),
2805 };
2806 if let Some(source_location) = self.source_location
2807 && text_bounds.contains(&window.mouse_position())
2808 && window.modifiers().secondary(cx)
2809 {
2810 let secondary_held = window.modifiers().secondary(cx);
2811 window.on_key_event({
2812 move |e: &crate::ModifiersChangedEvent, _phase, window, cx| {
2813 if e.modifiers.secondary(cx) != secondary_held
2814 && text_bounds.contains(&window.mouse_position())
2815 {
2816 window.refresh();
2817 }
2818 }
2819 });
2820
2821 let was_hovered = hitbox.is_hovered(window);
2822 let current_view = window.current_view();
2823 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
2824 window.on_mouse_event({
2825 let hitbox = hitbox.clone();
2826 move |_: &MouseMoveEvent, phase, window, cx| {
2827 if phase == DispatchPhase::Capture {
2828 let hovered = hitbox.is_hovered(window);
2829 if hovered != was_hovered {
2830 crate::fast::retained::invalidate_retained_subtrees(
2831 window, &subtrees,
2832 );
2833 cx.notify(current_view)
2834 }
2835 }
2836 }
2837 });
2838
2839 window.on_mouse_event({
2840 let hitbox = hitbox.clone();
2841 move |e: &crate::MouseDownEvent, phase, window, cx| {
2842 if text_bounds.contains(&e.position)
2843 && phase.capture()
2844 && hitbox.is_hovered(window)
2845 {
2846 cx.stop_propagation();
2847 let Ok(dir) = std::env::current_dir() else {
2848 return;
2849 };
2850
2851 eprintln!(
2852 "This element was created at:\n{}:{}:{}",
2853 dir.join(source_location.file()).to_string_lossy(),
2854 source_location.line(),
2855 source_location.column()
2856 );
2857 }
2858 }
2859 });
2860 window.paint_quad(crate::outline(
2861 crate::Bounds {
2862 origin: hitbox.origin
2863 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2864 size: crate::Size {
2865 width: text_bounds.size.width,
2866 height: crate::px(1.),
2867 },
2868 },
2869 crate::red(),
2870 BorderStyle::default(),
2871 ))
2872 }
2873 }
2874 };
2875
2876 window.with_text_style(
2877 Some(crate::TextStyleRefinement {
2878 color: Some(crate::red()),
2879 line_height: Some(FONT_SIZE.into()),
2880 background_color: Some(crate::white()),
2881 ..Default::default()
2882 }),
2883 render_debug_text,
2884 )
2885 }
2886 }
2887
2888 fn paint_mouse_listeners(
2889 &mut self,
2890 hitbox: &Hitbox,
2891 element_state: Option<&mut InteractiveElementState>,
2892 window: &mut Window,
2893 cx: &mut App,
2894 ) {
2895 let is_focused = self
2896 .tracked_focus_handle
2897 .as_ref()
2898 .map(|handle| handle.is_focused(window))
2899 .unwrap_or(false);
2900
2901 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2905 let hitbox = hitbox.clone();
2906 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2907 if phase == DispatchPhase::Bubble
2908 && hitbox.is_hovered(window)
2909 && !window.default_prevented()
2910 {
2911 window.focus(&focus_handle, cx);
2912 window.prevent_default();
2915 }
2916 });
2917 }
2918
2919 for listener in self.mouse_down_listeners.drain(..) {
2920 let hitbox = hitbox.clone();
2921 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2922 listener(event, phase, &hitbox, window, cx);
2923 })
2924 }
2925
2926 for listener in self.mouse_up_listeners.drain(..) {
2927 let hitbox = hitbox.clone();
2928 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2929 listener(event, phase, &hitbox, window, cx);
2930 })
2931 }
2932
2933 for listener in self.mouse_pressure_listeners.drain(..) {
2934 let hitbox = hitbox.clone();
2935 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2936 listener(event, phase, &hitbox, window, cx);
2937 })
2938 }
2939
2940 for listener in self.mouse_move_listeners.drain(..) {
2941 let hitbox = hitbox.clone();
2942 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2943 listener(event, phase, &hitbox, window, cx);
2944 })
2945 }
2946
2947 for listener in self.mouse_exit_listeners.drain(..) {
2948 let hitbox = hitbox.clone();
2949 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2950 listener(event, phase, &hitbox, window, cx);
2951 })
2952 }
2953
2954 for listener in self.file_drop_exit_listeners.drain(..) {
2955 let hitbox = hitbox.clone();
2956 window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
2957 listener(event, phase, &hitbox, window, cx);
2958 })
2959 }
2960
2961 for listener in self.scroll_listeners.drain(..) {
2962 let hitbox = hitbox.clone();
2963 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
2964 listener(event, phase, &hitbox, window, cx);
2965 })
2966 }
2967
2968 for listener in self.pinch_listeners.drain(..) {
2969 let hitbox = hitbox.clone();
2970 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2971 listener(event, phase, &hitbox, window, cx);
2972 })
2973 }
2974
2975 for listener in self.back_gesture_listeners.drain(..) {
2976 let hitbox = hitbox.clone();
2977 window.on_mouse_event(move |event: &BackGestureEvent, phase, window, cx| {
2978 listener(event, phase, &hitbox, window, cx);
2979 })
2980 }
2981
2982 if self.hover_style.is_some()
2983 || self.base_style.mouse_cursor.is_some()
2984 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2985 {
2986 let hitbox = hitbox.clone();
2987 let hover_state = self.hover_style.as_ref().and_then(|_| {
2988 element_state
2989 .as_ref()
2990 .and_then(|state| state.hover_state.as_ref())
2991 .cloned()
2992 });
2993 let current_view = window.current_view();
2994 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
2995
2996 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2997 let hovered = hitbox.is_hovered(window);
2998 let was_hovered = hover_state
2999 .as_ref()
3000 .is_some_and(|state| state.borrow().element);
3001 if phase == DispatchPhase::Capture && hovered != was_hovered {
3002 if let Some(hover_state) = &hover_state {
3003 hover_state.borrow_mut().element = hovered;
3004 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
3005 cx.notify(current_view);
3006 }
3007 }
3008 });
3009 }
3010
3011 if let Some(group_hover) = self.group_hover_style.as_ref() {
3012 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3013 let hover_state = element_state
3014 .as_ref()
3015 .and_then(|element| element.hover_state.as_ref())
3016 .cloned();
3017 let current_view = window.current_view();
3018 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
3019
3020 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3021 let group_hovered = group_hitbox_id.is_hovered(window);
3022 let was_group_hovered = hover_state
3023 .as_ref()
3024 .is_some_and(|state| state.borrow().group);
3025 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
3026 if let Some(hover_state) = &hover_state {
3027 hover_state.borrow_mut().group = group_hovered;
3028 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
3029 cx.notify(current_view);
3030 }
3031 }
3032 });
3033 }
3034 }
3035
3036 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
3037
3038 let mut drag_listener = mem::take(&mut self.drag_listener);
3039 let drop_listeners = mem::take(&mut self.drop_listeners);
3040 let click_listeners = mem::take(&mut self.click_listeners);
3041 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
3042 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
3043
3044 if !drop_listeners.is_empty() {
3045 let hitbox = hitbox.clone();
3046 window.on_mouse_event({
3047 move |_: &MouseUpEvent, phase, window, cx| {
3048 if let Some(drag) = &cx.active_drag
3049 && phase == DispatchPhase::Bubble
3050 && hitbox.is_hovered(window)
3051 {
3052 let drag_state_type = drag.value.as_ref().type_id();
3053 for (drop_state_type, listener) in &drop_listeners {
3054 if *drop_state_type == drag_state_type {
3055 let drag = cx
3056 .active_drag
3057 .take()
3058 .expect("checked for type drag state type above");
3059
3060 let mut can_drop = true;
3061 if let Some(predicate) = &can_drop_predicate {
3062 can_drop = predicate(drag.value.as_ref(), window, cx);
3063 }
3064
3065 if can_drop {
3066 listener(drag.value.as_ref(), window, cx);
3067 window.refresh();
3068 cx.stop_propagation();
3069 }
3070 }
3071 }
3072 }
3073 }
3074 });
3075 }
3076
3077 if let Some(element_state) = element_state {
3078 if !click_listeners.is_empty()
3079 || !aux_click_listeners.is_empty()
3080 || drag_listener.is_some()
3081 {
3082 let pending_mouse_down = element_state
3083 .pending_mouse_down
3084 .get_or_insert_with(Default::default)
3085 .clone();
3086
3087 let pending_keyboard_down = element_state
3088 .pending_keyboard_down
3089 .get_or_insert_with(Default::default)
3090 .clone();
3091
3092 let clicked_state = element_state
3093 .clicked_state
3094 .get_or_insert_with(Default::default)
3095 .clone();
3096
3097 window.on_mouse_event({
3098 let pending_mouse_down = pending_mouse_down.clone();
3099 let hitbox = hitbox.clone();
3100 let has_aux_click_listeners = !aux_click_listeners.is_empty();
3101 move |event: &MouseDownEvent, phase, window, _cx| {
3102 if phase == DispatchPhase::Bubble
3103 && (event.button == MouseButton::Left || has_aux_click_listeners)
3104 && hitbox.is_hovered(window)
3105 {
3106 *pending_mouse_down.borrow_mut() = Some(event.clone());
3107 window.refresh();
3108 }
3109 }
3110 });
3111
3112 window.on_mouse_event({
3113 let pending_mouse_down = pending_mouse_down.clone();
3114 let hitbox = hitbox.clone();
3115 move |event: &MouseMoveEvent, phase, window, cx| {
3116 if phase == DispatchPhase::Capture {
3117 return;
3118 }
3119
3120 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3121 if let Some(mouse_down) = pending_mouse_down.clone()
3122 && !cx.has_active_drag()
3123 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
3124 && let Some(listener) = drag_listener.take()
3125 && mouse_down.button == MouseButton::Left
3126 {
3127 *clicked_state.borrow_mut() = ElementClickedState::default();
3128 let cursor_offset = event.position - hitbox.origin;
3129 let drag = (listener.render)(
3130 listener.value.as_ref(),
3131 cursor_offset,
3132 window,
3133 cx,
3134 );
3135 let external_payload_source =
3136 listener.external_payload.map(|external_payload| {
3137 let value = listener.value.clone();
3138 Box::new(move |window: &mut Window, cx: &mut App| {
3139 external_payload(value.as_ref(), window, cx)
3140 })
3141 as ExternalDragPayloadSource
3142 });
3143 cx.active_drag = Some(AnyDrag {
3144 view: drag,
3145 value: listener.value,
3146 cursor_offset,
3147 cursor_style: drag_cursor_style,
3148 external_payload_source,
3149 });
3150 pending_mouse_down.take();
3151 window.refresh();
3152 cx.stop_propagation();
3153 }
3154 }
3155 });
3156
3157 if is_focused {
3158 window.on_key_event({
3168 let pending_keyboard_down = pending_keyboard_down.clone();
3169 move |event: &KeyDownEvent, phase, window, _cx| {
3170 if phase.bubble() && !window.default_prevented() {
3171 let stroke = &event.keystroke;
3172 let is_activation_key = (stroke.key.eq("enter")
3173 || stroke.key.eq("space"))
3174 && !stroke.modifiers.modified();
3175 *pending_keyboard_down.borrow_mut() =
3176 is_activation_key.then_some(window.focus_generation);
3177 }
3178 }
3179 });
3180
3181 window.on_key_event({
3183 let click_listeners = click_listeners.clone();
3184 let hitbox = hitbox.clone();
3185 move |event: &KeyUpEvent, phase, window, cx| {
3186 if phase.bubble() && !window.default_prevented() {
3187 let stroke = &event.keystroke;
3188 let keyboard_button = if stroke.key.eq("enter") {
3189 Some(KeyboardButton::Enter)
3190 } else if stroke.key.eq("space") {
3191 Some(KeyboardButton::Space)
3192 } else {
3193 None
3194 };
3195
3196 if let Some(button) = keyboard_button
3197 && !stroke.modifiers.modified()
3198 {
3199 let pending =
3200 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
3201 if pending != Some(window.focus_generation) {
3202 return;
3203 }
3204
3205 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
3206 button,
3207 bounds: hitbox.bounds,
3208 });
3209
3210 for listener in &click_listeners {
3211 listener(&click_event, window, cx);
3212 }
3213 } else {
3214 *pending_keyboard_down.borrow_mut() = None;
3218 }
3219 }
3220 }
3221 });
3222 }
3223
3224 window.on_mouse_event({
3225 let mut captured_mouse_down = None;
3226 let hitbox = hitbox.clone();
3227 move |event: &MouseUpEvent, phase, window, cx| match phase {
3228 DispatchPhase::Capture => {
3232 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3233 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
3234 captured_mouse_down = pending_mouse_down.take();
3235 window.refresh();
3236 } else if pending_mouse_down.is_some() {
3237 pending_mouse_down.take();
3243 window.refresh();
3244 }
3245 }
3246 DispatchPhase::Bubble => {
3248 if let Some(mouse_down) = captured_mouse_down.take() {
3249 let btn = mouse_down.button;
3250
3251 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
3252 down: mouse_down,
3253 up: event.clone(),
3254 });
3255
3256 match btn {
3257 MouseButton::Left => {
3258 for listener in &click_listeners {
3259 listener(&mouse_click, window, cx);
3260 }
3261 }
3262 _ => {
3263 for listener in &aux_click_listeners {
3264 listener(&mouse_click, window, cx);
3265 }
3266 }
3267 }
3268 }
3269 }
3270 }
3271 });
3272 }
3273
3274 if let Some(hover_listener) = self.hover_listener.take() {
3275 let was_hovered = element_state
3276 .hover_listener_state
3277 .get_or_insert_with(Default::default)
3278 .clone();
3279 let has_mouse_down = element_state
3280 .pending_mouse_down
3281 .get_or_insert_with(Default::default)
3282 .clone();
3283 let hover_listener = crate::fast::layers::hover_freeze::track_listener(
3284 window,
3285 &was_hovered,
3286 &has_mouse_down,
3287 hover_listener,
3288 hitbox,
3289 self.hover_listener_mode,
3290 );
3291 let hover_listener_state = was_hovered.clone();
3292 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3293 let mut was_hovered = hover_listener_state.borrow_mut();
3294 if is_hovered != *was_hovered {
3295 *was_hovered = is_hovered;
3296 drop(was_hovered);
3297 hover_listener(&is_hovered, window, cx);
3298 }
3299 };
3300 let hover_listener_mode = self.hover_listener_mode;
3301
3302 if has_mouse_down.borrow().is_none()
3303 && !crate::fast::layers::hover_freeze::holds_listeners(window)
3304 {
3305 let is_hovered =
3306 !cx.has_active_drag() && hover_listener_mode.is_hovered(hitbox, window);
3307 if is_hovered != *was_hovered.borrow() {
3308 let update_hover = update_hover.clone();
3309 window.defer(cx, move |window, cx| {
3310 update_hover(is_hovered, window, cx);
3311 });
3312 }
3313 }
3314
3315 window.on_mouse_event({
3316 let update_hover = update_hover.clone();
3317 let hitbox = hitbox.clone();
3318 move |_: &MouseMoveEvent, phase, window, cx| {
3319 if phase == DispatchPhase::Bubble {
3320 let is_hovered = has_mouse_down.borrow().is_none()
3321 && !cx.has_active_drag()
3322 && hover_listener_mode.is_hovered(&hitbox, window);
3323 update_hover(is_hovered, window, cx);
3324 }
3325 }
3326 });
3327
3328 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3331 if phase == DispatchPhase::Bubble {
3332 update_hover(false, window, cx);
3333 }
3334 });
3335 }
3336
3337 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3338 let active_tooltip = element_state
3339 .active_tooltip
3340 .get_or_insert_with(Default::default)
3341 .clone();
3342 let pending_mouse_down = element_state
3343 .pending_mouse_down
3344 .get_or_insert_with(Default::default)
3345 .clone();
3346 let long_press_tooltip_active = element_state
3347 .long_press_tooltip_active
3348 .get_or_insert_with(Default::default)
3349 .clone();
3350
3351 let tooltip_is_hoverable = tooltip_builder.hoverable;
3352 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3353 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3354 });
3355 let check_is_hovered_during_prepaint = Rc::new({
3357 let pending_mouse_down = pending_mouse_down.clone();
3358 let source_bounds = hitbox.bounds;
3359 move |window: &Window| {
3360 !window.last_input_was_keyboard()
3361 && pending_mouse_down.borrow().is_none()
3362 && source_bounds.contains(&window.mouse_position())
3363 }
3364 });
3365 let check_is_hovered = Rc::new({
3366 let hitbox = hitbox.clone();
3367 move |window: &Window| {
3368 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3369 }
3370 });
3371 register_tooltip_mouse_handlers(
3372 &active_tooltip,
3373 self.tooltip_id,
3374 build_tooltip,
3375 check_is_hovered,
3376 check_is_hovered_during_prepaint,
3377 long_press_tooltip_active,
3378 self.tooltip_show_delay,
3379 window,
3380 );
3381 }
3382
3383 let active_state = element_state
3386 .clicked_state
3387 .get_or_insert_with(Default::default)
3388 .clone();
3389
3390 {
3391 let active_state = active_state.clone();
3392 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3393 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3394 *active_state.borrow_mut() = ElementClickedState::default();
3395 window.refresh();
3396 }
3397 });
3398 }
3399
3400 {
3401 let active_group_hitbox = self
3402 .group_active_style
3403 .as_ref()
3404 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3405 let hitbox = hitbox.clone();
3406 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3407 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3408 let group_hovered = active_group_hitbox
3409 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3410 let element_hovered = hitbox.is_hovered(window);
3411 if group_hovered || element_hovered {
3412 *active_state.borrow_mut() = ElementClickedState {
3413 group: group_hovered,
3414 element: element_hovered,
3415 };
3416 window.refresh();
3417 }
3418 }
3419 });
3420 }
3421 }
3422 }
3423
3424 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3425 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3426 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3427 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3428 let action_listeners = mem::take(&mut self.action_listeners);
3429 if let Some(context) = self.key_context.clone() {
3430 window.set_key_context(context);
3431 }
3432
3433 for listener in key_down_listeners {
3434 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3435 listener(event, phase, window, cx);
3436 })
3437 }
3438
3439 for listener in key_up_listeners {
3440 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3441 listener(event, phase, window, cx);
3442 })
3443 }
3444
3445 for listener in modifiers_changed_listeners {
3446 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3447 listener(event, window, cx);
3448 })
3449 }
3450
3451 for (action_type, listener) in action_listeners {
3452 window.on_action(action_type, listener)
3453 }
3454 }
3455
3456 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3457 let group_hitbox = self
3458 .group_hover_style
3459 .as_ref()
3460 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3461
3462 if let Some(group_hitbox) = group_hitbox {
3463 let was_hovered = group_hitbox.is_hovered(window);
3464 let current_view = window.current_view();
3465 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
3466 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3467 let hovered = group_hitbox.is_hovered(window);
3468 if phase == DispatchPhase::Capture && hovered != was_hovered {
3469 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
3470 cx.notify(current_view);
3471 }
3472 });
3473 }
3474 }
3475
3476 fn paint_scroll_listener(
3477 &self,
3478 hitbox: &Hitbox,
3479 style: &Style,
3480 window: &mut Window,
3481 _cx: &mut App,
3482 ) {
3483 if let Some(scroll_offset) = self.scroll_offset.clone() {
3484 let ongoing_scroll = self.ongoing_scroll.clone();
3485 let overflow = style.overflow;
3486 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3487 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3488 let line_height = window.line_height();
3489 let fast_scroll_max =
3490 crate::fast::layers::wheel::scroll_max(self, hitbox.bounds, style, window);
3491 let hitbox = hitbox.clone();
3492 let current_view = window.current_view();
3493 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
3494 let fast_container = crate::fast::layers::invalidate::painted_container(window, self);
3495 window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
3496 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3497 let mut scroll_offset = scroll_offset.borrow_mut();
3498 let old_scroll_offset = *scroll_offset;
3499 let mut delta = event.delta.pixel_delta(line_height);
3500
3501 if restrict_scroll_to_axis
3502 && event.delta.precise()
3503 && let Some(ongoing_scroll) = &ongoing_scroll
3504 {
3505 ongoing_scroll
3506 .borrow_mut()
3507 .filter(&mut delta, event.touch_phase);
3508 }
3509
3510 let mut delta_x = match overflow.x {
3511 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3512 Overflow::Scroll
3513 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3514 {
3515 delta.y
3516 }
3517 _ => Pixels::ZERO,
3518 };
3519 let mut delta_y = match overflow.y {
3520 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3521 Overflow::Scroll
3522 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3523 {
3524 delta.x
3525 }
3526 _ => Pixels::ZERO,
3527 };
3528 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3529 if delta_x.abs() > delta_y.abs() {
3530 delta_y = Pixels::ZERO;
3531 } else {
3532 delta_x = Pixels::ZERO;
3533 }
3534 }
3535 if !crate::fast::layers::wheel::moves(
3536 old_scroll_offset,
3537 point(delta_x, delta_y),
3538 fast_scroll_max,
3539 ) {
3540 return;
3541 }
3542 scroll_offset.y += delta_y;
3543 scroll_offset.x += delta_x;
3544 if *scroll_offset != old_scroll_offset {
3545 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
3546 crate::fast::layers::invalidate::note_scrolled(window, &fast_container);
3547 cx.notify(current_view);
3548 }
3549 }
3550 });
3551 }
3552 }
3553
3554 pub fn compute_style(
3556 &self,
3557 global_id: Option<&GlobalElementId>,
3558 hitbox: Option<&Hitbox>,
3559 window: &mut Window,
3560 cx: &mut App,
3561 ) -> Style {
3562 window.with_optional_element_state(global_id, |element_state, window| {
3563 let mut element_state =
3564 element_state.map(|element_state| element_state.unwrap_or_default());
3565 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3566 (style, element_state)
3567 })
3568 }
3569
3570 fn compute_style_internal(
3572 &self,
3573 hitbox: Option<&Hitbox>,
3574 element_state: Option<&mut InteractiveElementState>,
3575 window: &mut Window,
3576 cx: &mut App,
3577 ) -> Style {
3578 let mut style = Style::default();
3579 style.refine(&self.base_style);
3580
3581 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3582 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3583 && focus_handle.within_focused(window, cx)
3584 {
3585 style.refine(in_focus_style);
3586 }
3587
3588 if let Some(focus_style) = self.focus_style.as_ref()
3589 && focus_handle.is_focused(window)
3590 {
3591 style.refine(focus_style);
3592 }
3593
3594 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3595 && focus_handle.is_focused(window)
3596 && window.last_input_was_keyboard()
3597 {
3598 style.refine(focus_visible_style);
3599 }
3600 }
3601
3602 if !cx.has_active_drag() {
3603 if let Some(group_hover) = self.group_hover_style.as_ref() {
3604 let is_group_hovered =
3605 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3606 !window.last_input_was_touch() && group_hitbox_id.is_hovered(window)
3607 } else if let Some(element_state) = element_state.as_ref() {
3608 !window.last_input_was_touch()
3609 && element_state
3610 .hover_state
3611 .as_ref()
3612 .map(|state| state.borrow().group)
3613 .unwrap_or(false)
3614 } else {
3615 false
3616 };
3617
3618 if is_group_hovered {
3619 style.refine(&group_hover.style);
3620 }
3621 }
3622
3623 if let Some(hover_style) = self.hover_style.as_ref() {
3624 let is_hovered = if let Some(hitbox) = hitbox {
3625 !window.last_input_was_touch() && hitbox.is_hovered(window)
3626 } else if let Some(element_state) = element_state.as_ref() {
3627 !window.last_input_was_touch()
3628 && element_state
3629 .hover_state
3630 .as_ref()
3631 .map(|state| state.borrow().element)
3632 .unwrap_or(false)
3633 } else {
3634 false
3635 };
3636
3637 if is_hovered {
3638 style.refine(hover_style);
3639 }
3640 }
3641 }
3642
3643 if let Some(hitbox) = hitbox {
3644 if let Some(drag) = cx.active_drag.take() {
3645 let mut can_drop = true;
3646 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3647 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3648 }
3649
3650 if can_drop {
3651 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3652 if let Some(group_hitbox_id) =
3653 GroupHitboxes::get(&group_drag_style.group, cx)
3654 && *state_type == drag.value.as_ref().type_id()
3655 && group_hitbox_id.is_hovered(window)
3656 {
3657 style.refine(&group_drag_style.style);
3658 }
3659 }
3660
3661 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3662 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3663 {
3664 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3665 }
3666 }
3667 }
3668
3669 style.mouse_cursor = drag.cursor_style;
3670 cx.active_drag = Some(drag);
3671 }
3672 }
3673
3674 if let Some(element_state) = element_state {
3675 let clicked_state = element_state
3676 .clicked_state
3677 .get_or_insert_with(Default::default)
3678 .borrow();
3679 if clicked_state.group
3680 && let Some(group) = self.group_active_style.as_ref()
3681 {
3682 style.refine(&group.style)
3683 }
3684
3685 if let Some(active_style) = self.active_style.as_ref()
3686 && clicked_state.element
3687 {
3688 style.refine(active_style)
3689 }
3690 }
3691
3692 style
3693 }
3694
3695 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3696 if let Some(id) = &self.aria.author_id {
3697 node.set_author_id(id.to_string());
3698 }
3699 if let Some(label) = &self.aria.label {
3700 node.set_label(label.to_string());
3701 }
3702 if let Some(description) = &self.aria.description {
3703 node.set_description(description.to_string());
3704 }
3705 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3706 node.set_keyboard_shortcut(keyshortcuts.to_string());
3707 }
3708 if let Some(selected) = self.aria.selected {
3709 node.set_selected(selected);
3710 }
3711 if let Some(expanded) = self.aria.expanded {
3712 node.set_expanded(expanded);
3713 }
3714 if let Some(toggled) = self.aria.toggled {
3715 node.set_toggled(toggled);
3716 }
3717 if let Some(value) = self.aria.numeric_value {
3718 node.set_numeric_value(value);
3719 }
3720 if let Some(value) = self.aria.min_numeric_value {
3721 node.set_min_numeric_value(value);
3722 }
3723 if let Some(value) = self.aria.max_numeric_value {
3724 node.set_max_numeric_value(value);
3725 }
3726 if let Some(step) = self.aria.numeric_value_step {
3727 node.set_numeric_value_step(step);
3728 }
3729 if let Some(value) = &self.aria.value {
3730 node.set_value(value.to_string());
3731 }
3732 if let Some(placeholder) = &self.aria.placeholder {
3733 node.set_placeholder(placeholder.to_string());
3734 }
3735 if let Some(orientation) = self.aria.orientation {
3736 node.set_orientation(orientation);
3737 }
3738 if let Some(level) = self.aria.level {
3739 node.set_level(level);
3740 }
3741 if let Some(position) = self.aria.position_in_set {
3742 node.set_position_in_set(position);
3743 }
3744 if let Some(size) = self.aria.size_of_set {
3745 node.set_size_of_set(size);
3746 }
3747 if let Some(index) = self.aria.row_index {
3748 node.set_row_index(index);
3749 }
3750 if let Some(index) = self.aria.column_index {
3751 node.set_column_index(index);
3752 }
3753 if let Some(count) = self.aria.row_count {
3754 node.set_row_count(count);
3755 }
3756 if let Some(count) = self.aria.column_count {
3757 node.set_column_count(count);
3758 }
3759 if !self.click_listeners.is_empty() {
3760 node.add_action(accesskit::Action::Click);
3761 }
3762 if self.tracked_focus_handle.is_some() || self.focusable {
3763 node.add_action(accesskit::Action::Focus);
3764 }
3765 for (action, _) in &self.a11y_action_listeners {
3766 node.add_action(*action);
3767 }
3768 }
3769}
3770
3771#[derive(Default)]
3774pub struct InteractiveElementState {
3775 pub(crate) focus_handle: Option<FocusHandle>,
3776 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3777 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3778 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3779 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3780 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3788 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3789 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3790 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3791 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3792}
3793
3794#[derive(Copy, Clone, Default, Eq, PartialEq)]
3796pub struct ElementClickedState {
3797 pub group: bool,
3799
3800 pub element: bool,
3802}
3803
3804impl ElementClickedState {
3805 fn is_clicked(&self) -> bool {
3806 self.group || self.element
3807 }
3808}
3809
3810#[derive(Copy, Clone, Default, Eq, PartialEq)]
3812pub struct ElementHoverState {
3813 pub group: bool,
3815
3816 pub element: bool,
3818}
3819
3820pub(crate) enum ActiveTooltip {
3821 WaitingForShow { _task: Task<()> },
3823 Visible {
3825 tooltip: AnyTooltip,
3826 is_hoverable: bool,
3827 },
3828 WaitingForHide {
3831 tooltip: AnyTooltip,
3832 _task: Task<()>,
3833 },
3834}
3835
3836pub(crate) fn clear_active_tooltip(
3837 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3838 window: &mut Window,
3839) {
3840 match active_tooltip.borrow_mut().take() {
3841 None => {}
3842 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3843 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3844 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3845 }
3846}
3847
3848pub(crate) fn clear_active_tooltip_if_not_hoverable(
3849 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3850 window: &mut Window,
3851) {
3852 let should_clear = match active_tooltip.borrow().as_ref() {
3853 None => false,
3854 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3855 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3856 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3857 };
3858 if should_clear {
3859 active_tooltip.borrow_mut().take();
3860 window.refresh();
3861 }
3862}
3863
3864pub(crate) fn set_tooltip_on_window(
3865 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3866 window: &mut Window,
3867) -> Option<TooltipId> {
3868 let tooltip = match active_tooltip.borrow().as_ref() {
3869 None => return None,
3870 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3871 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3872 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3873 };
3874 Some(window.set_tooltip(tooltip))
3875}
3876
3877pub(crate) fn register_tooltip_mouse_handlers(
3878 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3879 tooltip_id: Option<TooltipId>,
3880 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3881 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3882 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3883 long_press_tooltip_active: Rc<Cell<bool>>,
3884 show_delay: Option<Duration>,
3885 window: &mut Window,
3886) {
3887 let current_view = window.current_view();
3888 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3889
3890 window.on_mouse_event({
3891 let active_tooltip = active_tooltip.clone();
3892 let build_tooltip = build_tooltip.clone();
3893 let check_is_hovered = check_is_hovered.clone();
3894 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3895 move |_: &MouseMoveEvent, phase, window, cx| {
3896 handle_tooltip_mouse_move(
3897 &active_tooltip,
3898 &build_tooltip,
3899 &check_is_hovered,
3900 &check_is_hovered_during_prepaint,
3901 tooltip_id,
3902 current_view,
3903 phase,
3904 show_delay,
3905 window,
3906 cx,
3907 )
3908 }
3909 });
3910
3911 window.on_mouse_event({
3912 let active_tooltip = active_tooltip.clone();
3913 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3914 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3915 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3916 }
3917 }
3918 });
3919
3920 window.on_mouse_event({
3921 let active_tooltip = active_tooltip.clone();
3922 let build_tooltip = build_tooltip.clone();
3923 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3924 move |event: &LongPressEvent, phase, window, cx| {
3925 if !phase.bubble() {
3926 return;
3927 }
3928
3929 match event.phase {
3930 TouchPhase::Started if !window.default_prevented() && check_is_hovered(window) => {
3931 if show_tooltip(
3932 &active_tooltip,
3933 &build_tooltip,
3934 &check_is_hovered_during_prepaint,
3935 Some(long_press_tooltip_active.clone()),
3936 window,
3937 cx,
3938 ) {
3939 long_press_tooltip_active.set(true);
3940 window.prevent_default();
3941 cx.stop_propagation();
3942 }
3943 }
3944 TouchPhase::Ended | TouchPhase::Cancelled
3945 if long_press_tooltip_active.replace(false) =>
3946 {
3947 clear_active_tooltip(&active_tooltip, window);
3948 cx.stop_propagation();
3949 }
3950 TouchPhase::Started
3951 | TouchPhase::Moved
3952 | TouchPhase::Ended
3953 | TouchPhase::Cancelled => {}
3954 }
3955 }
3956 });
3957
3958 window.on_mouse_event({
3959 let active_tooltip = active_tooltip.clone();
3960 move |_: &ScrollEvent, _phase, window: &mut Window, _cx| {
3961 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3962 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3963 }
3964 }
3965 });
3966}
3967
3968fn handle_tooltip_mouse_move(
3980 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3981 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3982 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3983 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3984 tooltip_id: Option<TooltipId>,
3985 current_view: EntityId,
3986 phase: DispatchPhase,
3987 show_delay: Duration,
3988 window: &mut Window,
3989 cx: &mut App,
3990) {
3991 enum Action {
3994 None,
3995 CancelShow,
3996 ScheduleShow,
3997 CheckVisible,
3998 }
3999
4000 let action = match active_tooltip.borrow().as_ref() {
4001 None => {
4002 let is_hovered = check_is_hovered(window);
4003 if is_hovered && phase.bubble() {
4004 Action::ScheduleShow
4005 } else {
4006 Action::None
4007 }
4008 }
4009 Some(ActiveTooltip::WaitingForShow { .. }) => {
4010 let is_hovered = check_is_hovered(window);
4011 if is_hovered {
4012 Action::None
4013 } else {
4014 Action::CancelShow
4015 }
4016 }
4017 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
4018 if phase.capture()
4019 && !check_is_hovered(window)
4020 && (!*is_hoverable
4021 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
4022 {
4023 Action::CheckVisible
4024 } else {
4025 Action::None
4026 }
4027 }
4028 Some(ActiveTooltip::WaitingForHide { .. }) => {
4029 if phase.capture()
4030 && (check_is_hovered(window)
4031 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
4032 {
4033 Action::CheckVisible
4034 } else {
4035 Action::None
4036 }
4037 }
4038 };
4039
4040 match action {
4041 Action::None => {}
4042 Action::CancelShow => {
4043 active_tooltip.borrow_mut().take();
4045 }
4046 Action::ScheduleShow => {
4047 let delayed_show_task = window.spawn(cx, {
4048 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4049 let build_tooltip = build_tooltip.clone();
4050 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4051 async move |cx| {
4052 cx.background_executor().timer(show_delay).await;
4053 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4054 return;
4055 };
4056 cx.update(|window, cx| {
4057 show_tooltip(
4058 &active_tooltip,
4059 &build_tooltip,
4060 &check_is_hovered_during_prepaint,
4061 None,
4062 window,
4063 cx,
4064 );
4065 })
4066 .ok();
4067 }
4068 });
4069 active_tooltip
4070 .borrow_mut()
4071 .replace(ActiveTooltip::WaitingForShow {
4072 _task: delayed_show_task,
4073 });
4074 }
4075 Action::CheckVisible => cx.notify(current_view),
4076 }
4077}
4078
4079fn show_tooltip(
4080 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4081 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
4082 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
4083 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
4084 window: &mut Window,
4085 cx: &mut App,
4086) -> bool {
4087 let new_tooltip = build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
4088 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4089 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
4090 ActiveTooltip::Visible {
4091 tooltip: AnyTooltip {
4092 view,
4093 mouse_position: window.mouse_position(),
4094 check_visible_and_update: Rc::new(move |tooltip_bounds, window, cx| {
4095 if long_press_tooltip_active
4096 .as_ref()
4097 .is_some_and(|active| active.get())
4098 {
4099 return true;
4100 }
4101 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4102 return false;
4103 };
4104 handle_tooltip_check_visible_and_update(
4105 &active_tooltip,
4106 tooltip_is_hoverable,
4107 &check_is_hovered_during_prepaint,
4108 tooltip_bounds,
4109 window,
4110 cx,
4111 )
4112 }),
4113 },
4114 is_hoverable: tooltip_is_hoverable,
4115 }
4116 });
4117 let did_show = new_tooltip.is_some();
4118 *active_tooltip.borrow_mut() = new_tooltip;
4119 window.refresh();
4120 did_show
4121}
4122
4123fn handle_tooltip_check_visible_and_update(
4127 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4128 tooltip_is_hoverable: bool,
4129 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
4130 tooltip_bounds: Bounds<Pixels>,
4131 window: &mut Window,
4132 cx: &mut App,
4133) -> bool {
4134 enum Action {
4137 None,
4138 Hide,
4139 ScheduleHide(AnyTooltip),
4140 CancelHide(AnyTooltip),
4141 }
4142
4143 let is_hovered = check_is_hovered(window)
4144 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
4145 let action = match active_tooltip.borrow().as_ref() {
4146 Some(ActiveTooltip::Visible { tooltip, .. }) => {
4147 if is_hovered {
4148 Action::None
4149 } else {
4150 if tooltip_is_hoverable {
4151 Action::ScheduleHide(tooltip.clone())
4152 } else {
4153 Action::Hide
4154 }
4155 }
4156 }
4157 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
4158 if is_hovered {
4159 Action::CancelHide(tooltip.clone())
4160 } else {
4161 Action::None
4162 }
4163 }
4164 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
4165 };
4166
4167 match action {
4168 Action::None => {}
4169 Action::Hide => clear_active_tooltip(active_tooltip, window),
4170 Action::ScheduleHide(tooltip) => {
4171 let delayed_hide_task = window.spawn(cx, {
4172 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4173 async move |cx| {
4174 cx.background_executor()
4175 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
4176 .await;
4177 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4178 return;
4179 };
4180 if active_tooltip.borrow_mut().take().is_some() {
4181 cx.update(|window, _cx| window.refresh()).ok();
4182 }
4183 }
4184 });
4185 active_tooltip
4186 .borrow_mut()
4187 .replace(ActiveTooltip::WaitingForHide {
4188 tooltip,
4189 _task: delayed_hide_task,
4190 });
4191 }
4192 Action::CancelHide(tooltip) => {
4193 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
4195 tooltip,
4196 is_hoverable: true,
4197 });
4198 }
4199 }
4200
4201 active_tooltip.borrow().is_some()
4202}
4203
4204#[derive(Default)]
4205pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
4206
4207impl Global for GroupHitboxes {}
4208
4209impl GroupHitboxes {
4210 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
4211 cx.default_global::<Self>()
4212 .0
4213 .get(name)
4214 .and_then(|bounds_stack| bounds_stack.last())
4215 .cloned()
4216 }
4217
4218 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
4219 cx.default_global::<Self>()
4220 .0
4221 .entry(name)
4222 .or_default()
4223 .push(hitbox_id);
4224 }
4225
4226 pub fn pop(name: &SharedString, cx: &mut App) {
4227 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
4228 }
4229}
4230
4231pub struct Stateful<E> {
4233 pub(crate) element: E,
4234}
4235
4236impl<E> Styled for Stateful<E>
4237where
4238 E: Styled,
4239{
4240 fn style(&mut self) -> &mut StyleRefinement {
4241 self.element.style()
4242 }
4243}
4244
4245impl<E> StatefulInteractiveElement for Stateful<E>
4246where
4247 E: Element,
4248 Self: InteractiveElement,
4249{
4250}
4251
4252impl<E> InteractiveElement for Stateful<E>
4253where
4254 E: InteractiveElement,
4255{
4256 fn interactivity(&mut self) -> &mut Interactivity {
4257 self.element.interactivity()
4258 }
4259}
4260
4261impl<E> Element for Stateful<E>
4262where
4263 E: Element,
4264{
4265 type RequestLayoutState = E::RequestLayoutState;
4266 type PrepaintState = E::PrepaintState;
4267
4268 fn id(&self) -> Option<ElementId> {
4269 self.element.id()
4270 }
4271
4272 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4273 self.element.source_location()
4274 }
4275
4276 fn a11y_role(&self) -> Option<accesskit::Role> {
4277 self.element.a11y_role()
4278 }
4279
4280 fn write_a11y_info(&self, node: &mut accesskit::Node) {
4281 self.element.write_a11y_info(node);
4282 }
4283
4284 fn a11y_synthetic_children(
4285 &mut self,
4286 prepaint: &mut Self::PrepaintState,
4287 builder: &mut crate::A11ySubtreeBuilder,
4288 ) {
4289 self.element.a11y_synthetic_children(prepaint, builder);
4290 }
4291
4292 fn request_layout(
4293 &mut self,
4294 id: Option<&GlobalElementId>,
4295 inspector_id: Option<&InspectorElementId>,
4296 window: &mut Window,
4297 cx: &mut App,
4298 ) -> (LayoutId, Self::RequestLayoutState) {
4299 self.element.request_layout(id, inspector_id, window, cx)
4300 }
4301
4302 fn prepaint(
4303 &mut self,
4304 id: Option<&GlobalElementId>,
4305 inspector_id: Option<&InspectorElementId>,
4306 bounds: Bounds<Pixels>,
4307 state: &mut Self::RequestLayoutState,
4308 window: &mut Window,
4309 cx: &mut App,
4310 ) -> E::PrepaintState {
4311 self.element
4312 .prepaint(id, inspector_id, bounds, state, window, cx)
4313 }
4314
4315 fn paint(
4316 &mut self,
4317 id: Option<&GlobalElementId>,
4318 inspector_id: Option<&InspectorElementId>,
4319 bounds: Bounds<Pixels>,
4320 request_layout: &mut Self::RequestLayoutState,
4321 prepaint: &mut Self::PrepaintState,
4322 window: &mut Window,
4323 cx: &mut App,
4324 ) {
4325 self.element.paint(
4326 id,
4327 inspector_id,
4328 bounds,
4329 request_layout,
4330 prepaint,
4331 window,
4332 cx,
4333 );
4334 }
4335}
4336
4337impl<E> ParentElement for Stateful<E>
4338where
4339 E: ParentElement,
4340{
4341 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4342 self.element.extend(elements)
4343 }
4344}
4345
4346#[derive(Clone)]
4349pub struct ScrollAnchor {
4350 handle: ScrollHandle,
4351 last_origin: Rc<RefCell<Point<Pixels>>>,
4352}
4353
4354impl ScrollAnchor {
4355 pub fn for_handle(handle: ScrollHandle) -> Self {
4357 Self {
4358 handle,
4359 last_origin: Default::default(),
4360 }
4361 }
4362 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4364 let this = self.clone();
4365
4366 window.on_next_frame(move |_, _| {
4367 let viewport_bounds = this.handle.bounds();
4368 let self_bounds = *this.last_origin.borrow();
4369 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4370 });
4371 }
4372}
4373
4374#[derive(Default, Debug)]
4375pub(crate) struct ScrollHandleState {
4376 pub(crate) offset: Rc<RefCell<Point<Pixels>>>,
4377 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4378 bounds: Bounds<Pixels>,
4379 pub(crate) max_offset: Point<Pixels>,
4380 child_bounds: Vec<Bounds<Pixels>>,
4381 pub(crate) scroll_to_bottom: bool,
4382 overflow: Point<Overflow>,
4383 active_item: Option<ScrollActiveItem>,
4384 pub(crate) version: crate::fast::dependencies::StateVersion,
4385}
4386
4387#[derive(Default, Debug, Clone, Copy)]
4388struct ScrollActiveItem {
4389 index: usize,
4390 strategy: ScrollStrategy,
4391}
4392
4393#[derive(Default, Debug, Clone, Copy)]
4394enum ScrollStrategy {
4395 #[default]
4396 FirstVisible,
4397 Top,
4398}
4399
4400#[derive(Clone, Debug)]
4404pub struct ScrollHandle(pub(crate) Rc<RefCell<ScrollHandleState>>);
4405
4406impl Default for ScrollHandle {
4407 fn default() -> Self {
4408 Self::new()
4409 }
4410}
4411
4412impl ScrollHandle {
4413 pub fn new() -> Self {
4415 Self(Rc::default())
4416 }
4417
4418 pub fn offset(&self) -> Point<Pixels> {
4420 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
4421 *self.0.borrow().offset.borrow()
4422 }
4423
4424 pub fn max_offset(&self) -> Point<Pixels> {
4426 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
4427 self.0.borrow().max_offset
4428 }
4429
4430 pub fn top_item(&self) -> usize {
4432 let state = self.0.borrow();
4433 crate::fast::layers::invalidate::note_offset_read(&state.version);
4434 let top = state.bounds.top() - state.offset.borrow().y;
4435
4436 match state.child_bounds.binary_search_by(|bounds| {
4437 if top < bounds.top() {
4438 Ordering::Greater
4439 } else if top > bounds.bottom() {
4440 Ordering::Less
4441 } else {
4442 Ordering::Equal
4443 }
4444 }) {
4445 Ok(ix) => ix,
4446 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4447 }
4448 }
4449
4450 pub fn bottom_item(&self) -> usize {
4452 let state = self.0.borrow();
4453 crate::fast::layers::invalidate::note_offset_read(&state.version);
4454 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4455
4456 match state.child_bounds.binary_search_by(|bounds| {
4457 if bottom < bounds.top() {
4458 Ordering::Greater
4459 } else if bottom > bounds.bottom() {
4460 Ordering::Less
4461 } else {
4462 Ordering::Equal
4463 }
4464 }) {
4465 Ok(ix) => ix,
4466 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4467 }
4468 }
4469
4470 pub fn bounds(&self) -> Bounds<Pixels> {
4472 crate::fast::layers::input::moved(&self.0, Some(self.0.borrow().bounds)).unwrap_or_default()
4473 }
4474
4475 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4477 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
4478 crate::fast::layers::input::moved(&self.0, self.0.borrow().child_bounds.get(ix).cloned())
4479 }
4480
4481 pub fn scroll_to_item(&self, ix: usize) {
4483 let mut state = self.0.borrow_mut();
4484 crate::fast::dependencies::StateVersion::bump(&state.version);
4485 state.active_item = Some(ScrollActiveItem {
4486 index: ix,
4487 strategy: ScrollStrategy::default(),
4488 });
4489 }
4490
4491 pub fn scroll_to_top_of_item(&self, ix: usize) {
4494 let mut state = self.0.borrow_mut();
4495 crate::fast::dependencies::StateVersion::bump(&state.version);
4496 state.active_item = Some(ScrollActiveItem {
4497 index: ix,
4498 strategy: ScrollStrategy::Top,
4499 });
4500 }
4501
4502 fn scroll_to_active_item(&self) {
4506 let mut state = self.0.borrow_mut();
4507
4508 let Some(active_item) = state.active_item else {
4509 return;
4510 };
4511
4512 let active_item = match state.child_bounds.get(active_item.index) {
4513 Some(bounds) => {
4514 let mut scroll_offset = state.offset.borrow_mut();
4515
4516 match active_item.strategy {
4517 ScrollStrategy::FirstVisible => {
4518 if state.overflow.y == Overflow::Scroll {
4519 let child_height = bounds.size.height;
4520 let viewport_height = state.bounds.size.height;
4521 if child_height > viewport_height {
4522 scroll_offset.y = state.bounds.top() - bounds.top();
4523 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4524 scroll_offset.y = state.bounds.top() - bounds.top();
4525 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4526 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4527 }
4528 }
4529 }
4530 ScrollStrategy::Top => {
4531 scroll_offset.y = state.bounds.top() - bounds.top();
4532 }
4533 }
4534
4535 if state.overflow.x == Overflow::Scroll {
4536 let child_width = bounds.size.width;
4537 let viewport_width = state.bounds.size.width;
4538 if child_width > viewport_width {
4539 scroll_offset.x = state.bounds.left() - bounds.left();
4540 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4541 scroll_offset.x = state.bounds.left() - bounds.left();
4542 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4543 scroll_offset.x = state.bounds.right() - bounds.right();
4544 }
4545 }
4546 None
4547 }
4548 None => Some(active_item),
4549 };
4550 state.active_item = active_item;
4551 }
4552
4553 pub fn scroll_to_bottom(&self) {
4555 let mut state = self.0.borrow_mut();
4556 crate::fast::layers::scroll_to_bottom::note_scroll_to_bottom(self, &state);
4557 state.scroll_to_bottom = true;
4558 }
4559
4560 pub fn set_offset(&self, position: Point<Pixels>) {
4564 let state = self.0.borrow();
4565 crate::fast::layers::invalidate::offset_set(
4566 &state.version,
4567 *state.offset.borrow() != position,
4568 );
4569 *state.offset.borrow_mut() = position;
4570 }
4571
4572 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4574 let ix = self.top_item();
4575 let state = self.0.borrow();
4576
4577 if let Some(child_bounds) = state.child_bounds.get(ix) {
4578 (
4579 ix,
4580 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4581 )
4582 } else {
4583 (ix, px(0.))
4584 }
4585 }
4586
4587 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4589 let ix = self.bottom_item();
4590 let state = self.0.borrow();
4591
4592 if let Some(child_bounds) = state.child_bounds.get(ix) {
4593 (
4594 ix,
4595 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4596 )
4597 } else {
4598 (ix, px(0.))
4599 }
4600 }
4601
4602 pub fn children_count(&self) -> usize {
4604 self.0.borrow().child_bounds.len()
4605 }
4606}
4607
4608#[cfg(test)]
4609mod tests {
4610 use super::*;
4611 use crate::{
4612 AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, IntoElement,
4613 Keystroke, MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas,
4614 util::FluentBuilder as _,
4615 };
4616 use std::{cell::Cell, rc::Weak};
4617
4618 struct GroupHoverTestView {
4619 render_count: Rc<Cell<usize>>,
4620 anonymous_paint_count: Rc<Cell<usize>>,
4621 stateful_width: Rc<Cell<Pixels>>,
4622 }
4623
4624 impl Render for GroupHoverTestView {
4625 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4626 self.render_count.set(self.render_count.get() + 1);
4627 let anonymous_paint_count = self.anonymous_paint_count.clone();
4628 let stateful_width = self.stateful_width.clone();
4629 div().size_full().child(
4630 div()
4631 .ml(px(20.))
4632 .mt(px(20.))
4633 .size(px(50.))
4634 .relative()
4635 .group("hover-group")
4636 .child(
4637 div()
4638 .absolute()
4639 .size_full()
4640 .invisible()
4641 .group_hover("hover-group", |style| style.visible())
4642 .child(canvas(
4643 |_, _, _| {},
4644 move |_, _, _, _| {
4645 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4646 },
4647 )),
4648 )
4649 .child(
4650 div()
4651 .id("stateful-group-hover-target")
4652 .absolute()
4653 .top_0()
4654 .left_0()
4655 .size(px(10.))
4656 .group_hover("hover-group", |style| style.size(px(20.)))
4657 .child(canvas(
4658 move |bounds, _, _| stateful_width.set(bounds.size.width),
4659 |_, _, _, _| {},
4660 )),
4661 ),
4662 )
4663 }
4664 }
4665
4666 #[gpui::test]
4667 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4668 let render_count = Rc::new(Cell::new(0));
4669 let anonymous_paint_count = Rc::new(Cell::new(0));
4670 let stateful_width = Rc::new(Cell::new(px(0.)));
4671 let window = cx.add_window({
4672 let render_count = render_count.clone();
4673 let anonymous_paint_count = anonymous_paint_count.clone();
4674 let stateful_width = stateful_width.clone();
4675 move |_, _| GroupHoverTestView {
4676 render_count,
4677 anonymous_paint_count,
4678 stateful_width,
4679 }
4680 });
4681 let window = AnyWindowHandle::from(window);
4682
4683 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4684 .unwrap();
4685 assert_eq!(anonymous_paint_count.get(), 0);
4686 assert_eq!(stateful_width.get(), px(10.));
4687
4688 let move_mouse = |cx: &mut TestAppContext, position| {
4689 cx.update_window(window, |_, window, cx| {
4690 window.simulate_mouse_move(position, cx)
4691 })
4692 .unwrap();
4693 };
4694
4695 let initial_render_count = render_count.get();
4696 move_mouse(cx, point(px(25.), px(25.)));
4697 assert_eq!(render_count.get(), initial_render_count + 1);
4698 assert_eq!(anonymous_paint_count.get(), 1);
4699 assert_eq!(stateful_width.get(), px(20.));
4700
4701 move_mouse(cx, point(px(30.), px(30.)));
4702 assert_eq!(render_count.get(), initial_render_count + 1);
4703 assert_eq!(anonymous_paint_count.get(), 1);
4704 assert_eq!(stateful_width.get(), px(20.));
4705
4706 move_mouse(cx, point(px(5.), px(5.)));
4707 assert_eq!(render_count.get(), initial_render_count + 2);
4708 assert_eq!(anonymous_paint_count.get(), 1);
4709 assert_eq!(stateful_width.get(), px(10.));
4710
4711 move_mouse(cx, point(px(10.), px(10.)));
4712 assert_eq!(render_count.get(), initial_render_count + 2);
4713 assert_eq!(anonymous_paint_count.get(), 1);
4714 assert_eq!(stateful_width.get(), px(10.));
4715 }
4716
4717 struct HoverListenerLayoutTestView {
4718 target_left: Pixels,
4719 hover_transitions: Rc<RefCell<Vec<bool>>>,
4720 }
4721
4722 impl Render for HoverListenerLayoutTestView {
4723 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4724 let hover_transitions = self.hover_transitions.clone();
4725 div().relative().size_full().child(
4726 div()
4727 .id("hover-target")
4728 .absolute()
4729 .left(self.target_left)
4730 .top_0()
4731 .size(px(20.))
4732 .on_click(|_, _, _| {})
4733 .on_hover(move |is_hovered, _, _| {
4734 hover_transitions.borrow_mut().push(*is_hovered);
4735 }),
4736 )
4737 }
4738 }
4739
4740 #[gpui::test]
4741 fn default_hover_listener_updates_when_layout_changes_under_stationary_mouse(
4742 cx: &mut TestAppContext,
4743 ) {
4744 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4745 let window = cx.add_window({
4746 let hover_transitions = hover_transitions.clone();
4747 move |_, _| HoverListenerLayoutTestView {
4748 target_left: px(40.),
4749 hover_transitions,
4750 }
4751 });
4752 let any_window = AnyWindowHandle::from(window);
4753
4754 cx.update_window(any_window, |_, window, cx| {
4755 window.draw(cx).clear(cx);
4756 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4757 })
4758 .unwrap();
4759 assert!(hover_transitions.borrow().is_empty());
4760
4761 window
4762 .update(cx, |view, _, cx| {
4763 view.target_left = px(0.);
4764 cx.notify();
4765 })
4766 .unwrap();
4767 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4768 .unwrap();
4769 assert_eq!(*hover_transitions.borrow(), [true]);
4770
4771 window
4772 .update(cx, |view, _, cx| {
4773 view.target_left = px(40.);
4774 cx.notify();
4775 })
4776 .unwrap();
4777 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4778 .unwrap();
4779 assert_eq!(*hover_transitions.borrow(), [true, false]);
4780 }
4781
4782 #[gpui::test]
4783 fn default_hover_listener_ends_after_key_press(cx: &mut TestAppContext) {
4784 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4785 let window = cx.add_window({
4786 let hover_transitions = hover_transitions.clone();
4787 move |_, _| HoverListenerLayoutTestView {
4788 target_left: px(0.),
4789 hover_transitions,
4790 }
4791 });
4792 let any_window = AnyWindowHandle::from(window);
4793
4794 cx.update_window(any_window, |_, window, cx| {
4795 window.draw(cx).clear(cx);
4796 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4797 })
4798 .unwrap();
4799 assert_eq!(*hover_transitions.borrow(), [true]);
4800
4801 key_down(cx, any_window, "a");
4802 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4803 .unwrap();
4804 assert_eq!(*hover_transitions.borrow(), [true, false]);
4805 }
4806
4807 struct HoverListenerModeLayoutTestView {
4808 target_left: Pixels,
4809 hover_transitions: Rc<RefCell<Vec<bool>>>,
4810 }
4811
4812 impl Render for HoverListenerModeLayoutTestView {
4813 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4814 let hover_transitions = self.hover_transitions.clone();
4815 div().relative().size_full().child(
4816 div()
4817 .id("hover-target")
4818 .absolute()
4819 .left(self.target_left)
4820 .top_0()
4821 .size(px(20.))
4822 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
4823 .on_hover(move |is_hovered, _, _| {
4824 hover_transitions.borrow_mut().push(*is_hovered);
4825 }),
4826 )
4827 }
4828 }
4829
4830 #[gpui::test]
4831 fn input_modality_independent_hover_listener_updates_after_key_press(cx: &mut TestAppContext) {
4832 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4833 let window = cx.add_window({
4834 let hover_transitions = hover_transitions.clone();
4835 move |_, _| HoverListenerModeLayoutTestView {
4836 target_left: px(40.),
4837 hover_transitions,
4838 }
4839 });
4840 let any_window = AnyWindowHandle::from(window);
4841 let pointer_position = point(px(10.), px(10.));
4842
4843 cx.update_window(any_window, |_, window, cx| {
4844 window.draw(cx).clear(cx);
4845 window.simulate_mouse_move(pointer_position, cx);
4846 })
4847 .unwrap();
4848 assert!(hover_transitions.borrow().is_empty());
4849
4850 key_down(cx, any_window, "a");
4851 window
4852 .update(cx, |view, _, cx| {
4853 view.target_left = px(0.);
4854 cx.notify();
4855 })
4856 .unwrap();
4857 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4858 .unwrap();
4859 assert_eq!(*hover_transitions.borrow(), [true]);
4860
4861 key_down(cx, any_window, "b");
4862 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4863 .unwrap();
4864 assert_eq!(*hover_transitions.borrow(), [true]);
4865
4866 cx.update_window(any_window, |_, window, cx| {
4867 window.simulate_mouse_move(point(px(30.), px(10.)), cx);
4868 })
4869 .unwrap();
4870 assert_eq!(*hover_transitions.borrow(), [true, false]);
4871
4872 cx.update_window(any_window, |_, window, cx| {
4873 window.simulate_mouse_move(pointer_position, cx);
4874 window.dispatch_event(
4875 MouseExitEvent {
4876 position: pointer_position,
4877 ..Default::default()
4878 }
4879 .to_platform_input(),
4880 cx,
4881 );
4882 })
4883 .unwrap();
4884 assert_eq!(*hover_transitions.borrow(), [true, false, true, false]);
4885 }
4886
4887 #[gpui::test]
4888 fn default_hover_listener_remains_hovered_during_stationary_mouse_press(
4889 cx: &mut TestAppContext,
4890 ) {
4891 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4892 let window = cx.add_window({
4893 let hover_transitions = hover_transitions.clone();
4894 move |_, _| HoverListenerLayoutTestView {
4895 target_left: px(0.),
4896 hover_transitions,
4897 }
4898 });
4899 let any_window = AnyWindowHandle::from(window);
4900 let mouse_position = point(px(10.), px(10.));
4901
4902 cx.update_window(any_window, |_, window, cx| {
4903 window.draw(cx).clear(cx);
4904 window.simulate_mouse_move(mouse_position, cx);
4905 })
4906 .unwrap();
4907 assert_eq!(*hover_transitions.borrow(), [true]);
4908
4909 cx.update_window(any_window, |_, window, cx| {
4910 window.dispatch_event(
4911 MouseDownEvent {
4912 position: mouse_position,
4913 button: MouseButton::Left,
4914 modifiers: Default::default(),
4915 click_count: 1,
4916 first_mouse: false,
4917 }
4918 .to_platform_input(),
4919 cx,
4920 );
4921 window.draw(cx).clear(cx);
4922 })
4923 .unwrap();
4924 assert_eq!(*hover_transitions.borrow(), [true]);
4925
4926 cx.update_window(any_window, |_, window, cx| {
4927 window.dispatch_event(
4928 MouseUpEvent {
4929 position: mouse_position,
4930 button: MouseButton::Left,
4931 modifiers: Default::default(),
4932 click_count: 1,
4933 }
4934 .to_platform_input(),
4935 cx,
4936 );
4937 window.draw(cx).clear(cx);
4938 })
4939 .unwrap();
4940 assert_eq!(*hover_transitions.borrow(), [true]);
4941 }
4942
4943 struct TestTooltipView;
4944
4945 impl Render for TestTooltipView {
4946 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4947 div().w(px(20.)).h(px(20.)).child("tooltip")
4948 }
4949 }
4950
4951 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4952
4953 struct TooltipCaptureElement {
4954 child: AnyElement,
4955 captured_active_tooltip: CapturedActiveTooltip,
4956 }
4957
4958 impl Element for TooltipCaptureElement {
4959 type RequestLayoutState = ();
4960 type PrepaintState = ();
4961
4962 fn id(&self) -> Option<ElementId> {
4963 None
4964 }
4965
4966 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4967 None
4968 }
4969
4970 fn request_layout(
4971 &mut self,
4972 _id: Option<&GlobalElementId>,
4973 _inspector_id: Option<&InspectorElementId>,
4974 window: &mut Window,
4975 cx: &mut App,
4976 ) -> (LayoutId, Self::RequestLayoutState) {
4977 (self.child.request_layout(window, cx), ())
4978 }
4979
4980 fn prepaint(
4981 &mut self,
4982 _id: Option<&GlobalElementId>,
4983 _inspector_id: Option<&InspectorElementId>,
4984 _bounds: Bounds<Pixels>,
4985 _request_layout: &mut Self::RequestLayoutState,
4986 window: &mut Window,
4987 cx: &mut App,
4988 ) -> Self::PrepaintState {
4989 self.child.prepaint(window, cx);
4990 }
4991
4992 fn paint(
4993 &mut self,
4994 _id: Option<&GlobalElementId>,
4995 _inspector_id: Option<&InspectorElementId>,
4996 _bounds: Bounds<Pixels>,
4997 _request_layout: &mut Self::RequestLayoutState,
4998 _prepaint: &mut Self::PrepaintState,
4999 window: &mut Window,
5000 cx: &mut App,
5001 ) {
5002 self.child.paint(window, cx);
5003 window.with_global_id("target".into(), |global_id, window| {
5004 window.with_element_state::<InteractiveElementState, _>(
5005 global_id,
5006 |state, _window| {
5007 let state = state.unwrap();
5008 *self.captured_active_tooltip.borrow_mut() =
5009 state.active_tooltip.as_ref().map(Rc::downgrade);
5010 ((), state)
5011 },
5012 )
5013 });
5014 }
5015 }
5016
5017 struct TooltipOwner {
5018 captured_active_tooltip: CapturedActiveTooltip,
5019 show_delay_override: Option<Duration>,
5020 }
5021
5022 impl Render for TooltipOwner {
5023 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5024 TooltipCaptureElement {
5025 child: div()
5026 .size_full()
5027 .child(
5028 div()
5029 .id("target")
5030 .w(px(50.))
5031 .h(px(50.))
5032 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
5033 .when_some(self.show_delay_override, |this, delay| {
5034 this.tooltip_show_delay(delay)
5035 }),
5036 )
5037 .into_any_element(),
5038 captured_active_tooltip: self.captured_active_tooltip.clone(),
5039 }
5040 }
5041 }
5042
5043 #[test]
5044 fn scroll_handle_aligns_wide_children_to_left_edge() {
5045 let handle = ScrollHandle::new();
5046 {
5047 let mut state = handle.0.borrow_mut();
5048 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
5049 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
5050 state.overflow.x = Overflow::Scroll;
5051 state.active_item = Some(ScrollActiveItem {
5052 index: 0,
5053 strategy: ScrollStrategy::default(),
5054 });
5055 }
5056
5057 handle.scroll_to_active_item();
5058
5059 assert_eq!(handle.offset().x, px(-25.));
5060 }
5061
5062 #[test]
5063 fn scroll_handle_aligns_tall_children_to_top_edge() {
5064 let handle = ScrollHandle::new();
5065 {
5066 let mut state = handle.0.borrow_mut();
5067 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
5068 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
5069 state.overflow.y = Overflow::Scroll;
5070 state.active_item = Some(ScrollActiveItem {
5071 index: 0,
5072 strategy: ScrollStrategy::default(),
5073 });
5074 }
5075
5076 handle.scroll_to_active_item();
5077
5078 assert_eq!(handle.offset().y, px(-25.));
5079 }
5080
5081 #[test]
5082 fn long_press_shows_tooltip_until_touch_ends() {
5083 let (mut test_app, any_window, captured_active_tooltip) = create_tooltip_owner_test(None);
5084 let active_tooltip = captured_active_tooltip
5085 .borrow()
5086 .clone()
5087 .unwrap()
5088 .upgrade()
5089 .unwrap();
5090 let touch_id = TouchId(1);
5091 let touch_position = point(px(49.), px(10.));
5092
5093 test_app
5094 .update_window(any_window, |_, window, cx| {
5095 window.dispatch_event(
5096 TouchEvent {
5097 id: touch_id,
5098 phase: TouchPhase::Started,
5099 position: touch_position,
5100 predicted_position: None,
5101 force: None,
5102 }
5103 .to_platform_input(),
5104 cx,
5105 );
5106 })
5107 .unwrap();
5108 test_app
5109 .dispatcher
5110 .advance_clock(GestureTuning::default().long_press_duration + Duration::from_millis(1));
5111 test_app.run_until_parked();
5112
5113 assert!(matches!(
5114 active_tooltip.borrow().as_ref(),
5115 Some(ActiveTooltip::Visible { .. })
5116 ));
5117
5118 let moved_position = point(px(55.), px(10.));
5119 test_app
5120 .update_window(any_window, |_, window, cx| {
5121 window.dispatch_event(
5122 TouchEvent {
5123 id: touch_id,
5124 phase: TouchPhase::Moved,
5125 position: moved_position,
5126 predicted_position: None,
5127 force: None,
5128 }
5129 .to_platform_input(),
5130 cx,
5131 );
5132 window.draw(cx).clear(cx);
5133 })
5134 .unwrap();
5135 assert!(matches!(
5136 active_tooltip.borrow().as_ref(),
5137 Some(ActiveTooltip::Visible { .. })
5138 ));
5139
5140 test_app
5141 .update_window(any_window, |_, window, cx| {
5142 window.dispatch_event(
5143 TouchEvent {
5144 id: touch_id,
5145 phase: TouchPhase::Ended,
5146 position: moved_position,
5147 predicted_position: None,
5148 force: None,
5149 }
5150 .to_platform_input(),
5151 cx,
5152 );
5153 })
5154 .unwrap();
5155
5156 assert!(active_tooltip.borrow().is_none());
5157 }
5158
5159 fn setup_tooltip_owner_test(
5160 show_delay_override: Option<Duration>,
5161 ) -> (
5162 TestAppContext,
5163 crate::AnyWindowHandle,
5164 CapturedActiveTooltip,
5165 ) {
5166 let (mut test_app, any_window, captured_active_tooltip) =
5167 create_tooltip_owner_test(show_delay_override);
5168
5169 test_app
5170 .update_window(any_window, |_, window, cx| {
5171 window.dispatch_event(
5172 MouseMoveEvent {
5173 position: point(px(10.), px(10.)),
5174 modifiers: Default::default(),
5175 pressed_button: None,
5176 }
5177 .to_platform_input(),
5178 cx,
5179 );
5180 })
5181 .unwrap();
5182
5183 test_app
5184 .update_window(any_window, |_, window, cx| {
5185 window.draw(cx).clear(cx);
5186 })
5187 .unwrap();
5188
5189 (test_app, any_window, captured_active_tooltip)
5190 }
5191
5192 fn create_tooltip_owner_test(
5193 show_delay_override: Option<Duration>,
5194 ) -> (
5195 TestAppContext,
5196 crate::AnyWindowHandle,
5197 CapturedActiveTooltip,
5198 ) {
5199 let mut test_app = TestAppContext::single();
5200 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
5201 let window = test_app.add_window({
5202 let captured_active_tooltip = captured_active_tooltip.clone();
5203 move |_, _| TooltipOwner {
5204 captured_active_tooltip,
5205 show_delay_override,
5206 }
5207 });
5208 let any_window = window.into();
5209
5210 test_app
5211 .update_window(any_window, |_, window, cx| {
5212 window.draw(cx).clear(cx);
5213 })
5214 .unwrap();
5215
5216 (test_app, any_window, captured_active_tooltip)
5217 }
5218
5219 #[test]
5220 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
5221 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5222
5223 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5224 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5225 assert!(matches!(
5226 active_tooltip.borrow().as_ref(),
5227 Some(ActiveTooltip::WaitingForShow { .. })
5228 ));
5229
5230 test_app
5231 .update_window(any_window, |_, window, _| {
5232 window.remove_window();
5233 })
5234 .unwrap();
5235 test_app.run_until_parked();
5236 drop(active_tooltip);
5237
5238 assert!(weak_active_tooltip.upgrade().is_none());
5239 }
5240
5241 #[test]
5242 fn tooltip_respects_custom_show_delay() {
5243 let extra_delay = Duration::from_secs(1);
5244 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
5245 let (test_app, _any_window, captured_active_tooltip) =
5246 setup_tooltip_owner_test(Some(show_delay_override));
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::WaitingForShow { .. })
5259 ));
5260
5261 test_app.dispatcher.advance_clock(extra_delay);
5262 test_app.run_until_parked();
5263
5264 assert!(matches!(
5265 active_tooltip.borrow().as_ref(),
5266 Some(ActiveTooltip::Visible { .. })
5267 ));
5268 }
5269
5270 #[test]
5271 fn tooltip_is_released_when_its_owner_disappears() {
5272 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5273
5274 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5275 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5276
5277 test_app
5278 .dispatcher
5279 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5280 test_app.run_until_parked();
5281
5282 assert!(matches!(
5283 active_tooltip.borrow().as_ref(),
5284 Some(ActiveTooltip::Visible { .. })
5285 ));
5286
5287 test_app
5288 .update_window(any_window, |_, window, _| {
5289 window.remove_window();
5290 })
5291 .unwrap();
5292 test_app.run_until_parked();
5293 drop(active_tooltip);
5294
5295 assert!(weak_active_tooltip.upgrade().is_none());
5296 }
5297
5298 #[test]
5299 fn tooltip_hides_after_mouse_leaves_origin() {
5300 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5301
5302 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5303 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5304
5305 test_app
5306 .dispatcher
5307 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5308 test_app.run_until_parked();
5309
5310 assert!(matches!(
5311 active_tooltip.borrow().as_ref(),
5312 Some(ActiveTooltip::Visible { .. })
5313 ));
5314
5315 test_app
5316 .update_window(any_window, |_, window, cx| {
5317 window.dispatch_event(
5318 MouseMoveEvent {
5319 position: point(px(75.), px(75.)),
5320 modifiers: Default::default(),
5321 pressed_button: None,
5322 }
5323 .to_platform_input(),
5324 cx,
5325 );
5326 })
5327 .unwrap();
5328
5329 assert!(active_tooltip.borrow().is_none());
5330 }
5331
5332 struct MouseDownOutOwner {
5333 mouse_down_out_count: Rc<RefCell<usize>>,
5334 }
5335
5336 impl Render for MouseDownOutOwner {
5337 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5338 let mouse_down_out_count = self.mouse_down_out_count.clone();
5339 div()
5340 .size_full()
5341 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
5342 move |_, _, _| {
5343 *mouse_down_out_count.borrow_mut() += 1;
5344 },
5345 ))
5346 }
5347 }
5348
5349 #[test]
5350 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
5351 let mut test_app = TestAppContext::single();
5352 let mouse_down_out_count = Rc::new(RefCell::new(0));
5353 let window = test_app.add_window({
5354 let mouse_down_out_count = mouse_down_out_count.clone();
5355 move |_, _| MouseDownOutOwner {
5356 mouse_down_out_count,
5357 }
5358 });
5359 let any_window: AnyWindowHandle = window.into();
5360
5361 fn dispatch_mouse_down_outside_target(
5362 test_app: &mut TestAppContext,
5363 any_window: AnyWindowHandle,
5364 ) {
5365 test_app
5366 .update_window(any_window, |_, window, cx| {
5367 window.dispatch_event(
5368 MouseDownEvent {
5369 position: point(px(75.), px(75.)),
5370 button: MouseButton::Left,
5371 modifiers: Default::default(),
5372 click_count: 1,
5373 first_mouse: false,
5374 }
5375 .to_platform_input(),
5376 cx,
5377 );
5378 })
5379 .unwrap();
5380 }
5381
5382 test_app
5383 .update_window(any_window, |_, window, cx| {
5384 window.draw(cx).clear(cx);
5385 })
5386 .unwrap();
5387
5388 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5389 assert_eq!(
5390 *mouse_down_out_count.borrow(),
5391 1,
5392 "mouse down outside the element should fire mouse-down-out listeners"
5393 );
5394
5395 test_app
5396 .update_window(any_window, |_, window, cx| {
5397 cx.set_prompt_builder(crate::fallback_prompt_renderer);
5398 let _receiver =
5399 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
5400 assert!(window.has_active_prompt());
5401 window.draw(cx).clear(cx);
5402 })
5403 .unwrap();
5404
5405 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5406 assert_eq!(
5407 *mouse_down_out_count.borrow(),
5408 1,
5409 "mouse down over an active prompt should not fire mouse-down-out listeners"
5410 );
5411 }
5412
5413 #[test]
5414 fn touch_tap_out_fires_once_after_release() {
5415 let mut test_app = TestAppContext::single();
5416 let mouse_down_out_count = Rc::new(RefCell::new(0));
5417 let window = test_app.add_window({
5418 let mouse_down_out_count = mouse_down_out_count.clone();
5419 move |_, _| MouseDownOutOwner {
5420 mouse_down_out_count,
5421 }
5422 });
5423 let any_window: AnyWindowHandle = window.into();
5424
5425 test_app
5426 .update_window(any_window, |_, window, cx| {
5427 window.draw(cx).clear(cx);
5428 let started = TouchEvent {
5429 id: TouchId(1),
5430 phase: TouchPhase::Started,
5431 position: point(px(75.), px(75.)),
5432 force: None,
5433 predicted_position: None,
5434 };
5435 window.dispatch_event(started.clone().to_platform_input(), cx);
5436 assert_eq!(*mouse_down_out_count.borrow(), 0);
5437 window.dispatch_event(
5438 TouchEvent {
5439 phase: TouchPhase::Ended,
5440 ..started
5441 }
5442 .to_platform_input(),
5443 cx,
5444 );
5445 })
5446 .unwrap();
5447
5448 assert_eq!(
5449 *mouse_down_out_count.borrow(),
5450 1,
5451 "a touch tap outside the element should use mouse-down-out listeners"
5452 );
5453 }
5454
5455 #[crate::test]
5456 fn touch_pan_and_cancel_do_not_fire_mouse_down_out(cx: &mut TestAppContext) {
5457 let mouse_down_out_count = Rc::new(RefCell::new(0));
5458 let window = cx.add_window({
5459 let mouse_down_out_count = mouse_down_out_count.clone();
5460 move |_, _| MouseDownOutOwner {
5461 mouse_down_out_count,
5462 }
5463 });
5464 cx.update_window(window.into(), |_, window, cx| {
5465 window.draw(cx).clear(cx);
5466 for (id, samples) in [
5467 (
5468 TouchId(1),
5469 [
5470 (TouchPhase::Started, 100.),
5471 (TouchPhase::Moved, 75.),
5472 (TouchPhase::Ended, 75.),
5473 ],
5474 ),
5475 (
5476 TouchId(2),
5477 [
5478 (TouchPhase::Started, 100.),
5479 (TouchPhase::Moved, 100.),
5480 (TouchPhase::Cancelled, 100.),
5481 ],
5482 ),
5483 ] {
5484 for (phase, vertical_position) in samples {
5485 window.dispatch_event(
5486 TouchEvent {
5487 id,
5488 phase,
5489 position: point(px(75.), px(vertical_position)),
5490 predicted_position: None,
5491 force: None,
5492 }
5493 .to_platform_input(),
5494 cx,
5495 );
5496 }
5497 }
5498 })
5499 .unwrap();
5500 assert_eq!(*mouse_down_out_count.borrow(), 0);
5501 }
5502
5503 #[test]
5504 fn test_accessibility_id_builder_writes_author_id() {
5505 let mut element = div()
5506 .id("buffer-font-size")
5507 .accessibility_id("settings.buffer-font-size");
5508 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5509
5510 element.interactivity().write_a11y_info(&mut node);
5511
5512 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5513 }
5514
5515 #[test]
5516 fn test_write_a11y_info_string_and_numeric_properties() {
5517 let mut interactivity = Interactivity::default();
5518 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
5519 interactivity.aria.label = Some("Buffer Font Size".into());
5520 interactivity.aria.value = Some("15".into());
5521 interactivity.aria.placeholder = Some("Search".into());
5522 interactivity.aria.numeric_value = Some(15.0);
5523 interactivity.aria.min_numeric_value = Some(6.0);
5524 interactivity.aria.max_numeric_value = Some(72.0);
5525 interactivity.aria.numeric_value_step = Some(1.0);
5526
5527 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5528 interactivity.write_a11y_info(&mut node);
5529
5530 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5531 assert_eq!(node.label(), Some("Buffer Font Size"));
5532 assert_eq!(node.value(), Some("15"));
5533 assert_eq!(node.placeholder(), Some("Search"));
5534 assert_eq!(node.numeric_value(), Some(15.0));
5535 assert_eq!(node.min_numeric_value(), Some(6.0));
5536 assert_eq!(node.max_numeric_value(), Some(72.0));
5537 assert_eq!(node.numeric_value_step(), Some(1.0));
5538 }
5539
5540 struct KeyboardActivationTest {
5543 focus_a: FocusHandle,
5544 focus_b: FocusHandle,
5545 clicks: Rc<RefCell<Vec<&'static str>>>,
5546 }
5547
5548 impl Render for KeyboardActivationTest {
5549 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5550 let clicks_a = self.clicks.clone();
5551 let clicks_b = self.clicks.clone();
5552 div()
5553 .size_full()
5554 .child(
5555 div()
5556 .id("a")
5557 .w(px(50.))
5558 .h(px(50.))
5559 .track_focus(&self.focus_a)
5560 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
5561 )
5562 .child(
5563 div()
5564 .id("b")
5565 .w(px(50.))
5566 .h(px(50.))
5567 .track_focus(&self.focus_b)
5568 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
5569 )
5570 }
5571 }
5572
5573 fn setup_keyboard_activation_test() -> (
5574 TestAppContext,
5575 AnyWindowHandle,
5576 Rc<RefCell<Vec<&'static str>>>,
5577 FocusHandle,
5578 FocusHandle,
5579 ) {
5580 let mut cx = TestAppContext::single();
5581 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
5582 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
5583 let window = cx.add_window({
5584 let focus_a = focus_a.clone();
5585 let focus_b = focus_b.clone();
5586 let clicks = clicks.clone();
5587 move |_, _| KeyboardActivationTest {
5588 focus_a,
5589 focus_b,
5590 clicks,
5591 }
5592 });
5593 (cx, window.into(), clicks, focus_a, focus_b)
5594 }
5595
5596 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
5599 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
5600 .unwrap();
5601 cx.run_until_parked();
5602 cx.update_window(window, |_, window, cx| {
5603 window.draw(cx).clear(cx);
5604 })
5605 .unwrap();
5606 }
5607
5608 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5609 let os = cx.read(|cx| cx.platform_info().os);
5610 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5611 cx.update_window(window, |_, window, cx| {
5612 window.dispatch_event(
5613 KeyDownEvent {
5614 keystroke,
5615 is_held: false,
5616 prefer_character_input: false,
5617 }
5618 .to_platform_input(),
5619 cx,
5620 );
5621 })
5622 .unwrap();
5623 }
5624
5625 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5626 let os = cx.read(|cx| cx.platform_info().os);
5627 let keystroke = Keystroke::parse_with_os(key, os).unwrap();
5628 cx.update_window(window, |_, window, cx| {
5629 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
5630 })
5631 .unwrap();
5632 }
5633
5634 #[test]
5636 fn keyboard_activation_fires_click_on_same_element() {
5637 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5638
5639 focus_and_draw(&mut cx, window, &focus_a);
5640 key_down(&mut cx, window, "enter");
5641 key_up(&mut cx, window, "enter");
5642
5643 assert_eq!(*clicks.borrow(), vec!["a"]);
5644 }
5645
5646 #[test]
5651 fn keyboard_activation_does_not_leak_across_focus_change() {
5652 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5653
5654 focus_and_draw(&mut cx, window, &focus_a);
5656 key_down(&mut cx, window, "enter");
5657
5658 focus_and_draw(&mut cx, window, &focus_b);
5660 key_up(&mut cx, window, "enter");
5661
5662 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5665 }
5666
5667 #[test]
5672 fn keyboard_activation_does_not_leak_when_focus_returns() {
5673 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5674
5675 focus_and_draw(&mut cx, window, &focus_a);
5677 key_down(&mut cx, window, "enter");
5678
5679 focus_and_draw(&mut cx, window, &focus_b);
5682 focus_and_draw(&mut cx, window, &focus_a);
5683 key_up(&mut cx, window, "enter");
5684
5685 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5687 }
5688
5689 #[test]
5694 fn keyboard_activation_cleared_by_intervening_key_release() {
5695 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5696
5697 focus_and_draw(&mut cx, window, &focus_a);
5698 key_down(&mut cx, window, "escape");
5699 key_down(&mut cx, window, "space");
5700 key_up(&mut cx, window, "escape");
5701 key_up(&mut cx, window, "space");
5702
5703 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5704 }
5705
5706 #[test]
5710 fn keyboard_activation_does_not_distinguish_space_and_enter() {
5711 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5712
5713 focus_and_draw(&mut cx, window, &focus_a);
5714 key_down(&mut cx, window, "space");
5715 key_up(&mut cx, window, "enter");
5716
5717 assert_eq!(*clicks.borrow(), vec!["a"]);
5718 }
5719
5720 #[test]
5723 fn keyboard_activation_cleared_by_intervening_keydown() {
5724 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5725
5726 focus_and_draw(&mut cx, window, &focus_a);
5727 key_down(&mut cx, window, "enter");
5728 key_down(&mut cx, window, "a");
5729 key_up(&mut cx, window, "enter");
5730
5731 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5732 }
5733
5734 #[test]
5737 fn keyboard_activation_ignores_modified_keys() {
5738 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5739
5740 focus_and_draw(&mut cx, window, &focus_a);
5741 key_down(&mut cx, window, "cmd-enter");
5742 key_up(&mut cx, window, "cmd-enter");
5743
5744 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5745 }
5746
5747 struct TabGroupFocus {
5751 group_a: FocusHandle,
5752 item_a: FocusHandle,
5753 group_b: FocusHandle,
5754 item_b: FocusHandle,
5755 }
5756
5757 impl Render for TabGroupFocus {
5758 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5759 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
5760 div()
5761 .track_focus(container)
5762 .tab_group()
5763 .child(div().track_focus(item))
5764 }
5765 div()
5766 .child(group(&self.group_a, &self.item_a))
5767 .child(group(&self.group_b, &self.item_b))
5768 }
5769 }
5770
5771 #[test]
5775 fn focus_next_from_tab_group_container_enters_that_group() {
5776 let mut cx = TestAppContext::single();
5777 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
5778 (
5779 cx.focus_handle(),
5780 cx.focus_handle().tab_stop(true),
5781 cx.focus_handle(),
5782 cx.focus_handle().tab_stop(true),
5783 )
5784 });
5785 let window: AnyWindowHandle = cx
5786 .add_window({
5787 let (group_a, item_a, group_b, item_b) =
5788 (group_a, item_a, group_b.clone(), item_b.clone());
5789 move |_, _| TabGroupFocus {
5790 group_a,
5791 item_a,
5792 group_b,
5793 item_b,
5794 }
5795 })
5796 .into();
5797 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5798 .unwrap();
5799
5800 let focused = cx
5802 .update_window(window, |_, window, cx| {
5803 window.focus(&group_b, cx);
5804 window.focus_next(cx);
5805 window.focused(cx).map(|handle| handle.id)
5806 })
5807 .unwrap();
5808
5809 assert_eq!(focused, Some(item_b.id));
5810 }
5811
5812 #[gpui::test]
5813 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5814 cx: &mut TestAppContext,
5815 ) {
5816 struct PaddedContainer {
5817 scroll_handle: ScrollHandle,
5818 }
5819
5820 impl Render for PaddedContainer {
5821 fn render(
5822 &mut self,
5823 _window: &mut Window,
5824 _cx: &mut Context<Self>,
5825 ) -> impl IntoElement {
5826 div().size_full().child(
5829 div()
5830 .id("container")
5831 .h(px(50.))
5832 .w(px(100.))
5833 .py(px(4.25))
5834 .overflow_y_scroll()
5835 .track_scroll(&self.scroll_handle)
5836 .child(div().w_full().h(px(42.))),
5837 )
5838 }
5839 }
5840
5841 let scroll_handle = ScrollHandle::new();
5842 let window: AnyWindowHandle = cx
5843 .add_window({
5844 let scroll_handle = scroll_handle.clone();
5845 move |_, _| PaddedContainer { scroll_handle }
5846 })
5847 .into();
5848 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5849 .unwrap();
5850
5851 assert_eq!(scroll_handle.max_offset().y, px(0.));
5852 }
5853
5854 struct ContentSizedGrid;
5855
5856 impl Render for ContentSizedGrid {
5857 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5858 let widths = [px(100.), px(200.), px(50.)];
5859 div().size_full().child(
5860 div()
5861 .w_full()
5862 .grid()
5863 .grid_cols_max_content(widths.len() as u16)
5864 .children(widths.into_iter().enumerate().map(|(index, width)| {
5865 div()
5866 .debug_selector(move || format!("cell-{index}"))
5867 .w(width)
5868 .h(px(10.))
5869 })),
5870 )
5871 }
5872 }
5873
5874 #[gpui::test]
5875 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
5876 let window = cx.add_window(|_, _| ContentSizedGrid);
5877 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
5878 .unwrap();
5879
5880 let mut bounds = |selector: &'static str| {
5881 cx.update_window(window.into(), |_, window, _| {
5882 window.rendered_frame.debug_bounds.get(selector).copied()
5883 })
5884 .unwrap()
5885 .unwrap_or_else(|| panic!("{selector} was not rendered"))
5886 };
5887
5888 assert_eq!(bounds("cell-0").origin.x, px(0.));
5889 assert_eq!(bounds("cell-1").origin.x, px(100.));
5890 assert_eq!(bounds("cell-2").origin.x, px(300.));
5891 }
5892}