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