1use crate::{
20 Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent, DispatchPhase,
21 Display, Element, ElementId, Entity, EntityId, ExternalDragPayload, ExternalDragPayloadSource,
22 FileDropEvent, FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, HitboxId,
23 InspectorElementId, IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, KeyboardButton,
24 KeyboardClickEvent, LayoutId, LongPressEvent, ModifiersChangedEvent, MouseButton,
25 MouseClickEvent, MouseDownEvent, MouseExitEvent, MouseMoveEvent, MousePressureEvent,
26 MouseUpEvent, OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels, Point, Render,
27 ScrollWheelEvent, SharedString, Size, Style, StyleRefinement, Styled, Task, TooltipId,
28 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_wheel(
392 &mut self,
393 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
394 ) {
395 self.scroll_wheel_listeners
396 .push(Box::new(move |event, phase, hitbox, window, cx| {
397 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
398 (listener)(event, window, cx);
399 }
400 }));
401 }
402
403 pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
407 self.pinch_listeners
408 .push(Box::new(move |event, phase, hitbox, window, cx| {
409 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
410 (listener)(event, window, cx);
411 }
412 }));
413 }
414
415 pub fn capture_pinch(
419 &mut self,
420 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
421 ) {
422 self.pinch_listeners
423 .push(Box::new(move |event, phase, _hitbox, window, cx| {
424 if phase == DispatchPhase::Capture {
425 (listener)(event, window, cx);
426 } else {
427 cx.propagate();
428 }
429 }));
430 }
431
432 pub fn capture_action<A: Action>(
437 &mut self,
438 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
439 ) {
440 self.action_listeners.push((
441 TypeId::of::<A>(),
442 Box::new(move |action, phase, window, cx| {
443 let action = action.downcast_ref().unwrap();
444 if phase == DispatchPhase::Capture {
445 (listener)(action, window, cx)
446 } else {
447 cx.propagate();
448 }
449 }),
450 ));
451 }
452
453 #[track_caller]
458 #[inline(always)]
459 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
460 self.action_listeners.push((
461 TypeId::of::<A>(),
462 Box::new(move |action, phase, window, cx| {
463 let action = action.downcast_ref().unwrap();
464 if phase == DispatchPhase::Bubble {
465 (listener)(action, window, cx)
466 }
467 }),
468 ));
469 }
470
471 pub fn on_boxed_action(
478 &mut self,
479 action: &dyn Action,
480 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
481 ) {
482 let action = action.boxed_clone();
483 self.action_listeners.push((
484 (*action).type_id(),
485 Box::new(move |_, phase, window, cx| {
486 if phase == DispatchPhase::Bubble {
487 (listener)(&*action, window, cx)
488 }
489 }),
490 ));
491 }
492
493 pub fn on_key_down(
498 &mut self,
499 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
500 ) {
501 self.key_down_listeners
502 .push(Box::new(move |event, phase, window, cx| {
503 if phase == DispatchPhase::Bubble {
504 (listener)(event, window, cx)
505 }
506 }));
507 }
508
509 pub fn capture_key_down(
514 &mut self,
515 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
516 ) {
517 self.key_down_listeners
518 .push(Box::new(move |event, phase, window, cx| {
519 if phase == DispatchPhase::Capture {
520 listener(event, window, cx)
521 }
522 }));
523 }
524
525 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
530 self.key_up_listeners
531 .push(Box::new(move |event, phase, window, cx| {
532 if phase == DispatchPhase::Bubble {
533 listener(event, window, cx)
534 }
535 }));
536 }
537
538 pub fn capture_key_up(
543 &mut self,
544 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
545 ) {
546 self.key_up_listeners
547 .push(Box::new(move |event, phase, window, cx| {
548 if phase == DispatchPhase::Capture {
549 listener(event, window, cx)
550 }
551 }));
552 }
553
554 pub fn on_modifiers_changed(
559 &mut self,
560 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
561 ) {
562 self.modifiers_changed_listeners.push(Box::new(listener));
563 }
564
565 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
570 self.drop_listeners.push((
571 TypeId::of::<T>(),
572 Box::new(move |dragged_value, window, cx| {
573 listener(dragged_value.downcast_ref().unwrap(), window, cx);
574 }),
575 ));
576 }
577
578 pub fn can_drop(
581 &mut self,
582 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
583 ) {
584 self.can_drop_predicate = crate::fast::interactivity::rare(Box::new(predicate));
585 }
586
587 #[inline(always)]
592 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
593 where
594 Self: Sized,
595 {
596 self.click_listeners.push(Rc::new(listener));
597 }
598
599 pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
604 where
605 Self: Sized,
606 {
607 self.aux_click_listeners.push(Rc::new(listener));
608 }
609
610 pub fn on_drag<T, W>(
617 &mut self,
618 value: T,
619 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
620 ) where
621 Self: Sized,
622 T: 'static,
623 W: 'static + Render,
624 {
625 debug_assert!(
626 self.drag_listener.is_none(),
627 "calling on_drag more than once on the same element is not supported"
628 );
629 self.drag_listener = crate::fast::interactivity::rare(DragListener {
630 value: Arc::new(value),
631 render: Box::new(move |value, offset, window, cx| {
632 constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
633 }),
634 external_payload: None,
635 });
636 }
637
638 pub fn external_drag_payload<T>(
643 &mut self,
644 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
645 ) where
646 Self: Sized,
647 T: 'static,
648 {
649 let Some(drag_listener) = self.drag_listener.as_mut() else {
650 debug_assert!(false, "external_drag_payload must be called after on_drag");
651 return;
652 };
653 debug_assert!(
654 drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
655 "external_drag_payload must use the same dragged value type as on_drag"
656 );
657 debug_assert!(
658 drag_listener.external_payload.is_none(),
659 "calling external_drag_payload more than once on the same element is not supported"
660 );
661 drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
662 resolver(value.downcast_ref::<T>()?, window, cx)
663 }));
664 }
665
666 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
677 where
678 Self: Sized,
679 {
680 debug_assert!(
681 self.hover_listener.is_none(),
682 "calling on_hover more than once on the same element is not supported"
683 );
684 self.hover_listener = crate::fast::interactivity::rare(Box::new(listener));
685 }
686
687 pub fn hover_listener_mode(&mut self, mode: HoverListenerMode)
691 where
692 Self: Sized,
693 {
694 self.hover_listener_mode = mode;
695 }
696
697 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
700 where
701 Self: Sized,
702 {
703 debug_assert!(
704 self.tooltip_builder.is_none(),
705 "calling tooltip more than once on the same element is not supported"
706 );
707 self.tooltip_builder = crate::fast::interactivity::rare(TooltipBuilder {
708 build: Rc::new(build_tooltip),
709 hoverable: false,
710 });
711 }
712
713 pub fn hoverable_tooltip(
717 &mut self,
718 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
719 ) where
720 Self: Sized,
721 {
722 debug_assert!(
723 self.tooltip_builder.is_none(),
724 "calling tooltip more than once on the same element is not supported"
725 );
726 self.tooltip_builder = crate::fast::interactivity::rare(TooltipBuilder {
727 build: Rc::new(build_tooltip),
728 hoverable: true,
729 });
730 }
731
732 pub fn tooltip_show_delay(&mut self, delay: Duration) {
737 self.tooltip_show_delay = Some(delay);
738 }
739
740 pub fn occlude_mouse(&mut self) {
745 self.hitbox_behavior = HitboxBehavior::BlockMouse;
746 }
747
748 pub fn window_control_area(&mut self, area: WindowControlArea) {
751 self.window_control = Some(area);
752 }
753
754 pub fn block_mouse_except_scroll(&mut self) {
759 self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
760 }
761
762 fn has_pinch_listeners(&self) -> bool {
763 !self.pinch_listeners.is_empty()
764 }
765}
766
767pub trait InteractiveElement: Sized {
770 fn interactivity(&mut self) -> &mut Interactivity;
772
773 fn group(mut self, group: impl Into<SharedString>) -> Self {
775 self.interactivity().group = Some(group.into());
776 self
777 }
778
779 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
781 self.interactivity().element_id = Some(id.into());
782
783 Stateful { element: self }
784 }
785
786 fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
790 self.interactivity().focusable = true;
791 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
792 self
793 }
794
795 fn tab_stop(mut self, tab_stop: bool) -> Self {
802 self.interactivity().tab_stop = tab_stop;
803 self
804 }
805
806 fn tab_index(mut self, index: isize) -> Self {
811 self.interactivity().focusable = true;
812 self.interactivity().tab_index = Some(index);
813 self.interactivity().tab_stop = true;
814 self
815 }
816
817 fn tab_group(mut self) -> Self {
822 self.interactivity().tab_group = true;
823 if self.interactivity().tab_index.is_none() {
824 self.interactivity().tab_index = Some(0);
825 }
826 self
827 }
828
829 fn key_context<C, E>(mut self, key_context: C) -> Self
832 where
833 C: TryInto<KeyContext, Error = E>,
834 E: std::fmt::Display,
835 {
836 if let Some(key_context) = key_context.try_into().log_err() {
837 self.interactivity().key_context = Some(key_context);
838 }
839 self
840 }
841
842 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
844 debug_assert!(
845 self.interactivity().hover_style.is_none(),
846 "hover style already set"
847 );
848 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
849 self
850 }
851
852 fn group_hover(
854 mut self,
855 group_name: impl Into<SharedString>,
856 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
857 ) -> Self {
858 self.interactivity().group_hover_style = crate::fast::interactivity::rare(GroupStyle {
859 group: group_name.into(),
860 style: Box::new(f(StyleRefinement::default())),
861 });
862 self
863 }
864
865 #[inline(always)]
870 fn on_mouse_down(
871 mut self,
872 button: MouseButton,
873 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
874 ) -> Self {
875 self.interactivity().on_mouse_down(button, listener);
876 self
877 }
878
879 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
886 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
887 self.interactivity().debug_selector = Some(f());
888 self
889 }
890
891 #[cfg(not(any(test, all(debug_assertions, feature = "test-support"))))]
898 #[inline]
899 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
900 self
901 }
902
903 fn capture_any_mouse_down(
908 mut self,
909 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
910 ) -> Self {
911 self.interactivity().capture_any_mouse_down(listener);
912 self
913 }
914
915 fn on_any_mouse_down(
920 mut self,
921 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
922 ) -> Self {
923 self.interactivity().on_any_mouse_down(listener);
924 self
925 }
926
927 fn on_mouse_up(
932 mut self,
933 button: MouseButton,
934 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
935 ) -> Self {
936 self.interactivity().on_mouse_up(button, listener);
937 self
938 }
939
940 fn capture_any_mouse_up(
945 mut self,
946 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
947 ) -> Self {
948 self.interactivity().capture_any_mouse_up(listener);
949 self
950 }
951
952 fn on_mouse_pressure(
957 mut self,
958 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
959 ) -> Self {
960 self.interactivity().on_mouse_pressure(listener);
961 self
962 }
963
964 fn capture_mouse_pressure(
969 mut self,
970 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
971 ) -> Self {
972 self.interactivity().capture_mouse_pressure(listener);
973 self
974 }
975
976 fn on_mouse_down_out(
982 mut self,
983 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
984 ) -> Self {
985 self.interactivity().on_mouse_down_out(listener);
986 self
987 }
988
989 fn on_mouse_up_out(
995 mut self,
996 button: MouseButton,
997 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
998 ) -> Self {
999 self.interactivity().on_mouse_up_out(button, listener);
1000 self
1001 }
1002
1003 fn on_mouse_move(
1008 mut self,
1009 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
1010 ) -> Self {
1011 self.interactivity().on_mouse_move(listener);
1012 self
1013 }
1014
1015 fn on_mouse_exit(
1020 mut self,
1021 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
1022 ) -> Self {
1023 self.interactivity().on_mouse_exit(listener);
1024 self
1025 }
1026
1027 fn on_file_drop_exit(
1035 mut self,
1036 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
1037 ) -> Self {
1038 self.interactivity().on_file_drop_exit(listener);
1039 self
1040 }
1041
1042 fn on_drag_move<T: 'static>(
1050 mut self,
1051 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
1052 ) -> Self {
1053 self.interactivity().on_drag_move(listener);
1054 self
1055 }
1056
1057 fn on_scroll_wheel(
1062 mut self,
1063 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
1064 ) -> Self {
1065 self.interactivity().on_scroll_wheel(listener);
1066 self
1067 }
1068
1069 fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
1074 self.interactivity().on_pinch(listener);
1075 self
1076 }
1077
1078 fn capture_pinch(
1083 mut self,
1084 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
1085 ) -> Self {
1086 self.interactivity().capture_pinch(listener);
1087 self
1088 }
1089 fn capture_action<A: Action>(
1094 mut self,
1095 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1096 ) -> Self {
1097 self.interactivity().capture_action(listener);
1098 self
1099 }
1100
1101 #[track_caller]
1106 #[inline(always)]
1107 fn on_action<A: Action>(
1108 mut self,
1109 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1110 ) -> Self {
1111 self.interactivity().on_action(listener);
1112 self
1113 }
1114
1115 fn on_boxed_action(
1122 mut self,
1123 action: &dyn Action,
1124 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1125 ) -> Self {
1126 self.interactivity().on_boxed_action(action, listener);
1127 self
1128 }
1129
1130 fn on_key_down(
1135 mut self,
1136 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1137 ) -> Self {
1138 self.interactivity().on_key_down(listener);
1139 self
1140 }
1141
1142 fn capture_key_down(
1147 mut self,
1148 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1149 ) -> Self {
1150 self.interactivity().capture_key_down(listener);
1151 self
1152 }
1153
1154 fn on_key_up(
1159 mut self,
1160 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1161 ) -> Self {
1162 self.interactivity().on_key_up(listener);
1163 self
1164 }
1165
1166 fn capture_key_up(
1171 mut self,
1172 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1173 ) -> Self {
1174 self.interactivity().capture_key_up(listener);
1175 self
1176 }
1177
1178 #[inline(always)]
1183 fn on_modifiers_changed(
1184 mut self,
1185 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1186 ) -> Self {
1187 self.interactivity().on_modifiers_changed(listener);
1188 self
1189 }
1190
1191 fn drag_over<S: 'static>(
1193 mut self,
1194 f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1195 ) -> Self {
1196 self.interactivity().drag_over_styles.push((
1197 TypeId::of::<S>(),
1198 Box::new(move |currently_dragged: &dyn Any, window, cx| {
1199 f(
1200 StyleRefinement::default(),
1201 currently_dragged.downcast_ref::<S>().unwrap(),
1202 window,
1203 cx,
1204 )
1205 }),
1206 ));
1207 self
1208 }
1209
1210 fn group_drag_over<S: 'static>(
1212 mut self,
1213 group_name: impl Into<SharedString>,
1214 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1215 ) -> Self {
1216 self.interactivity().group_drag_over_styles.push((
1217 TypeId::of::<S>(),
1218 GroupStyle {
1219 group: group_name.into(),
1220 style: Box::new(f(StyleRefinement::default())),
1221 },
1222 ));
1223 self
1224 }
1225
1226 fn on_drop<T: 'static>(
1231 mut self,
1232 listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1233 ) -> Self {
1234 self.interactivity().on_drop(listener);
1235 self
1236 }
1237
1238 fn can_drop(
1241 mut self,
1242 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1243 ) -> Self {
1244 self.interactivity().can_drop(predicate);
1245 self
1246 }
1247
1248 fn occlude(mut self) -> Self {
1252 self.interactivity().occlude_mouse();
1253 self
1254 }
1255
1256 fn window_control_area(mut self, area: WindowControlArea) -> Self {
1259 self.interactivity().window_control_area(area);
1260 self
1261 }
1262
1263 fn block_mouse_except_scroll(mut self) -> Self {
1268 self.interactivity().block_mouse_except_scroll();
1269 self
1270 }
1271
1272 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1275 where
1276 Self: Sized,
1277 {
1278 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1279 self
1280 }
1281
1282 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1285 where
1286 Self: Sized,
1287 {
1288 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1289 self
1290 }
1291
1292 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1297 where
1298 Self: Sized,
1299 {
1300 self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1301 self
1302 }
1303}
1304
1305pub trait StatefulInteractiveElement: InteractiveElement {
1308 fn role(mut self, role: accesskit::Role) -> Self {
1312 debug_assert!(
1313 role != accesskit::Role::GenericContainer,
1314 "GenericContainer is filtered out of the a11y tree and has no effect"
1315 );
1316 self.interactivity().override_role = Some(role);
1317 self
1318 }
1319
1320 fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self {
1328 self.interactivity().aria.author_id = Some(id.into());
1329 self
1330 }
1331
1332 fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1334 self.interactivity().aria.label = Some(label.into());
1335 self
1336 }
1337
1338 fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
1343 self.interactivity().aria.description = Some(description.into());
1344 self
1345 }
1346
1347 fn aria_keyshortcuts(mut self, keyshortcuts: impl Into<SharedString>) -> Self {
1353 self.interactivity().aria.keyshortcuts = Some(keyshortcuts.into());
1354 self
1355 }
1356
1357 fn aria_active_descendant(mut self) -> Self {
1373 self.interactivity().report_active_descendant_focus = true;
1374 self
1375 }
1376
1377 fn a11y_synthetic_children(
1387 mut self,
1388 f: impl FnOnce(&mut crate::A11ySubtreeBuilder) + 'static,
1389 ) -> Self {
1390 self.interactivity().a11y_synthetic_children =
1391 crate::fast::interactivity::rare(Box::new(f));
1392 self
1393 }
1394
1395 fn aria_selected(mut self, selected: bool) -> Self {
1397 self.interactivity().aria.selected = Some(selected);
1398 self
1399 }
1400
1401 fn aria_expanded(mut self, expanded: bool) -> Self {
1403 self.interactivity().aria.expanded = Some(expanded);
1404 self
1405 }
1406
1407 fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1409 self.interactivity().aria.toggled = Some(toggled);
1410 self
1411 }
1412
1413 fn aria_numeric_value(mut self, value: f64) -> Self {
1415 self.interactivity().aria.numeric_value = Some(value);
1416 self
1417 }
1418
1419 fn aria_numeric_value_step(mut self, step: f64) -> Self {
1422 self.interactivity().aria.numeric_value_step = Some(step);
1423 self
1424 }
1425
1426 fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
1429 self.interactivity().aria.value = Some(value.into());
1430 self
1431 }
1432
1433 fn aria_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1436 self.interactivity().aria.placeholder = Some(placeholder.into());
1437 self
1438 }
1439
1440 fn aria_min_numeric_value(mut self, value: f64) -> Self {
1442 self.interactivity().aria.min_numeric_value = Some(value);
1443 self
1444 }
1445
1446 fn aria_max_numeric_value(mut self, value: f64) -> Self {
1448 self.interactivity().aria.max_numeric_value = Some(value);
1449 self
1450 }
1451
1452 fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1454 self.interactivity().aria.orientation = Some(orientation);
1455 self
1456 }
1457
1458 fn aria_level(mut self, level: usize) -> Self {
1460 self.interactivity().aria.level = Some(level);
1461 self
1462 }
1463
1464 fn aria_position_in_set(mut self, position: usize) -> Self {
1466 self.interactivity().aria.position_in_set = Some(position);
1467 self
1468 }
1469
1470 fn aria_size_of_set(mut self, size: usize) -> Self {
1472 self.interactivity().aria.size_of_set = Some(size);
1473 self
1474 }
1475
1476 fn aria_row_index(mut self, index: usize) -> Self {
1478 self.interactivity().aria.row_index = Some(index);
1479 self
1480 }
1481
1482 fn aria_column_index(mut self, index: usize) -> Self {
1484 self.interactivity().aria.column_index = Some(index);
1485 self
1486 }
1487
1488 fn aria_row_count(mut self, count: usize) -> Self {
1490 self.interactivity().aria.row_count = Some(count);
1491 self
1492 }
1493
1494 fn aria_column_count(mut self, count: usize) -> Self {
1496 self.interactivity().aria.column_count = Some(count);
1497 self
1498 }
1499
1500 #[inline(always)]
1505 fn on_a11y_action(
1506 mut self,
1507 action: accesskit::Action,
1508 listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1509 + 'static,
1510 ) -> Self {
1511 self.interactivity()
1512 .a11y_action_listeners
1513 .push((action, Box::new(listener)));
1514 self
1515 }
1516
1517 fn focusable(mut self) -> Self {
1519 self.interactivity().focusable = true;
1520 self
1521 }
1522
1523 fn overflow_scroll(mut self) -> Self {
1525 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1526 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1527 self
1528 }
1529
1530 fn overflow_x_scroll(mut self) -> Self {
1532 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1533 self
1534 }
1535
1536 fn overflow_y_scroll(mut self) -> Self {
1538 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1539 self
1540 }
1541
1542 fn restrict_scroll_to_axis(mut self) -> Self {
1546 self.interactivity().base_style.restrict_scroll_to_axis = Some(true);
1547 self
1548 }
1549
1550 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1552 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1553 self
1554 }
1555
1556 fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1558 self.interactivity().scroll_anchor = crate::fast::interactivity::rare_option(scroll_anchor);
1559 self
1560 }
1561
1562 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1564 where
1565 Self: Sized,
1566 {
1567 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1568 self
1569 }
1570
1571 fn group_active(
1573 mut self,
1574 group_name: impl Into<SharedString>,
1575 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1576 ) -> Self
1577 where
1578 Self: Sized,
1579 {
1580 self.interactivity().group_active_style = crate::fast::interactivity::rare(GroupStyle {
1581 group: group_name.into(),
1582 style: Box::new(f(StyleRefinement::default())),
1583 });
1584 self
1585 }
1586
1587 #[inline(always)]
1592 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1593 where
1594 Self: Sized,
1595 {
1596 self.interactivity().on_click(listener);
1597 self
1598 }
1599
1600 fn on_aux_click(
1605 mut self,
1606 listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1607 ) -> Self
1608 where
1609 Self: Sized,
1610 {
1611 self.interactivity().on_aux_click(listener);
1612 self
1613 }
1614
1615 fn on_drag<T, W>(
1623 mut self,
1624 value: T,
1625 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1626 ) -> Self
1627 where
1628 Self: Sized,
1629 T: 'static,
1630 W: 'static + Render,
1631 {
1632 self.interactivity().on_drag(value, constructor);
1633 self
1634 }
1635
1636 fn external_drag_payload<T>(
1642 mut self,
1643 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
1644 ) -> Self
1645 where
1646 Self: Sized,
1647 T: 'static,
1648 {
1649 self.interactivity().external_drag_payload(resolver);
1650 self
1651 }
1652
1653 fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1664 where
1665 Self: Sized,
1666 {
1667 self.interactivity().on_hover(listener);
1668 self
1669 }
1670
1671 fn hover_listener_mode(mut self, mode: HoverListenerMode) -> Self
1675 where
1676 Self: Sized,
1677 {
1678 self.interactivity().hover_listener_mode(mode);
1679 self
1680 }
1681
1682 fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1685 where
1686 Self: Sized,
1687 {
1688 self.interactivity().tooltip(build_tooltip);
1689 self
1690 }
1691
1692 fn hoverable_tooltip(
1696 mut self,
1697 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1698 ) -> Self
1699 where
1700 Self: Sized,
1701 {
1702 self.interactivity().hoverable_tooltip(build_tooltip);
1703 self
1704 }
1705
1706 fn tooltip_show_delay(mut self, delay: Duration) -> Self
1711 where
1712 Self: Sized,
1713 {
1714 self.interactivity().tooltip_show_delay(delay);
1715 self
1716 }
1717}
1718
1719pub(crate) type MouseDownListener =
1720 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1721pub(crate) type MouseUpListener =
1722 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1723pub(crate) type MousePressureListener =
1724 Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1725pub(crate) type MouseMoveListener =
1726 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1727pub(crate) type MouseExitListener =
1728 Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1729
1730pub(crate) type FileDropExitListener =
1731 Box<dyn Fn(&FileDropEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1732
1733pub(crate) type ScrollWheelListener =
1734 Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1735
1736pub(crate) type PinchListener =
1737 Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1738
1739pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1740
1741#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1744pub enum HoverListenerMode {
1745 #[default]
1748 InputModalityAware,
1749 InputModalityIndependent,
1753}
1754
1755impl HoverListenerMode {
1756 fn is_hovered(self, hitbox: &Hitbox, window: &Window) -> bool {
1757 match self {
1758 Self::InputModalityAware => hitbox.is_hovered(window),
1759 Self::InputModalityIndependent => hitbox.id.is_hovered_ignoring_last_input(window),
1760 }
1761 }
1762}
1763
1764pub(crate) struct DragListener {
1765 value: Arc<dyn Any>,
1766 render: Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>,
1767 external_payload: Option<ExternalDragPayloadResolver>,
1768}
1769
1770type ExternalDragPayloadResolver =
1771 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
1772
1773type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1774
1775type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1776
1777pub(crate) struct TooltipBuilder {
1778 build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1779 hoverable: bool,
1780}
1781
1782pub(crate) type KeyDownListener =
1783 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1784
1785pub(crate) type KeyUpListener =
1786 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1787
1788pub(crate) type ModifiersChangedListener =
1789 Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1790
1791pub(crate) type ActionListener =
1792 Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1793
1794#[track_caller]
1796pub fn div() -> Div {
1797 Div {
1798 interactivity: Interactivity::new(),
1799 children: SmallVec::default(),
1800 prepaint_listener: None,
1801 image_cache: None,
1802 prepaint_order_fn: None,
1803 }
1804}
1805
1806pub struct Div {
1808 interactivity: Interactivity,
1809 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1810 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1811 image_cache: Option<Box<dyn ImageCacheProvider>>,
1812 prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1813}
1814
1815impl Div {
1816 pub fn on_children_prepainted(
1819 mut self,
1820 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1821 ) -> Self {
1822 self.prepaint_listener = Some(Box::new(listener));
1823 self
1824 }
1825
1826 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1828 self.image_cache = Some(Box::new(cache));
1829 self
1830 }
1831
1832 pub fn with_dynamic_prepaint_order(
1841 mut self,
1842 order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1843 ) -> Self {
1844 self.prepaint_order_fn = Some(Box::new(order_fn));
1845 self
1846 }
1847}
1848
1849pub struct DivFrameState {
1856 child_layout_ids: SmallVec<[LayoutId; 2]>,
1857}
1858
1859#[derive(Clone)]
1861pub struct DivInspectorState {
1862 #[cfg(any(feature = "inspector", debug_assertions))]
1866 pub base_style: Box<StyleRefinement>,
1867 pub bounds: Bounds<Pixels>,
1869 pub content_size: Size<Pixels>,
1871}
1872
1873impl Styled for Div {
1874 fn style(&mut self) -> &mut StyleRefinement {
1875 &mut self.interactivity.base_style
1876 }
1877}
1878
1879impl InteractiveElement for Div {
1880 fn interactivity(&mut self) -> &mut Interactivity {
1881 &mut self.interactivity
1882 }
1883}
1884
1885impl ParentElement for Div {
1886 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1887 #[cfg(feature = "stacker")]
1888 self.children
1889 .extend(elements.into_iter().map(StackSafe::new));
1890 #[cfg(not(feature = "stacker"))]
1891 self.children.extend(elements);
1892 }
1893}
1894
1895impl Element for Div {
1896 type RequestLayoutState = DivFrameState;
1897 type PrepaintState = Option<Hitbox>;
1898
1899 fn id(&self) -> Option<ElementId> {
1900 self.interactivity.element_id.clone()
1901 }
1902
1903 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1904 self.interactivity.source_location()
1905 }
1906
1907 fn a11y_role(&self) -> Option<accesskit::Role> {
1908 self.interactivity
1911 .override_role
1912 .filter(|role| *role != accesskit::Role::GenericContainer)
1913 }
1914
1915 fn write_a11y_info(&self, node: &mut accesskit::Node) {
1916 self.interactivity.write_a11y_info(node);
1917 }
1918
1919 fn a11y_synthetic_children(
1920 &mut self,
1921 _prepaint: &mut Self::PrepaintState,
1922 builder: &mut crate::A11ySubtreeBuilder,
1923 ) {
1924 if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
1925 f(builder);
1926 }
1927 }
1928
1929 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
1930 fn request_layout(
1931 &mut self,
1932 global_id: Option<&GlobalElementId>,
1933 inspector_id: Option<&InspectorElementId>,
1934 window: &mut Window,
1935 cx: &mut App,
1936 ) -> (LayoutId, Self::RequestLayoutState) {
1937 let mut child_layout_ids = SmallVec::new();
1938 let image_cache = self
1939 .image_cache
1940 .as_mut()
1941 .map(|provider| provider.provide(window, cx));
1942
1943 let layout_id = window.with_image_cache(image_cache, |window| {
1944 self.interactivity.request_layout(
1945 global_id,
1946 inspector_id,
1947 window,
1948 cx,
1949 |style, window, cx| {
1950 window.with_text_style(style.text_style().cloned(), |window| {
1951 child_layout_ids = self
1952 .children
1953 .iter_mut()
1954 .map(|child| child.request_layout(window, cx))
1955 .collect::<SmallVec<_>>();
1956 crate::fast::layout::request_layout(window, &style, &child_layout_ids)
1957 })
1958 },
1959 )
1960 });
1961
1962 (layout_id, DivFrameState { child_layout_ids })
1963 }
1964
1965 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
1966 fn prepaint(
1967 &mut self,
1968 global_id: Option<&GlobalElementId>,
1969 inspector_id: Option<&InspectorElementId>,
1970 bounds: Bounds<Pixels>,
1971 request_layout: &mut Self::RequestLayoutState,
1972 window: &mut Window,
1973 cx: &mut App,
1974 ) -> Option<Hitbox> {
1975 let image_cache = self
1976 .image_cache
1977 .as_mut()
1978 .map(|provider| provider.provide(window, cx));
1979
1980 let has_prepaint_listener = self.prepaint_listener.is_some();
1981 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1982 request_layout.child_layout_ids.len()
1983 } else {
1984 0
1985 });
1986
1987 let mut child_min = point(Pixels::MAX, Pixels::MAX);
1988 let mut child_max = Point::default();
1989 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1990 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1991 }
1992 let content_size = if request_layout.child_layout_ids.is_empty() {
1993 bounds.size
1994 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1995 crate::fast::layers::input::track_handle(window, &scroll_handle.0);
1996 let mut state = scroll_handle.0.borrow_mut();
1997 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1998 for child_layout_id in &request_layout.child_layout_ids {
1999 let child_bounds = window.layout_bounds(*child_layout_id);
2000 child_min = child_min.min(&child_bounds.origin);
2001 child_max = child_max.max(&child_bounds.bottom_right());
2002 state.child_bounds.push(child_bounds);
2003 }
2004 (child_max - child_min).into()
2005 } else {
2006 for child_layout_id in &request_layout.child_layout_ids {
2007 let child_bounds = window.layout_bounds(*child_layout_id);
2008 child_min = child_min.min(&child_bounds.origin);
2009 child_max = child_max.max(&child_bounds.bottom_right());
2010
2011 if has_prepaint_listener {
2012 children_bounds.push(child_bounds);
2013 }
2014 }
2015 (child_max - child_min).into()
2016 };
2017
2018 if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2019 scroll_handle.scroll_to_active_item();
2020 }
2021
2022 self.interactivity.prepaint(
2023 global_id,
2024 inspector_id,
2025 bounds,
2026 content_size,
2027 window,
2028 cx,
2029 |style, scroll_offset, hitbox, window, cx| {
2030 if style.display == Display::None {
2032 return hitbox;
2033 }
2034
2035 window.with_image_cache(image_cache, |window| {
2036 let fast_layer = crate::fast::layers::paint::begin_children(
2037 window,
2038 cx,
2039 global_id,
2040 bounds,
2041 child_min,
2042 content_size,
2043 scroll_offset,
2044 style,
2045 );
2046 crate::fast::layers::paint::prepaint_children(window, fast_layer, |window| {
2047 if let Some(order_fn) = &self.prepaint_order_fn {
2048 let order = order_fn(window, cx);
2049 for idx in order {
2050 if let Some(child) = self.children.get_mut(idx) {
2051 child.prepaint(window, cx);
2052 }
2053 }
2054 } else {
2055 for child in &mut self.children {
2056 child.prepaint(window, cx);
2057 }
2058 }
2059 });
2060 crate::fast::layers::paint::end_children(window, cx, fast_layer);
2061
2062 if let Some(listener) = self.prepaint_listener.as_ref() {
2063 crate::fast::layers::invalidate::note_uncarried(window);
2064 listener(children_bounds, window, cx);
2065 }
2066 });
2067
2068 hitbox
2069 },
2070 )
2071 }
2072
2073 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2074 fn paint(
2075 &mut self,
2076 global_id: Option<&GlobalElementId>,
2077 inspector_id: Option<&InspectorElementId>,
2078 bounds: Bounds<Pixels>,
2079 _request_layout: &mut Self::RequestLayoutState,
2080 hitbox: &mut Option<Hitbox>,
2081 window: &mut Window,
2082 cx: &mut App,
2083 ) {
2084 let image_cache = self
2085 .image_cache
2086 .as_mut()
2087 .map(|provider| provider.provide(window, cx));
2088
2089 window.with_image_cache(image_cache, |window| {
2090 self.interactivity.paint(
2091 global_id,
2092 inspector_id,
2093 bounds,
2094 hitbox.as_ref(),
2095 window,
2096 cx,
2097 |style, window, cx| {
2098 if style.display == Display::None {
2100 return;
2101 }
2102
2103 crate::fast::layers::paint::paint_children(
2104 window,
2105 cx,
2106 global_id,
2107 |window, cx| {
2108 for child in &mut self.children {
2109 child.paint(window, cx);
2110 }
2111 },
2112 );
2113 },
2114 )
2115 });
2116 }
2117}
2118
2119impl IntoElement for Div {
2120 type Element = Self;
2121
2122 fn into_element(self) -> Self::Element {
2123 self
2124 }
2125}
2126
2127#[derive(Default)]
2128pub(crate) struct AriaProperties {
2129 pub(crate) author_id: Option<SharedString>,
2130 pub(crate) label: Option<SharedString>,
2131 pub(crate) description: Option<SharedString>,
2132 pub(crate) keyshortcuts: Option<SharedString>,
2133 pub(crate) selected: Option<bool>,
2134 pub(crate) expanded: Option<bool>,
2135 pub(crate) toggled: Option<accesskit::Toggled>,
2136 pub(crate) numeric_value: Option<f64>,
2137 pub(crate) min_numeric_value: Option<f64>,
2138 pub(crate) max_numeric_value: Option<f64>,
2139 pub(crate) numeric_value_step: Option<f64>,
2140 pub(crate) value: Option<SharedString>,
2141 pub(crate) placeholder: Option<SharedString>,
2142 pub(crate) orientation: Option<accesskit::Orientation>,
2143 pub(crate) level: Option<usize>,
2144 pub(crate) position_in_set: Option<usize>,
2145 pub(crate) size_of_set: Option<usize>,
2146 pub(crate) row_index: Option<usize>,
2147 pub(crate) column_index: Option<usize>,
2148 pub(crate) row_count: Option<usize>,
2149 pub(crate) column_count: Option<usize>,
2150}
2151
2152#[derive(Default)]
2155pub struct Interactivity {
2156 pub element_id: Option<ElementId>,
2158 pub active: Option<bool>,
2160 pub hovered: Option<bool>,
2163 pub(crate) tooltip_id: Option<TooltipId>,
2164 pub(crate) content_size: Size<Pixels>,
2165 pub(crate) key_context: Option<KeyContext>,
2166 pub(crate) focusable: bool,
2167 pub(crate) tracked_focus_handle: Option<FocusHandle>,
2168 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2169 pub(crate) scroll_anchor: crate::fast::interactivity::Rare<ScrollAnchor>,
2170 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2171 pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2172 pub(crate) group: Option<SharedString>,
2173 pub base_style: Box<StyleRefinement>,
2176 pub(crate) focus_style: Option<Box<StyleRefinement>>,
2177 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2178 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2179 pub(crate) hover_style: Option<Box<StyleRefinement>>,
2180 pub(crate) group_hover_style: crate::fast::interactivity::Rare<GroupStyle>,
2181 pub(crate) active_style: Option<Box<StyleRefinement>>,
2182 pub(crate) group_active_style: crate::fast::interactivity::Rare<GroupStyle>,
2183 pub(crate) drag_over_styles: crate::fast::interactivity::LazyVec<(
2184 TypeId,
2185 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2186 )>,
2187 pub(crate) group_drag_over_styles: crate::fast::interactivity::LazyVec<(TypeId, GroupStyle)>,
2188 pub(crate) mouse_down_listeners: crate::fast::interactivity::LazyVec<MouseDownListener>,
2189 pub(crate) mouse_up_listeners: crate::fast::interactivity::LazyVec<MouseUpListener>,
2190 pub(crate) mouse_pressure_listeners: crate::fast::interactivity::LazyVec<MousePressureListener>,
2191 pub(crate) mouse_move_listeners: crate::fast::interactivity::LazyVec<MouseMoveListener>,
2192 pub(crate) mouse_exit_listeners: crate::fast::interactivity::LazyVec<MouseExitListener>,
2193 pub(crate) file_drop_exit_listeners: crate::fast::interactivity::LazyVec<FileDropExitListener>,
2194 pub(crate) scroll_wheel_listeners: crate::fast::interactivity::LazyVec<ScrollWheelListener>,
2195 pub(crate) pinch_listeners: crate::fast::interactivity::LazyVec<PinchListener>,
2196 pub(crate) key_down_listeners: crate::fast::interactivity::LazyVec<KeyDownListener>,
2197 pub(crate) key_up_listeners: crate::fast::interactivity::LazyVec<KeyUpListener>,
2198 pub(crate) modifiers_changed_listeners:
2199 crate::fast::interactivity::LazyVec<ModifiersChangedListener>,
2200 pub(crate) action_listeners: crate::fast::interactivity::LazyVec<(TypeId, ActionListener)>,
2201 pub(crate) drop_listeners: crate::fast::interactivity::LazyVec<(TypeId, DropListener)>,
2202 pub(crate) can_drop_predicate: crate::fast::interactivity::Rare<CanDropPredicate>,
2203 pub(crate) click_listeners: crate::fast::interactivity::LazyVec<ClickListener>,
2204 pub(crate) aux_click_listeners: crate::fast::interactivity::LazyVec<ClickListener>,
2205 pub(crate) drag_listener: crate::fast::interactivity::Rare<DragListener>,
2206 pub(crate) hover_listener:
2207 crate::fast::interactivity::Rare<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2208 pub(crate) hover_listener_mode: HoverListenerMode,
2209 pub(crate) tooltip_builder: crate::fast::interactivity::Rare<TooltipBuilder>,
2210 pub(crate) tooltip_show_delay: Option<Duration>,
2211 pub(crate) window_control: Option<WindowControlArea>,
2212 pub(crate) hitbox_behavior: HitboxBehavior,
2213 pub(crate) tab_index: Option<isize>,
2214 pub(crate) tab_group: bool,
2215 pub(crate) tab_stop: bool,
2216
2217 pub(crate) a11y_action_listeners: crate::fast::interactivity::LazyVec<(
2218 accesskit::Action,
2219 crate::window::a11y::A11yActionListener,
2220 )>,
2221 pub(crate) a11y_synthetic_children:
2222 crate::fast::interactivity::Rare<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2223 pub(crate) report_active_descendant_focus: bool,
2224 pub(crate) override_role: Option<accesskit::Role>,
2225 pub(crate) aria: crate::fast::interactivity::Aria,
2226
2227 #[cfg(any(feature = "inspector", debug_assertions))]
2228 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2229
2230 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2231 pub(crate) debug_selector: Option<String>,
2232}
2233
2234impl Interactivity {
2235 pub fn request_layout(
2237 &mut self,
2238 global_id: Option<&GlobalElementId>,
2239 _inspector_id: Option<&InspectorElementId>,
2240 window: &mut Window,
2241 cx: &mut App,
2242 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2243 ) -> LayoutId {
2244 #[cfg(any(feature = "inspector", debug_assertions))]
2245 window.with_inspector_state(
2246 _inspector_id,
2247 cx,
2248 |inspector_state: &mut Option<DivInspectorState>, _window| {
2249 if let Some(inspector_state) = inspector_state {
2250 self.base_style = inspector_state.base_style.clone();
2251 } else {
2252 *inspector_state = Some(DivInspectorState {
2253 base_style: self.base_style.clone(),
2254 bounds: Default::default(),
2255 content_size: Default::default(),
2256 })
2257 }
2258 },
2259 );
2260
2261 window.with_optional_element_state::<InteractiveElementState, _>(
2262 global_id,
2263 |element_state, window| {
2264 let mut element_state =
2265 element_state.map(|element_state| element_state.unwrap_or_default());
2266
2267 if let Some(element_state) = element_state.as_ref()
2268 && cx.has_active_drag()
2269 {
2270 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2271 *pending_mouse_down.borrow_mut() = None;
2272 }
2273 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2274 *clicked_state.borrow_mut() = ElementClickedState::default();
2275 }
2276 }
2277
2278 if self.focusable
2283 && self.tracked_focus_handle.is_none()
2284 && let Some(element_state) = element_state.as_mut()
2285 {
2286 let mut handle = element_state
2287 .focus_handle
2288 .get_or_insert_with(|| cx.focus_handle())
2289 .clone()
2290 .tab_stop(self.tab_stop);
2291
2292 if let Some(index) = self.tab_index {
2293 handle = handle.tab_index(index);
2294 }
2295
2296 self.tracked_focus_handle = Some(handle);
2297 }
2298
2299 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2300 let scroll_handle_state = scroll_handle.0.borrow();
2301 crate::fast::dependencies::note_state_read(cx, &scroll_handle_state.version);
2302 self.scroll_offset = Some(scroll_handle_state.offset.clone());
2303 self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2304 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2305 || self.base_style.overflow.y == Some(Overflow::Scroll))
2306 && let Some(element_state) = element_state.as_mut()
2307 {
2308 self.scroll_offset = Some(
2309 element_state
2310 .scroll_offset
2311 .get_or_insert_with(Rc::default)
2312 .clone(),
2313 );
2314 self.ongoing_scroll = Some(
2315 element_state
2316 .ongoing_scroll
2317 .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2318 .clone(),
2319 );
2320 }
2321
2322 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2323 let layout_id = f(style, window, cx);
2324 (layout_id, element_state)
2325 },
2326 )
2327 }
2328
2329 pub fn prepaint<R>(
2331 &mut self,
2332 global_id: Option<&GlobalElementId>,
2333 _inspector_id: Option<&InspectorElementId>,
2334 bounds: Bounds<Pixels>,
2335 content_size: Size<Pixels>,
2336 window: &mut Window,
2337 cx: &mut App,
2338 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2339 ) -> R {
2340 self.content_size = content_size;
2341
2342 #[cfg(any(feature = "inspector", debug_assertions))]
2343 window.with_inspector_state(
2344 _inspector_id,
2345 cx,
2346 |inspector_state: &mut Option<DivInspectorState>, _window| {
2347 if let Some(inspector_state) = inspector_state {
2348 inspector_state.bounds = bounds;
2349 inspector_state.content_size = content_size;
2350 }
2351 },
2352 );
2353
2354 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2355 window.set_focus_handle(focus_handle, cx);
2356
2357 if window.a11y.is_active() {
2358 if let Some(global_id) = global_id {
2359 let node_id = global_id.accesskit_node_id();
2360 window.a11y.set_focusable(node_id, focus_handle.id);
2361 if focus_handle.is_focused(window) {
2362 window.a11y.set_focus(node_id);
2363 }
2364 } else if focus_handle.is_focused(window) {
2365 window
2369 .a11y
2370 .note_focus_without_node(focus_handle.id, "it has no element id");
2371 }
2372 }
2373 }
2374
2375 if self.report_active_descendant_focus && window.a11y.is_active() {
2376 if let Some(global_id) = global_id {
2377 window
2378 .a11y
2379 .set_active_descendant(global_id.accesskit_node_id());
2380 }
2381 }
2382 window.with_optional_element_state::<InteractiveElementState, _>(
2383 global_id,
2384 |element_state, window| {
2385 let mut element_state =
2386 element_state.map(|element_state| element_state.unwrap_or_default());
2387 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2388
2389 if let Some(element_state) = element_state.as_mut() {
2390 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2391 let clicked_state = clicked_state.borrow();
2392 self.active = Some(clicked_state.element);
2393 }
2394 if self.hover_style.is_some() || self.group_hover_style.is_some() {
2395 element_state
2396 .hover_state
2397 .get_or_insert_with(Default::default);
2398 }
2399 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2400 if self.tooltip_builder.is_some() {
2401 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2402 } else {
2403 if let Some(long_press_tooltip_active) =
2405 element_state.long_press_tooltip_active.as_ref()
2406 {
2407 long_press_tooltip_active.set(false);
2408 }
2409 element_state.active_tooltip.take();
2410 }
2411 }
2412 }
2413
2414 let opacity = crate::fast::retained::push_element_opacity(window, style.opacity);
2415 let result = window.with_text_style(style.text_style().cloned(), |window| {
2416 window.with_content_mask(
2417 style.overflow_mask(bounds, window.rem_size()),
2418 |window| {
2419 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2420 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2421 } else {
2422 None
2423 };
2424
2425 let scroll_offset =
2426 self.clamp_scroll_position(bounds, &style, window, cx);
2427 let result = f(&style, scroll_offset, hitbox, window, cx);
2428 (result, element_state)
2429 },
2430 )
2431 });
2432 crate::fast::retained::pop_element_opacity(window, opacity);
2433 result
2434 },
2435 )
2436 }
2437
2438 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2439 self.hitbox_behavior != HitboxBehavior::Normal
2440 || self.window_control.is_some()
2441 || style.mouse_cursor.is_some()
2442 || self.group.is_some()
2443 || self.scroll_offset.is_some()
2444 || self.tracked_focus_handle.is_some()
2445 || self.hover_style.is_some()
2446 || self.group_hover_style.is_some()
2447 || self.hover_listener.is_some()
2448 || !self.mouse_up_listeners.is_empty()
2449 || !self.mouse_pressure_listeners.is_empty()
2450 || !self.mouse_down_listeners.is_empty()
2451 || !self.mouse_move_listeners.is_empty()
2452 || !self.mouse_exit_listeners.is_empty()
2453 || !self.file_drop_exit_listeners.is_empty()
2454 || !self.click_listeners.is_empty()
2455 || !self.aux_click_listeners.is_empty()
2456 || !self.scroll_wheel_listeners.is_empty()
2457 || self.has_pinch_listeners()
2458 || self.drag_listener.is_some()
2459 || !self.drop_listeners.is_empty()
2460 || !self.drag_over_styles.is_empty()
2461 || self.tooltip_builder.is_some()
2462 || window.is_inspector_picking(cx)
2463 }
2464
2465 fn clamp_scroll_position(
2466 &self,
2467 bounds: Bounds<Pixels>,
2468 style: &Style,
2469 window: &mut Window,
2470 _cx: &mut App,
2471 ) -> Point<Pixels> {
2472 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2473 const ROUNDING_FACTOR: f32 = 100.0;
2474 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2475 }
2476
2477 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2478 let mut scroll_to_bottom = false;
2479 let mut tracked_scroll_handle = self
2480 .tracked_scroll_handle
2481 .as_ref()
2482 .map(|handle| handle.0.borrow_mut());
2483 if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2484 scroll_handle_state.overflow = style.overflow;
2485 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2486 }
2487
2488 let rem_size = window.rem_size();
2489 let padding = style
2494 .padding
2495 .to_pixels(bounds.size.into(), rem_size)
2496 .map(|edge| window.pixel_snap(*edge));
2497 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2498 let padded_content_size = self.content_size + padding_size;
2505 let scroll_max = Point::from(padded_content_size - bounds.size)
2506 .map(round_to_two_decimals)
2507 .max(&Default::default());
2508 let mut scroll_offset = scroll_offset.borrow_mut();
2511
2512 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2513 if scroll_to_bottom {
2514 scroll_offset.y = -scroll_max.y;
2515 } else {
2516 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2517 }
2518
2519 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2520 scroll_handle_state.max_offset = scroll_max;
2521 scroll_handle_state.bounds = bounds;
2522 }
2523
2524 *scroll_offset
2525 } else {
2526 Point::default()
2527 }
2528 }
2529
2530 pub fn paint(
2539 &mut self,
2540 global_id: Option<&GlobalElementId>,
2541 _inspector_id: Option<&InspectorElementId>,
2542 bounds: Bounds<Pixels>,
2543 hitbox: Option<&Hitbox>,
2544 window: &mut Window,
2545 cx: &mut App,
2546 f: impl FnOnce(&Style, &mut Window, &mut App),
2547 ) {
2548 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2549 window.with_optional_element_state::<InteractiveElementState, _>(
2550 global_id,
2551 |element_state, window| {
2552 let mut element_state =
2553 element_state.map(|element_state| element_state.unwrap_or_default());
2554
2555 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2556
2557 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2558 if let Some(debug_selector) = &self.debug_selector {
2559 window
2560 .next_frame
2561 .record_debug_bounds(debug_selector.clone(), bounds);
2562 }
2563
2564 self.paint_hover_group_handler(window, cx);
2565
2566 if style.visibility == Visibility::Hidden {
2567 return ((), element_state);
2568 }
2569
2570 let mut tab_group = None;
2571 if self.tab_group {
2572 tab_group = self.tab_index;
2573 }
2574
2575 window.with_element_opacity(style.opacity, |window| {
2576 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2577 window.with_text_style(style.text_style().cloned(), |window| {
2578 window.with_content_mask(
2579 style.overflow_mask(bounds, window.rem_size()),
2580 |window| {
2581 window.with_tab_group(tab_group, |window| {
2582 if let Some(focus_handle) = &self.tracked_focus_handle {
2591 window.next_frame.tab_stops.insert(focus_handle);
2592 }
2593 if let Some(hitbox) = hitbox {
2594 #[cfg(debug_assertions)]
2595 self.paint_debug_info(
2596 global_id, hitbox, &style, window, cx,
2597 );
2598
2599 if let Some(drag) = cx.active_drag.as_ref() {
2600 if let Some(mouse_cursor) = drag.cursor_style {
2601 window.set_window_cursor_style(mouse_cursor);
2602 }
2603 } else {
2604 if let Some(mouse_cursor) = style.mouse_cursor {
2605 window.set_cursor_style(mouse_cursor, hitbox);
2606 }
2607 }
2608
2609 if let Some(group) = self.group.clone() {
2610 GroupHitboxes::push(group, hitbox.id, cx);
2611 }
2612
2613 if let Some(area) = self.window_control {
2614 window.insert_window_control_hitbox(
2615 area,
2616 hitbox.clone(),
2617 );
2618 }
2619
2620 self.paint_mouse_listeners(
2621 hitbox,
2622 element_state.as_mut(),
2623 window,
2624 cx,
2625 );
2626 self.paint_scroll_listener(hitbox, &style, window, cx);
2627 }
2628
2629 self.paint_keyboard_listeners(window, cx);
2630
2631 if window.a11y.is_active() {
2632 if let Some(global_id) = global_id {
2633 if !self.a11y_action_listeners.is_empty() {
2634 let node_id = global_id.accesskit_node_id();
2635 for (action, listener) in
2636 self.a11y_action_listeners.drain(..)
2637 {
2638 window.on_a11y_action(
2639 node_id, action, listener,
2640 );
2641 }
2642 }
2643 }
2644 }
2645
2646 f(&style, window, cx);
2647
2648 if let Some(_hitbox) = hitbox {
2649 #[cfg(any(feature = "inspector", debug_assertions))]
2650 window.insert_inspector_hitbox(
2651 _hitbox.id,
2652 _inspector_id,
2653 cx,
2654 );
2655
2656 if let Some(group) = self.group.as_ref() {
2657 GroupHitboxes::pop(group, cx);
2658 }
2659 }
2660 })
2661 },
2662 );
2663 });
2664 });
2665 });
2666
2667 ((), element_state)
2668 },
2669 );
2670 }
2671
2672 #[cfg(debug_assertions)]
2673 fn paint_debug_info(
2674 &self,
2675 global_id: Option<&GlobalElementId>,
2676 hitbox: &Hitbox,
2677 style: &Style,
2678 window: &mut Window,
2679 cx: &mut App,
2680 ) {
2681 use crate::{BorderStyle, TextAlign};
2682
2683 if let Some(global_id) = global_id
2684 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2685 && hitbox.is_hovered(window)
2686 {
2687 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2688 let element_id = format!("{global_id:?}");
2689 let str_len = element_id.len();
2690
2691 let render_debug_text = |window: &mut Window| {
2692 if let Some(text) = window
2693 .text_system()
2694 .shape_text(
2695 element_id.into(),
2696 FONT_SIZE,
2697 &[window.text_style().to_run(str_len)],
2698 None,
2699 None,
2700 )
2701 .ok()
2702 .and_then(|mut text| text.pop())
2703 {
2704 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2705 .ok();
2706
2707 let text_bounds = crate::Bounds {
2708 origin: hitbox.origin,
2709 size: text.size(FONT_SIZE),
2710 };
2711 if let Some(source_location) = self.source_location
2712 && text_bounds.contains(&window.mouse_position())
2713 && window.modifiers().secondary()
2714 {
2715 let secondary_held = window.modifiers().secondary();
2716 window.on_key_event({
2717 move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2718 if e.modifiers.secondary() != secondary_held
2719 && text_bounds.contains(&window.mouse_position())
2720 {
2721 window.refresh();
2722 }
2723 }
2724 });
2725
2726 let was_hovered = hitbox.is_hovered(window);
2727 let current_view = window.current_view();
2728 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
2729 window.on_mouse_event({
2730 let hitbox = hitbox.clone();
2731 move |_: &MouseMoveEvent, phase, window, cx| {
2732 if phase == DispatchPhase::Capture {
2733 let hovered = hitbox.is_hovered(window);
2734 if hovered != was_hovered {
2735 crate::fast::retained::invalidate_retained_subtrees(
2736 window, &subtrees,
2737 );
2738 cx.notify(current_view)
2739 }
2740 }
2741 }
2742 });
2743
2744 window.on_mouse_event({
2745 let hitbox = hitbox.clone();
2746 move |e: &crate::MouseDownEvent, phase, window, cx| {
2747 if text_bounds.contains(&e.position)
2748 && phase.capture()
2749 && hitbox.is_hovered(window)
2750 {
2751 cx.stop_propagation();
2752 let Ok(dir) = std::env::current_dir() else {
2753 return;
2754 };
2755
2756 eprintln!(
2757 "This element was created at:\n{}:{}:{}",
2758 dir.join(source_location.file()).to_string_lossy(),
2759 source_location.line(),
2760 source_location.column()
2761 );
2762 }
2763 }
2764 });
2765 window.paint_quad(crate::outline(
2766 crate::Bounds {
2767 origin: hitbox.origin
2768 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2769 size: crate::Size {
2770 width: text_bounds.size.width,
2771 height: crate::px(1.),
2772 },
2773 },
2774 crate::red(),
2775 BorderStyle::default(),
2776 ))
2777 }
2778 }
2779 };
2780
2781 window.with_text_style(
2782 Some(crate::TextStyleRefinement {
2783 color: Some(crate::red()),
2784 line_height: Some(FONT_SIZE.into()),
2785 background_color: Some(crate::white()),
2786 ..Default::default()
2787 }),
2788 render_debug_text,
2789 )
2790 }
2791 }
2792
2793 fn paint_mouse_listeners(
2794 &mut self,
2795 hitbox: &Hitbox,
2796 element_state: Option<&mut InteractiveElementState>,
2797 window: &mut Window,
2798 cx: &mut App,
2799 ) {
2800 let is_focused = self
2801 .tracked_focus_handle
2802 .as_ref()
2803 .map(|handle| handle.is_focused(window))
2804 .unwrap_or(false);
2805
2806 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2810 let hitbox = hitbox.clone();
2811 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2812 if phase == DispatchPhase::Bubble
2813 && hitbox.is_hovered(window)
2814 && !window.default_prevented()
2815 {
2816 window.focus(&focus_handle, cx);
2817 window.prevent_default();
2820 }
2821 });
2822 }
2823
2824 for listener in self.mouse_down_listeners.drain(..) {
2825 let hitbox = hitbox.clone();
2826 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2827 listener(event, phase, &hitbox, window, cx);
2828 })
2829 }
2830
2831 for listener in self.mouse_up_listeners.drain(..) {
2832 let hitbox = hitbox.clone();
2833 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2834 listener(event, phase, &hitbox, window, cx);
2835 })
2836 }
2837
2838 for listener in self.mouse_pressure_listeners.drain(..) {
2839 let hitbox = hitbox.clone();
2840 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2841 listener(event, phase, &hitbox, window, cx);
2842 })
2843 }
2844
2845 for listener in self.mouse_move_listeners.drain(..) {
2846 let hitbox = hitbox.clone();
2847 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2848 listener(event, phase, &hitbox, window, cx);
2849 })
2850 }
2851
2852 for listener in self.mouse_exit_listeners.drain(..) {
2853 let hitbox = hitbox.clone();
2854 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2855 listener(event, phase, &hitbox, window, cx);
2856 })
2857 }
2858
2859 for listener in self.file_drop_exit_listeners.drain(..) {
2860 let hitbox = hitbox.clone();
2861 window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
2862 listener(event, phase, &hitbox, window, cx);
2863 })
2864 }
2865
2866 for listener in self.scroll_wheel_listeners.drain(..) {
2867 let hitbox = hitbox.clone();
2868 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2869 listener(event, phase, &hitbox, window, cx);
2870 })
2871 }
2872
2873 for listener in self.pinch_listeners.drain(..) {
2874 let hitbox = hitbox.clone();
2875 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2876 listener(event, phase, &hitbox, window, cx);
2877 })
2878 }
2879
2880 if self.hover_style.is_some()
2881 || self.base_style.mouse_cursor.is_some()
2882 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2883 {
2884 let hitbox = hitbox.clone();
2885 let hover_state = self.hover_style.as_ref().and_then(|_| {
2886 element_state
2887 .as_ref()
2888 .and_then(|state| state.hover_state.as_ref())
2889 .cloned()
2890 });
2891 let current_view = window.current_view();
2892 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
2893
2894 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2895 let hovered = hitbox.is_hovered(window);
2896 let was_hovered = hover_state
2897 .as_ref()
2898 .is_some_and(|state| state.borrow().element);
2899 if phase == DispatchPhase::Capture && hovered != was_hovered {
2900 if let Some(hover_state) = &hover_state {
2901 hover_state.borrow_mut().element = hovered;
2902 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
2903 cx.notify(current_view);
2904 }
2905 }
2906 });
2907 }
2908
2909 if let Some(group_hover) = self.group_hover_style.as_ref() {
2910 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2911 let hover_state = element_state
2912 .as_ref()
2913 .and_then(|element| element.hover_state.as_ref())
2914 .cloned();
2915 let current_view = window.current_view();
2916 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
2917
2918 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2919 let group_hovered = group_hitbox_id.is_hovered(window);
2920 let was_group_hovered = hover_state
2921 .as_ref()
2922 .is_some_and(|state| state.borrow().group);
2923 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2924 if let Some(hover_state) = &hover_state {
2925 hover_state.borrow_mut().group = group_hovered;
2926 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
2927 cx.notify(current_view);
2928 }
2929 }
2930 });
2931 }
2932 }
2933
2934 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2935
2936 let mut drag_listener = mem::take(&mut self.drag_listener);
2937 let drop_listeners = mem::take(&mut self.drop_listeners);
2938 let click_listeners = mem::take(&mut self.click_listeners);
2939 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2940 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2941
2942 if !drop_listeners.is_empty() {
2943 let hitbox = hitbox.clone();
2944 window.on_mouse_event({
2945 move |_: &MouseUpEvent, phase, window, cx| {
2946 if let Some(drag) = &cx.active_drag
2947 && phase == DispatchPhase::Bubble
2948 && hitbox.is_hovered(window)
2949 {
2950 let drag_state_type = drag.value.as_ref().type_id();
2951 for (drop_state_type, listener) in &drop_listeners {
2952 if *drop_state_type == drag_state_type {
2953 let drag = cx
2954 .active_drag
2955 .take()
2956 .expect("checked for type drag state type above");
2957
2958 let mut can_drop = true;
2959 if let Some(predicate) = &can_drop_predicate {
2960 can_drop = predicate(drag.value.as_ref(), window, cx);
2961 }
2962
2963 if can_drop {
2964 listener(drag.value.as_ref(), window, cx);
2965 window.refresh();
2966 cx.stop_propagation();
2967 }
2968 }
2969 }
2970 }
2971 }
2972 });
2973 }
2974
2975 if let Some(element_state) = element_state {
2976 if !click_listeners.is_empty()
2977 || !aux_click_listeners.is_empty()
2978 || drag_listener.is_some()
2979 {
2980 let pending_mouse_down = element_state
2981 .pending_mouse_down
2982 .get_or_insert_with(Default::default)
2983 .clone();
2984
2985 let pending_keyboard_down = element_state
2986 .pending_keyboard_down
2987 .get_or_insert_with(Default::default)
2988 .clone();
2989
2990 let clicked_state = element_state
2991 .clicked_state
2992 .get_or_insert_with(Default::default)
2993 .clone();
2994
2995 window.on_mouse_event({
2996 let pending_mouse_down = pending_mouse_down.clone();
2997 let hitbox = hitbox.clone();
2998 let has_aux_click_listeners = !aux_click_listeners.is_empty();
2999 move |event: &MouseDownEvent, phase, window, _cx| {
3000 if phase == DispatchPhase::Bubble
3001 && (event.button == MouseButton::Left || has_aux_click_listeners)
3002 && hitbox.is_hovered(window)
3003 {
3004 *pending_mouse_down.borrow_mut() = Some(event.clone());
3005 window.refresh();
3006 }
3007 }
3008 });
3009
3010 window.on_mouse_event({
3011 let pending_mouse_down = pending_mouse_down.clone();
3012 let hitbox = hitbox.clone();
3013 move |event: &MouseMoveEvent, phase, window, cx| {
3014 if phase == DispatchPhase::Capture {
3015 return;
3016 }
3017
3018 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3019 if let Some(mouse_down) = pending_mouse_down.clone()
3020 && !cx.has_active_drag()
3021 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
3022 && let Some(listener) = drag_listener.take()
3023 && mouse_down.button == MouseButton::Left
3024 {
3025 *clicked_state.borrow_mut() = ElementClickedState::default();
3026 let cursor_offset = event.position - hitbox.origin;
3027 let drag = (listener.render)(
3028 listener.value.as_ref(),
3029 cursor_offset,
3030 window,
3031 cx,
3032 );
3033 let external_payload_source =
3034 listener.external_payload.map(|external_payload| {
3035 let value = listener.value.clone();
3036 Box::new(move |window: &mut Window, cx: &mut App| {
3037 external_payload(value.as_ref(), window, cx)
3038 })
3039 as ExternalDragPayloadSource
3040 });
3041 cx.active_drag = Some(AnyDrag {
3042 view: drag,
3043 value: listener.value,
3044 cursor_offset,
3045 cursor_style: drag_cursor_style,
3046 external_payload_source,
3047 });
3048 pending_mouse_down.take();
3049 window.refresh();
3050 cx.stop_propagation();
3051 }
3052 }
3053 });
3054
3055 if is_focused {
3056 window.on_key_event({
3066 let pending_keyboard_down = pending_keyboard_down.clone();
3067 move |event: &KeyDownEvent, phase, window, _cx| {
3068 if phase.bubble() && !window.default_prevented() {
3069 let stroke = &event.keystroke;
3070 let is_activation_key = (stroke.key.eq("enter")
3071 || stroke.key.eq("space"))
3072 && !stroke.modifiers.modified();
3073 *pending_keyboard_down.borrow_mut() =
3074 is_activation_key.then_some(window.focus_generation);
3075 }
3076 }
3077 });
3078
3079 window.on_key_event({
3081 let click_listeners = click_listeners.clone();
3082 let hitbox = hitbox.clone();
3083 move |event: &KeyUpEvent, phase, window, cx| {
3084 if phase.bubble() && !window.default_prevented() {
3085 let stroke = &event.keystroke;
3086 let keyboard_button = if stroke.key.eq("enter") {
3087 Some(KeyboardButton::Enter)
3088 } else if stroke.key.eq("space") {
3089 Some(KeyboardButton::Space)
3090 } else {
3091 None
3092 };
3093
3094 if let Some(button) = keyboard_button
3095 && !stroke.modifiers.modified()
3096 {
3097 let pending =
3098 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
3099 if pending != Some(window.focus_generation) {
3100 return;
3101 }
3102
3103 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
3104 button,
3105 bounds: hitbox.bounds,
3106 });
3107
3108 for listener in &click_listeners {
3109 listener(&click_event, window, cx);
3110 }
3111 } else {
3112 *pending_keyboard_down.borrow_mut() = None;
3116 }
3117 }
3118 }
3119 });
3120 }
3121
3122 window.on_mouse_event({
3123 let mut captured_mouse_down = None;
3124 let hitbox = hitbox.clone();
3125 move |event: &MouseUpEvent, phase, window, cx| match phase {
3126 DispatchPhase::Capture => {
3130 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3131 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
3132 captured_mouse_down = pending_mouse_down.take();
3133 window.refresh();
3134 } else if pending_mouse_down.is_some() {
3135 pending_mouse_down.take();
3141 window.refresh();
3142 }
3143 }
3144 DispatchPhase::Bubble => {
3146 if let Some(mouse_down) = captured_mouse_down.take() {
3147 let btn = mouse_down.button;
3148
3149 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
3150 down: mouse_down,
3151 up: event.clone(),
3152 });
3153
3154 match btn {
3155 MouseButton::Left => {
3156 for listener in &click_listeners {
3157 listener(&mouse_click, window, cx);
3158 }
3159 }
3160 _ => {
3161 for listener in &aux_click_listeners {
3162 listener(&mouse_click, window, cx);
3163 }
3164 }
3165 }
3166 }
3167 }
3168 }
3169 });
3170 }
3171
3172 if let Some(hover_listener) = self.hover_listener.take() {
3173 let was_hovered = element_state
3174 .hover_listener_state
3175 .get_or_insert_with(Default::default)
3176 .clone();
3177 let has_mouse_down = element_state
3178 .pending_mouse_down
3179 .get_or_insert_with(Default::default)
3180 .clone();
3181 let hover_listener = Rc::new(hover_listener);
3182 let hover_listener_state = was_hovered.clone();
3183 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3184 let mut was_hovered = hover_listener_state.borrow_mut();
3185 if is_hovered != *was_hovered {
3186 *was_hovered = is_hovered;
3187 drop(was_hovered);
3188 hover_listener(&is_hovered, window, cx);
3189 }
3190 };
3191 let hover_listener_mode = self.hover_listener_mode;
3192
3193 if has_mouse_down.borrow().is_none() {
3194 let is_hovered =
3195 !cx.has_active_drag() && hover_listener_mode.is_hovered(hitbox, window);
3196 if is_hovered != *was_hovered.borrow() {
3197 let update_hover = update_hover.clone();
3198 window.defer(cx, move |window, cx| {
3199 update_hover(is_hovered, window, cx);
3200 });
3201 }
3202 }
3203
3204 window.on_mouse_event({
3205 let update_hover = update_hover.clone();
3206 let hitbox = hitbox.clone();
3207 move |_: &MouseMoveEvent, phase, window, cx| {
3208 if phase == DispatchPhase::Bubble {
3209 let is_hovered = has_mouse_down.borrow().is_none()
3210 && !cx.has_active_drag()
3211 && hover_listener_mode.is_hovered(&hitbox, window);
3212 update_hover(is_hovered, window, cx);
3213 }
3214 }
3215 });
3216
3217 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3220 if phase == DispatchPhase::Bubble {
3221 update_hover(false, window, cx);
3222 }
3223 });
3224 }
3225
3226 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3227 let active_tooltip = element_state
3228 .active_tooltip
3229 .get_or_insert_with(Default::default)
3230 .clone();
3231 let pending_mouse_down = element_state
3232 .pending_mouse_down
3233 .get_or_insert_with(Default::default)
3234 .clone();
3235 let long_press_tooltip_active = element_state
3236 .long_press_tooltip_active
3237 .get_or_insert_with(Default::default)
3238 .clone();
3239
3240 let tooltip_is_hoverable = tooltip_builder.hoverable;
3241 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3242 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3243 });
3244 let check_is_hovered_during_prepaint = Rc::new({
3246 let pending_mouse_down = pending_mouse_down.clone();
3247 let source_bounds = hitbox.bounds;
3248 move |window: &Window| {
3249 !window.last_input_was_keyboard()
3250 && pending_mouse_down.borrow().is_none()
3251 && source_bounds.contains(&window.mouse_position())
3252 }
3253 });
3254 let check_is_hovered = Rc::new({
3255 let hitbox = hitbox.clone();
3256 move |window: &Window| {
3257 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3258 }
3259 });
3260 register_tooltip_mouse_handlers(
3261 &active_tooltip,
3262 self.tooltip_id,
3263 build_tooltip,
3264 check_is_hovered,
3265 check_is_hovered_during_prepaint,
3266 long_press_tooltip_active,
3267 self.tooltip_show_delay,
3268 window,
3269 );
3270 }
3271
3272 let active_state = element_state
3275 .clicked_state
3276 .get_or_insert_with(Default::default)
3277 .clone();
3278
3279 {
3280 let active_state = active_state.clone();
3281 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3282 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3283 *active_state.borrow_mut() = ElementClickedState::default();
3284 window.refresh();
3285 }
3286 });
3287 }
3288
3289 {
3290 let active_group_hitbox = self
3291 .group_active_style
3292 .as_ref()
3293 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3294 let hitbox = hitbox.clone();
3295 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3296 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3297 let group_hovered = active_group_hitbox
3298 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3299 let element_hovered = hitbox.is_hovered(window);
3300 if group_hovered || element_hovered {
3301 *active_state.borrow_mut() = ElementClickedState {
3302 group: group_hovered,
3303 element: element_hovered,
3304 };
3305 window.refresh();
3306 }
3307 }
3308 });
3309 }
3310 }
3311 }
3312
3313 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3314 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3315 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3316 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3317 let action_listeners = mem::take(&mut self.action_listeners);
3318 if let Some(context) = self.key_context.clone() {
3319 window.set_key_context(context);
3320 }
3321
3322 for listener in key_down_listeners {
3323 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3324 listener(event, phase, window, cx);
3325 })
3326 }
3327
3328 for listener in key_up_listeners {
3329 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3330 listener(event, phase, window, cx);
3331 })
3332 }
3333
3334 for listener in modifiers_changed_listeners {
3335 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3336 listener(event, window, cx);
3337 })
3338 }
3339
3340 for (action_type, listener) in action_listeners {
3341 window.on_action(action_type, listener)
3342 }
3343 }
3344
3345 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3346 let group_hitbox = self
3347 .group_hover_style
3348 .as_ref()
3349 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3350
3351 if let Some(group_hitbox) = group_hitbox {
3352 let was_hovered = group_hitbox.is_hovered(window);
3353 let current_view = window.current_view();
3354 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
3355 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3356 let hovered = group_hitbox.is_hovered(window);
3357 if phase == DispatchPhase::Capture && hovered != was_hovered {
3358 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
3359 cx.notify(current_view);
3360 }
3361 });
3362 }
3363 }
3364
3365 fn paint_scroll_listener(
3366 &self,
3367 hitbox: &Hitbox,
3368 style: &Style,
3369 window: &mut Window,
3370 _cx: &mut App,
3371 ) {
3372 if let Some(scroll_offset) = self.scroll_offset.clone() {
3373 let ongoing_scroll = self.ongoing_scroll.clone();
3374 let overflow = style.overflow;
3375 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3376 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3377 let line_height = window.line_height();
3378 let hitbox = hitbox.clone();
3379 let current_view = window.current_view();
3380 let subtrees = crate::fast::retained::enclosing_retained_subtrees(window);
3381 let fast_container = crate::fast::layers::invalidate::painted_container(window, self);
3382 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
3383 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3384 let mut scroll_offset = scroll_offset.borrow_mut();
3385 let old_scroll_offset = *scroll_offset;
3386 let mut delta = event.delta.pixel_delta(line_height);
3387
3388 if restrict_scroll_to_axis
3389 && event.delta.precise()
3390 && let Some(ongoing_scroll) = &ongoing_scroll
3391 {
3392 ongoing_scroll
3393 .borrow_mut()
3394 .filter(&mut delta, event.touch_phase);
3395 }
3396
3397 let mut delta_x = match overflow.x {
3398 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3399 Overflow::Scroll
3400 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3401 {
3402 delta.y
3403 }
3404 _ => Pixels::ZERO,
3405 };
3406 let mut delta_y = match overflow.y {
3407 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3408 Overflow::Scroll
3409 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3410 {
3411 delta.x
3412 }
3413 _ => Pixels::ZERO,
3414 };
3415 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3416 if delta_x.abs() > delta_y.abs() {
3417 delta_y = Pixels::ZERO;
3418 } else {
3419 delta_x = Pixels::ZERO;
3420 }
3421 }
3422 scroll_offset.y += delta_y;
3423 scroll_offset.x += delta_x;
3424 if *scroll_offset != old_scroll_offset {
3425 crate::fast::retained::invalidate_retained_subtrees(window, &subtrees);
3426 crate::fast::layers::invalidate::note_scrolled(window, &fast_container);
3427 cx.notify(current_view);
3428 }
3429 }
3430 });
3431 }
3432 }
3433
3434 pub fn compute_style(
3436 &self,
3437 global_id: Option<&GlobalElementId>,
3438 hitbox: Option<&Hitbox>,
3439 window: &mut Window,
3440 cx: &mut App,
3441 ) -> Style {
3442 window.with_optional_element_state(global_id, |element_state, window| {
3443 let mut element_state =
3444 element_state.map(|element_state| element_state.unwrap_or_default());
3445 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3446 (style, element_state)
3447 })
3448 }
3449
3450 fn compute_style_internal(
3452 &self,
3453 hitbox: Option<&Hitbox>,
3454 element_state: Option<&mut InteractiveElementState>,
3455 window: &mut Window,
3456 cx: &mut App,
3457 ) -> Style {
3458 let mut style = Style::default();
3459 style.refine(&self.base_style);
3460
3461 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3462 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3463 && focus_handle.within_focused(window, cx)
3464 {
3465 style.refine(in_focus_style);
3466 }
3467
3468 if let Some(focus_style) = self.focus_style.as_ref()
3469 && focus_handle.is_focused(window)
3470 {
3471 style.refine(focus_style);
3472 }
3473
3474 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3475 && focus_handle.is_focused(window)
3476 && window.last_input_was_keyboard()
3477 {
3478 style.refine(focus_visible_style);
3479 }
3480 }
3481
3482 if !cx.has_active_drag() {
3483 if let Some(group_hover) = self.group_hover_style.as_ref() {
3484 let is_group_hovered =
3485 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3486 !window.last_input_was_touch() && group_hitbox_id.is_hovered(window)
3487 } else if let Some(element_state) = element_state.as_ref() {
3488 !window.last_input_was_touch()
3489 && element_state
3490 .hover_state
3491 .as_ref()
3492 .map(|state| state.borrow().group)
3493 .unwrap_or(false)
3494 } else {
3495 false
3496 };
3497
3498 if is_group_hovered {
3499 style.refine(&group_hover.style);
3500 }
3501 }
3502
3503 if let Some(hover_style) = self.hover_style.as_ref() {
3504 let is_hovered = if let Some(hitbox) = hitbox {
3505 !window.last_input_was_touch() && hitbox.is_hovered(window)
3506 } else if let Some(element_state) = element_state.as_ref() {
3507 !window.last_input_was_touch()
3508 && element_state
3509 .hover_state
3510 .as_ref()
3511 .map(|state| state.borrow().element)
3512 .unwrap_or(false)
3513 } else {
3514 false
3515 };
3516
3517 if is_hovered {
3518 style.refine(hover_style);
3519 }
3520 }
3521 }
3522
3523 if let Some(hitbox) = hitbox {
3524 if let Some(drag) = cx.active_drag.take() {
3525 let mut can_drop = true;
3526 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3527 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3528 }
3529
3530 if can_drop {
3531 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3532 if let Some(group_hitbox_id) =
3533 GroupHitboxes::get(&group_drag_style.group, cx)
3534 && *state_type == drag.value.as_ref().type_id()
3535 && group_hitbox_id.is_hovered(window)
3536 {
3537 style.refine(&group_drag_style.style);
3538 }
3539 }
3540
3541 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3542 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3543 {
3544 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3545 }
3546 }
3547 }
3548
3549 style.mouse_cursor = drag.cursor_style;
3550 cx.active_drag = Some(drag);
3551 }
3552 }
3553
3554 if let Some(element_state) = element_state {
3555 let clicked_state = element_state
3556 .clicked_state
3557 .get_or_insert_with(Default::default)
3558 .borrow();
3559 if clicked_state.group
3560 && let Some(group) = self.group_active_style.as_ref()
3561 {
3562 style.refine(&group.style)
3563 }
3564
3565 if let Some(active_style) = self.active_style.as_ref()
3566 && clicked_state.element
3567 {
3568 style.refine(active_style)
3569 }
3570 }
3571
3572 style
3573 }
3574
3575 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3576 if let Some(id) = &self.aria.author_id {
3577 node.set_author_id(id.to_string());
3578 }
3579 if let Some(label) = &self.aria.label {
3580 node.set_label(label.to_string());
3581 }
3582 if let Some(description) = &self.aria.description {
3583 node.set_description(description.to_string());
3584 }
3585 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3586 node.set_keyboard_shortcut(keyshortcuts.to_string());
3587 }
3588 if let Some(selected) = self.aria.selected {
3589 node.set_selected(selected);
3590 }
3591 if let Some(expanded) = self.aria.expanded {
3592 node.set_expanded(expanded);
3593 }
3594 if let Some(toggled) = self.aria.toggled {
3595 node.set_toggled(toggled);
3596 }
3597 if let Some(value) = self.aria.numeric_value {
3598 node.set_numeric_value(value);
3599 }
3600 if let Some(value) = self.aria.min_numeric_value {
3601 node.set_min_numeric_value(value);
3602 }
3603 if let Some(value) = self.aria.max_numeric_value {
3604 node.set_max_numeric_value(value);
3605 }
3606 if let Some(step) = self.aria.numeric_value_step {
3607 node.set_numeric_value_step(step);
3608 }
3609 if let Some(value) = &self.aria.value {
3610 node.set_value(value.to_string());
3611 }
3612 if let Some(placeholder) = &self.aria.placeholder {
3613 node.set_placeholder(placeholder.to_string());
3614 }
3615 if let Some(orientation) = self.aria.orientation {
3616 node.set_orientation(orientation);
3617 }
3618 if let Some(level) = self.aria.level {
3619 node.set_level(level);
3620 }
3621 if let Some(position) = self.aria.position_in_set {
3622 node.set_position_in_set(position);
3623 }
3624 if let Some(size) = self.aria.size_of_set {
3625 node.set_size_of_set(size);
3626 }
3627 if let Some(index) = self.aria.row_index {
3628 node.set_row_index(index);
3629 }
3630 if let Some(index) = self.aria.column_index {
3631 node.set_column_index(index);
3632 }
3633 if let Some(count) = self.aria.row_count {
3634 node.set_row_count(count);
3635 }
3636 if let Some(count) = self.aria.column_count {
3637 node.set_column_count(count);
3638 }
3639 if !self.click_listeners.is_empty() {
3640 node.add_action(accesskit::Action::Click);
3641 }
3642 if self.tracked_focus_handle.is_some() || self.focusable {
3643 node.add_action(accesskit::Action::Focus);
3644 }
3645 for (action, _) in &self.a11y_action_listeners {
3646 node.add_action(*action);
3647 }
3648 }
3649}
3650
3651#[derive(Default)]
3654pub struct InteractiveElementState {
3655 pub(crate) focus_handle: Option<FocusHandle>,
3656 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3657 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3658 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3659 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3660 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3668 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3669 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3670 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3671 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3672}
3673
3674#[derive(Copy, Clone, Default, Eq, PartialEq)]
3676pub struct ElementClickedState {
3677 pub group: bool,
3679
3680 pub element: bool,
3682}
3683
3684impl ElementClickedState {
3685 fn is_clicked(&self) -> bool {
3686 self.group || self.element
3687 }
3688}
3689
3690#[derive(Copy, Clone, Default, Eq, PartialEq)]
3692pub struct ElementHoverState {
3693 pub group: bool,
3695
3696 pub element: bool,
3698}
3699
3700pub(crate) enum ActiveTooltip {
3701 WaitingForShow { _task: Task<()> },
3703 Visible {
3705 tooltip: AnyTooltip,
3706 is_hoverable: bool,
3707 },
3708 WaitingForHide {
3711 tooltip: AnyTooltip,
3712 _task: Task<()>,
3713 },
3714}
3715
3716pub(crate) fn clear_active_tooltip(
3717 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3718 window: &mut Window,
3719) {
3720 match active_tooltip.borrow_mut().take() {
3721 None => {}
3722 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3723 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3724 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3725 }
3726}
3727
3728pub(crate) fn clear_active_tooltip_if_not_hoverable(
3729 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3730 window: &mut Window,
3731) {
3732 let should_clear = match active_tooltip.borrow().as_ref() {
3733 None => false,
3734 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3735 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3736 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3737 };
3738 if should_clear {
3739 active_tooltip.borrow_mut().take();
3740 window.refresh();
3741 }
3742}
3743
3744pub(crate) fn set_tooltip_on_window(
3745 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3746 window: &mut Window,
3747) -> Option<TooltipId> {
3748 let tooltip = match active_tooltip.borrow().as_ref() {
3749 None => return None,
3750 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3751 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3752 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3753 };
3754 Some(window.set_tooltip(tooltip))
3755}
3756
3757pub(crate) fn register_tooltip_mouse_handlers(
3758 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3759 tooltip_id: Option<TooltipId>,
3760 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3761 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3762 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3763 long_press_tooltip_active: Rc<Cell<bool>>,
3764 show_delay: Option<Duration>,
3765 window: &mut Window,
3766) {
3767 let current_view = window.current_view();
3768 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3769
3770 window.on_mouse_event({
3771 let active_tooltip = active_tooltip.clone();
3772 let build_tooltip = build_tooltip.clone();
3773 let check_is_hovered = check_is_hovered.clone();
3774 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3775 move |_: &MouseMoveEvent, phase, window, cx| {
3776 handle_tooltip_mouse_move(
3777 &active_tooltip,
3778 &build_tooltip,
3779 &check_is_hovered,
3780 &check_is_hovered_during_prepaint,
3781 tooltip_id,
3782 current_view,
3783 phase,
3784 show_delay,
3785 window,
3786 cx,
3787 )
3788 }
3789 });
3790
3791 window.on_mouse_event({
3792 let active_tooltip = active_tooltip.clone();
3793 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3794 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3795 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3796 }
3797 }
3798 });
3799
3800 window.on_mouse_event({
3801 let active_tooltip = active_tooltip.clone();
3802 let build_tooltip = build_tooltip.clone();
3803 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3804 move |event: &LongPressEvent, phase, window, cx| {
3805 if !phase.bubble() {
3806 return;
3807 }
3808
3809 match event.phase {
3810 TouchPhase::Started if !window.default_prevented() && check_is_hovered(window) => {
3811 if show_tooltip(
3812 &active_tooltip,
3813 &build_tooltip,
3814 &check_is_hovered_during_prepaint,
3815 Some(long_press_tooltip_active.clone()),
3816 window,
3817 cx,
3818 ) {
3819 long_press_tooltip_active.set(true);
3820 window.prevent_default();
3821 cx.stop_propagation();
3822 }
3823 }
3824 TouchPhase::Ended | TouchPhase::Cancelled
3825 if long_press_tooltip_active.replace(false) =>
3826 {
3827 clear_active_tooltip(&active_tooltip, window);
3828 cx.stop_propagation();
3829 }
3830 TouchPhase::Started
3831 | TouchPhase::Moved
3832 | TouchPhase::Ended
3833 | TouchPhase::Cancelled => {}
3834 }
3835 }
3836 });
3837
3838 window.on_mouse_event({
3839 let active_tooltip = active_tooltip.clone();
3840 move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
3841 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3842 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3843 }
3844 }
3845 });
3846}
3847
3848fn handle_tooltip_mouse_move(
3860 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3861 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3862 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3863 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3864 tooltip_id: Option<TooltipId>,
3865 current_view: EntityId,
3866 phase: DispatchPhase,
3867 show_delay: Duration,
3868 window: &mut Window,
3869 cx: &mut App,
3870) {
3871 enum Action {
3874 None,
3875 CancelShow,
3876 ScheduleShow,
3877 CheckVisible,
3878 }
3879
3880 let action = match active_tooltip.borrow().as_ref() {
3881 None => {
3882 let is_hovered = check_is_hovered(window);
3883 if is_hovered && phase.bubble() {
3884 Action::ScheduleShow
3885 } else {
3886 Action::None
3887 }
3888 }
3889 Some(ActiveTooltip::WaitingForShow { .. }) => {
3890 let is_hovered = check_is_hovered(window);
3891 if is_hovered {
3892 Action::None
3893 } else {
3894 Action::CancelShow
3895 }
3896 }
3897 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3898 if phase.capture()
3899 && !check_is_hovered(window)
3900 && (!*is_hoverable
3901 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3902 {
3903 Action::CheckVisible
3904 } else {
3905 Action::None
3906 }
3907 }
3908 Some(ActiveTooltip::WaitingForHide { .. }) => {
3909 if phase.capture()
3910 && (check_is_hovered(window)
3911 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3912 {
3913 Action::CheckVisible
3914 } else {
3915 Action::None
3916 }
3917 }
3918 };
3919
3920 match action {
3921 Action::None => {}
3922 Action::CancelShow => {
3923 active_tooltip.borrow_mut().take();
3925 }
3926 Action::ScheduleShow => {
3927 let delayed_show_task = window.spawn(cx, {
3928 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3929 let build_tooltip = build_tooltip.clone();
3930 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3931 async move |cx| {
3932 cx.background_executor().timer(show_delay).await;
3933 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3934 return;
3935 };
3936 cx.update(|window, cx| {
3937 show_tooltip(
3938 &active_tooltip,
3939 &build_tooltip,
3940 &check_is_hovered_during_prepaint,
3941 None,
3942 window,
3943 cx,
3944 );
3945 })
3946 .ok();
3947 }
3948 });
3949 active_tooltip
3950 .borrow_mut()
3951 .replace(ActiveTooltip::WaitingForShow {
3952 _task: delayed_show_task,
3953 });
3954 }
3955 Action::CheckVisible => cx.notify(current_view),
3956 }
3957}
3958
3959fn show_tooltip(
3960 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3961 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3962 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3963 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3964 window: &mut Window,
3965 cx: &mut App,
3966) -> bool {
3967 let new_tooltip = build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3968 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3969 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3970 ActiveTooltip::Visible {
3971 tooltip: AnyTooltip {
3972 view,
3973 mouse_position: window.mouse_position(),
3974 check_visible_and_update: Rc::new(move |tooltip_bounds, window, cx| {
3975 if long_press_tooltip_active
3976 .as_ref()
3977 .is_some_and(|active| active.get())
3978 {
3979 return true;
3980 }
3981 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3982 return false;
3983 };
3984 handle_tooltip_check_visible_and_update(
3985 &active_tooltip,
3986 tooltip_is_hoverable,
3987 &check_is_hovered_during_prepaint,
3988 tooltip_bounds,
3989 window,
3990 cx,
3991 )
3992 }),
3993 },
3994 is_hoverable: tooltip_is_hoverable,
3995 }
3996 });
3997 let did_show = new_tooltip.is_some();
3998 *active_tooltip.borrow_mut() = new_tooltip;
3999 window.refresh();
4000 did_show
4001}
4002
4003fn handle_tooltip_check_visible_and_update(
4007 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
4008 tooltip_is_hoverable: bool,
4009 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
4010 tooltip_bounds: Bounds<Pixels>,
4011 window: &mut Window,
4012 cx: &mut App,
4013) -> bool {
4014 enum Action {
4017 None,
4018 Hide,
4019 ScheduleHide(AnyTooltip),
4020 CancelHide(AnyTooltip),
4021 }
4022
4023 let is_hovered = check_is_hovered(window)
4024 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
4025 let action = match active_tooltip.borrow().as_ref() {
4026 Some(ActiveTooltip::Visible { tooltip, .. }) => {
4027 if is_hovered {
4028 Action::None
4029 } else {
4030 if tooltip_is_hoverable {
4031 Action::ScheduleHide(tooltip.clone())
4032 } else {
4033 Action::Hide
4034 }
4035 }
4036 }
4037 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
4038 if is_hovered {
4039 Action::CancelHide(tooltip.clone())
4040 } else {
4041 Action::None
4042 }
4043 }
4044 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
4045 };
4046
4047 match action {
4048 Action::None => {}
4049 Action::Hide => clear_active_tooltip(active_tooltip, window),
4050 Action::ScheduleHide(tooltip) => {
4051 let delayed_hide_task = window.spawn(cx, {
4052 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4053 async move |cx| {
4054 cx.background_executor()
4055 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
4056 .await;
4057 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4058 return;
4059 };
4060 if active_tooltip.borrow_mut().take().is_some() {
4061 cx.update(|window, _cx| window.refresh()).ok();
4062 }
4063 }
4064 });
4065 active_tooltip
4066 .borrow_mut()
4067 .replace(ActiveTooltip::WaitingForHide {
4068 tooltip,
4069 _task: delayed_hide_task,
4070 });
4071 }
4072 Action::CancelHide(tooltip) => {
4073 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
4075 tooltip,
4076 is_hoverable: true,
4077 });
4078 }
4079 }
4080
4081 active_tooltip.borrow().is_some()
4082}
4083
4084#[derive(Default)]
4085pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
4086
4087impl Global for GroupHitboxes {}
4088
4089impl GroupHitboxes {
4090 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
4091 cx.default_global::<Self>()
4092 .0
4093 .get(name)
4094 .and_then(|bounds_stack| bounds_stack.last())
4095 .cloned()
4096 }
4097
4098 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
4099 cx.default_global::<Self>()
4100 .0
4101 .entry(name)
4102 .or_default()
4103 .push(hitbox_id);
4104 }
4105
4106 pub fn pop(name: &SharedString, cx: &mut App) {
4107 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
4108 }
4109}
4110
4111pub struct Stateful<E> {
4113 pub(crate) element: E,
4114}
4115
4116impl<E> Styled for Stateful<E>
4117where
4118 E: Styled,
4119{
4120 fn style(&mut self) -> &mut StyleRefinement {
4121 self.element.style()
4122 }
4123}
4124
4125impl<E> StatefulInteractiveElement for Stateful<E>
4126where
4127 E: Element,
4128 Self: InteractiveElement,
4129{
4130}
4131
4132impl<E> InteractiveElement for Stateful<E>
4133where
4134 E: InteractiveElement,
4135{
4136 fn interactivity(&mut self) -> &mut Interactivity {
4137 self.element.interactivity()
4138 }
4139}
4140
4141impl<E> Element for Stateful<E>
4142where
4143 E: Element,
4144{
4145 type RequestLayoutState = E::RequestLayoutState;
4146 type PrepaintState = E::PrepaintState;
4147
4148 fn id(&self) -> Option<ElementId> {
4149 self.element.id()
4150 }
4151
4152 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4153 self.element.source_location()
4154 }
4155
4156 fn a11y_role(&self) -> Option<accesskit::Role> {
4157 self.element.a11y_role()
4158 }
4159
4160 fn write_a11y_info(&self, node: &mut accesskit::Node) {
4161 self.element.write_a11y_info(node);
4162 }
4163
4164 fn a11y_synthetic_children(
4165 &mut self,
4166 prepaint: &mut Self::PrepaintState,
4167 builder: &mut crate::A11ySubtreeBuilder,
4168 ) {
4169 self.element.a11y_synthetic_children(prepaint, builder);
4170 }
4171
4172 fn request_layout(
4173 &mut self,
4174 id: Option<&GlobalElementId>,
4175 inspector_id: Option<&InspectorElementId>,
4176 window: &mut Window,
4177 cx: &mut App,
4178 ) -> (LayoutId, Self::RequestLayoutState) {
4179 self.element.request_layout(id, inspector_id, window, cx)
4180 }
4181
4182 fn prepaint(
4183 &mut self,
4184 id: Option<&GlobalElementId>,
4185 inspector_id: Option<&InspectorElementId>,
4186 bounds: Bounds<Pixels>,
4187 state: &mut Self::RequestLayoutState,
4188 window: &mut Window,
4189 cx: &mut App,
4190 ) -> E::PrepaintState {
4191 self.element
4192 .prepaint(id, inspector_id, bounds, state, window, cx)
4193 }
4194
4195 fn paint(
4196 &mut self,
4197 id: Option<&GlobalElementId>,
4198 inspector_id: Option<&InspectorElementId>,
4199 bounds: Bounds<Pixels>,
4200 request_layout: &mut Self::RequestLayoutState,
4201 prepaint: &mut Self::PrepaintState,
4202 window: &mut Window,
4203 cx: &mut App,
4204 ) {
4205 self.element.paint(
4206 id,
4207 inspector_id,
4208 bounds,
4209 request_layout,
4210 prepaint,
4211 window,
4212 cx,
4213 );
4214 }
4215}
4216
4217impl<E> IntoElement for Stateful<E>
4218where
4219 E: Element,
4220{
4221 type Element = Self;
4222
4223 fn into_element(self) -> Self::Element {
4224 self
4225 }
4226}
4227
4228impl<E> ParentElement for Stateful<E>
4229where
4230 E: ParentElement,
4231{
4232 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4233 self.element.extend(elements)
4234 }
4235}
4236
4237#[derive(Clone)]
4240pub struct ScrollAnchor {
4241 handle: ScrollHandle,
4242 last_origin: Rc<RefCell<Point<Pixels>>>,
4243}
4244
4245impl ScrollAnchor {
4246 pub fn for_handle(handle: ScrollHandle) -> Self {
4248 Self {
4249 handle,
4250 last_origin: Default::default(),
4251 }
4252 }
4253 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4255 let this = self.clone();
4256
4257 window.on_next_frame(move |_, _| {
4258 let viewport_bounds = this.handle.bounds();
4259 let self_bounds = *this.last_origin.borrow();
4260 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4261 });
4262 }
4263}
4264
4265#[derive(Default, Debug)]
4266pub(crate) struct ScrollHandleState {
4267 pub(crate) offset: Rc<RefCell<Point<Pixels>>>,
4268 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4269 bounds: Bounds<Pixels>,
4270 pub(crate) max_offset: Point<Pixels>,
4271 child_bounds: Vec<Bounds<Pixels>>,
4272 pub(crate) scroll_to_bottom: bool,
4273 overflow: Point<Overflow>,
4274 active_item: Option<ScrollActiveItem>,
4275 pub(crate) version: crate::fast::dependencies::StateVersion,
4276}
4277
4278#[derive(Default, Debug, Clone, Copy)]
4279struct ScrollActiveItem {
4280 index: usize,
4281 strategy: ScrollStrategy,
4282}
4283
4284#[derive(Default, Debug, Clone, Copy)]
4285enum ScrollStrategy {
4286 #[default]
4287 FirstVisible,
4288 Top,
4289}
4290
4291#[derive(Clone, Debug)]
4295pub struct ScrollHandle(pub(crate) Rc<RefCell<ScrollHandleState>>);
4296
4297impl Default for ScrollHandle {
4298 fn default() -> Self {
4299 Self::new()
4300 }
4301}
4302
4303impl ScrollHandle {
4304 pub fn new() -> Self {
4306 Self(Rc::default())
4307 }
4308
4309 pub fn offset(&self) -> Point<Pixels> {
4311 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
4312 *self.0.borrow().offset.borrow()
4313 }
4314
4315 pub fn max_offset(&self) -> Point<Pixels> {
4317 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
4318 self.0.borrow().max_offset
4319 }
4320
4321 pub fn top_item(&self) -> usize {
4323 let state = self.0.borrow();
4324 crate::fast::layers::invalidate::note_offset_read(&state.version);
4325 let top = state.bounds.top() - state.offset.borrow().y;
4326
4327 match state.child_bounds.binary_search_by(|bounds| {
4328 if top < bounds.top() {
4329 Ordering::Greater
4330 } else if top > bounds.bottom() {
4331 Ordering::Less
4332 } else {
4333 Ordering::Equal
4334 }
4335 }) {
4336 Ok(ix) => ix,
4337 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4338 }
4339 }
4340
4341 pub fn bottom_item(&self) -> usize {
4343 let state = self.0.borrow();
4344 crate::fast::layers::invalidate::note_offset_read(&state.version);
4345 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4346
4347 match state.child_bounds.binary_search_by(|bounds| {
4348 if bottom < bounds.top() {
4349 Ordering::Greater
4350 } else if bottom > bounds.bottom() {
4351 Ordering::Less
4352 } else {
4353 Ordering::Equal
4354 }
4355 }) {
4356 Ok(ix) => ix,
4357 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4358 }
4359 }
4360
4361 pub fn bounds(&self) -> Bounds<Pixels> {
4363 crate::fast::layers::input::moved(&self.0, Some(self.0.borrow().bounds)).unwrap_or_default()
4364 }
4365
4366 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4368 crate::fast::layers::invalidate::note_offset_read(&self.0.borrow().version);
4369 crate::fast::layers::input::moved(&self.0, self.0.borrow().child_bounds.get(ix).cloned())
4370 }
4371
4372 pub fn scroll_to_item(&self, ix: usize) {
4374 let mut state = self.0.borrow_mut();
4375 crate::fast::dependencies::StateVersion::bump(&state.version);
4376 state.active_item = Some(ScrollActiveItem {
4377 index: ix,
4378 strategy: ScrollStrategy::default(),
4379 });
4380 }
4381
4382 pub fn scroll_to_top_of_item(&self, ix: usize) {
4385 let mut state = self.0.borrow_mut();
4386 crate::fast::dependencies::StateVersion::bump(&state.version);
4387 state.active_item = Some(ScrollActiveItem {
4388 index: ix,
4389 strategy: ScrollStrategy::Top,
4390 });
4391 }
4392
4393 fn scroll_to_active_item(&self) {
4397 let mut state = self.0.borrow_mut();
4398
4399 let Some(active_item) = state.active_item else {
4400 return;
4401 };
4402
4403 let active_item = match state.child_bounds.get(active_item.index) {
4404 Some(bounds) => {
4405 let mut scroll_offset = state.offset.borrow_mut();
4406
4407 match active_item.strategy {
4408 ScrollStrategy::FirstVisible => {
4409 if state.overflow.y == Overflow::Scroll {
4410 let child_height = bounds.size.height;
4411 let viewport_height = state.bounds.size.height;
4412 if child_height > viewport_height {
4413 scroll_offset.y = state.bounds.top() - bounds.top();
4414 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4415 scroll_offset.y = state.bounds.top() - bounds.top();
4416 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4417 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4418 }
4419 }
4420 }
4421 ScrollStrategy::Top => {
4422 scroll_offset.y = state.bounds.top() - bounds.top();
4423 }
4424 }
4425
4426 if state.overflow.x == Overflow::Scroll {
4427 let child_width = bounds.size.width;
4428 let viewport_width = state.bounds.size.width;
4429 if child_width > viewport_width {
4430 scroll_offset.x = state.bounds.left() - bounds.left();
4431 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4432 scroll_offset.x = state.bounds.left() - bounds.left();
4433 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4434 scroll_offset.x = state.bounds.right() - bounds.right();
4435 }
4436 }
4437 None
4438 }
4439 None => Some(active_item),
4440 };
4441 state.active_item = active_item;
4442 }
4443
4444 pub fn scroll_to_bottom(&self) {
4446 let mut state = self.0.borrow_mut();
4447 crate::fast::layers::scroll_to_bottom::note_scroll_to_bottom(self, &state);
4448 state.scroll_to_bottom = true;
4449 }
4450
4451 pub fn set_offset(&self, mut position: Point<Pixels>) {
4455 let state = self.0.borrow();
4456 crate::fast::layers::invalidate::offset_set(
4457 &state.version,
4458 *state.offset.borrow() != position,
4459 );
4460 *state.offset.borrow_mut() = position;
4461 }
4462
4463 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4465 let ix = self.top_item();
4466 let state = self.0.borrow();
4467
4468 if let Some(child_bounds) = state.child_bounds.get(ix) {
4469 (
4470 ix,
4471 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4472 )
4473 } else {
4474 (ix, px(0.))
4475 }
4476 }
4477
4478 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4480 let ix = self.bottom_item();
4481 let state = self.0.borrow();
4482
4483 if let Some(child_bounds) = state.child_bounds.get(ix) {
4484 (
4485 ix,
4486 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4487 )
4488 } else {
4489 (ix, px(0.))
4490 }
4491 }
4492
4493 pub fn children_count(&self) -> usize {
4495 self.0.borrow().child_bounds.len()
4496 }
4497}
4498
4499#[cfg(test)]
4500mod tests {
4501 use super::*;
4502 use crate::{
4503 AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, Keystroke,
4504 MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas, util::FluentBuilder as _,
4505 };
4506 use std::{cell::Cell, rc::Weak};
4507
4508 struct GroupHoverTestView {
4509 render_count: Rc<Cell<usize>>,
4510 anonymous_paint_count: Rc<Cell<usize>>,
4511 stateful_width: Rc<Cell<Pixels>>,
4512 }
4513
4514 impl Render for GroupHoverTestView {
4515 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4516 self.render_count.set(self.render_count.get() + 1);
4517 let anonymous_paint_count = self.anonymous_paint_count.clone();
4518 let stateful_width = self.stateful_width.clone();
4519 div().size_full().child(
4520 div()
4521 .ml(px(20.))
4522 .mt(px(20.))
4523 .size(px(50.))
4524 .relative()
4525 .group("hover-group")
4526 .child(
4527 div()
4528 .absolute()
4529 .size_full()
4530 .invisible()
4531 .group_hover("hover-group", |style| style.visible())
4532 .child(canvas(
4533 |_, _, _| {},
4534 move |_, _, _, _| {
4535 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4536 },
4537 )),
4538 )
4539 .child(
4540 div()
4541 .id("stateful-group-hover-target")
4542 .absolute()
4543 .top_0()
4544 .left_0()
4545 .size(px(10.))
4546 .group_hover("hover-group", |style| style.size(px(20.)))
4547 .child(canvas(
4548 move |bounds, _, _| stateful_width.set(bounds.size.width),
4549 |_, _, _, _| {},
4550 )),
4551 ),
4552 )
4553 }
4554 }
4555
4556 #[gpui::test]
4557 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4558 let render_count = Rc::new(Cell::new(0));
4559 let anonymous_paint_count = Rc::new(Cell::new(0));
4560 let stateful_width = Rc::new(Cell::new(px(0.)));
4561 let window = cx.add_window({
4562 let render_count = render_count.clone();
4563 let anonymous_paint_count = anonymous_paint_count.clone();
4564 let stateful_width = stateful_width.clone();
4565 move |_, _| GroupHoverTestView {
4566 render_count,
4567 anonymous_paint_count,
4568 stateful_width,
4569 }
4570 });
4571 let window = AnyWindowHandle::from(window);
4572
4573 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4574 .unwrap();
4575 assert_eq!(anonymous_paint_count.get(), 0);
4576 assert_eq!(stateful_width.get(), px(10.));
4577
4578 let move_mouse = |cx: &mut TestAppContext, position| {
4579 cx.update_window(window, |_, window, cx| {
4580 window.simulate_mouse_move(position, cx)
4581 })
4582 .unwrap();
4583 };
4584
4585 let initial_render_count = render_count.get();
4586 move_mouse(cx, point(px(25.), px(25.)));
4587 assert_eq!(render_count.get(), initial_render_count + 1);
4588 assert_eq!(anonymous_paint_count.get(), 1);
4589 assert_eq!(stateful_width.get(), px(20.));
4590
4591 move_mouse(cx, point(px(30.), px(30.)));
4592 assert_eq!(render_count.get(), initial_render_count + 1);
4593 assert_eq!(anonymous_paint_count.get(), 1);
4594 assert_eq!(stateful_width.get(), px(20.));
4595
4596 move_mouse(cx, point(px(5.), px(5.)));
4597 assert_eq!(render_count.get(), initial_render_count + 2);
4598 assert_eq!(anonymous_paint_count.get(), 1);
4599 assert_eq!(stateful_width.get(), px(10.));
4600
4601 move_mouse(cx, point(px(10.), px(10.)));
4602 assert_eq!(render_count.get(), initial_render_count + 2);
4603 assert_eq!(anonymous_paint_count.get(), 1);
4604 assert_eq!(stateful_width.get(), px(10.));
4605 }
4606
4607 struct HoverListenerLayoutTestView {
4608 target_left: Pixels,
4609 hover_transitions: Rc<RefCell<Vec<bool>>>,
4610 }
4611
4612 impl Render for HoverListenerLayoutTestView {
4613 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4614 let hover_transitions = self.hover_transitions.clone();
4615 div().relative().size_full().child(
4616 div()
4617 .id("hover-target")
4618 .absolute()
4619 .left(self.target_left)
4620 .top_0()
4621 .size(px(20.))
4622 .on_click(|_, _, _| {})
4623 .on_hover(move |is_hovered, _, _| {
4624 hover_transitions.borrow_mut().push(*is_hovered);
4625 }),
4626 )
4627 }
4628 }
4629
4630 #[gpui::test]
4631 fn default_hover_listener_updates_when_layout_changes_under_stationary_mouse(
4632 cx: &mut TestAppContext,
4633 ) {
4634 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4635 let window = cx.add_window({
4636 let hover_transitions = hover_transitions.clone();
4637 move |_, _| HoverListenerLayoutTestView {
4638 target_left: px(40.),
4639 hover_transitions,
4640 }
4641 });
4642 let any_window = AnyWindowHandle::from(window);
4643
4644 cx.update_window(any_window, |_, window, cx| {
4645 window.draw(cx).clear(cx);
4646 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4647 })
4648 .unwrap();
4649 assert!(hover_transitions.borrow().is_empty());
4650
4651 window
4652 .update(cx, |view, _, cx| {
4653 view.target_left = px(0.);
4654 cx.notify();
4655 })
4656 .unwrap();
4657 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4658 .unwrap();
4659 assert_eq!(*hover_transitions.borrow(), [true]);
4660
4661 window
4662 .update(cx, |view, _, cx| {
4663 view.target_left = px(40.);
4664 cx.notify();
4665 })
4666 .unwrap();
4667 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4668 .unwrap();
4669 assert_eq!(*hover_transitions.borrow(), [true, false]);
4670 }
4671
4672 #[gpui::test]
4673 fn default_hover_listener_ends_after_key_press(cx: &mut TestAppContext) {
4674 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4675 let window = cx.add_window({
4676 let hover_transitions = hover_transitions.clone();
4677 move |_, _| HoverListenerLayoutTestView {
4678 target_left: px(0.),
4679 hover_transitions,
4680 }
4681 });
4682 let any_window = AnyWindowHandle::from(window);
4683
4684 cx.update_window(any_window, |_, window, cx| {
4685 window.draw(cx).clear(cx);
4686 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4687 })
4688 .unwrap();
4689 assert_eq!(*hover_transitions.borrow(), [true]);
4690
4691 key_down(cx, any_window, "a");
4692 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4693 .unwrap();
4694 assert_eq!(*hover_transitions.borrow(), [true, false]);
4695 }
4696
4697 struct HoverListenerModeLayoutTestView {
4698 target_left: Pixels,
4699 hover_transitions: Rc<RefCell<Vec<bool>>>,
4700 }
4701
4702 impl Render for HoverListenerModeLayoutTestView {
4703 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4704 let hover_transitions = self.hover_transitions.clone();
4705 div().relative().size_full().child(
4706 div()
4707 .id("hover-target")
4708 .absolute()
4709 .left(self.target_left)
4710 .top_0()
4711 .size(px(20.))
4712 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
4713 .on_hover(move |is_hovered, _, _| {
4714 hover_transitions.borrow_mut().push(*is_hovered);
4715 }),
4716 )
4717 }
4718 }
4719
4720 #[gpui::test]
4721 fn input_modality_independent_hover_listener_updates_after_key_press(cx: &mut TestAppContext) {
4722 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4723 let window = cx.add_window({
4724 let hover_transitions = hover_transitions.clone();
4725 move |_, _| HoverListenerModeLayoutTestView {
4726 target_left: px(40.),
4727 hover_transitions,
4728 }
4729 });
4730 let any_window = AnyWindowHandle::from(window);
4731 let pointer_position = point(px(10.), px(10.));
4732
4733 cx.update_window(any_window, |_, window, cx| {
4734 window.draw(cx).clear(cx);
4735 window.simulate_mouse_move(pointer_position, cx);
4736 })
4737 .unwrap();
4738 assert!(hover_transitions.borrow().is_empty());
4739
4740 key_down(cx, any_window, "a");
4741 window
4742 .update(cx, |view, _, cx| {
4743 view.target_left = px(0.);
4744 cx.notify();
4745 })
4746 .unwrap();
4747 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4748 .unwrap();
4749 assert_eq!(*hover_transitions.borrow(), [true]);
4750
4751 key_down(cx, any_window, "b");
4752 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4753 .unwrap();
4754 assert_eq!(*hover_transitions.borrow(), [true]);
4755
4756 cx.update_window(any_window, |_, window, cx| {
4757 window.simulate_mouse_move(point(px(30.), px(10.)), cx);
4758 })
4759 .unwrap();
4760 assert_eq!(*hover_transitions.borrow(), [true, false]);
4761
4762 cx.update_window(any_window, |_, window, cx| {
4763 window.simulate_mouse_move(pointer_position, cx);
4764 window.dispatch_event(
4765 MouseExitEvent {
4766 position: pointer_position,
4767 ..Default::default()
4768 }
4769 .to_platform_input(),
4770 cx,
4771 );
4772 })
4773 .unwrap();
4774 assert_eq!(*hover_transitions.borrow(), [true, false, true, false]);
4775 }
4776
4777 #[gpui::test]
4778 fn default_hover_listener_remains_hovered_during_stationary_mouse_press(
4779 cx: &mut TestAppContext,
4780 ) {
4781 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4782 let window = cx.add_window({
4783 let hover_transitions = hover_transitions.clone();
4784 move |_, _| HoverListenerLayoutTestView {
4785 target_left: px(0.),
4786 hover_transitions,
4787 }
4788 });
4789 let any_window = AnyWindowHandle::from(window);
4790 let mouse_position = point(px(10.), px(10.));
4791
4792 cx.update_window(any_window, |_, window, cx| {
4793 window.draw(cx).clear(cx);
4794 window.simulate_mouse_move(mouse_position, cx);
4795 })
4796 .unwrap();
4797 assert_eq!(*hover_transitions.borrow(), [true]);
4798
4799 cx.update_window(any_window, |_, window, cx| {
4800 window.dispatch_event(
4801 MouseDownEvent {
4802 position: mouse_position,
4803 button: MouseButton::Left,
4804 modifiers: Default::default(),
4805 click_count: 1,
4806 first_mouse: false,
4807 }
4808 .to_platform_input(),
4809 cx,
4810 );
4811 window.draw(cx).clear(cx);
4812 })
4813 .unwrap();
4814 assert_eq!(*hover_transitions.borrow(), [true]);
4815
4816 cx.update_window(any_window, |_, window, cx| {
4817 window.dispatch_event(
4818 MouseUpEvent {
4819 position: mouse_position,
4820 button: MouseButton::Left,
4821 modifiers: Default::default(),
4822 click_count: 1,
4823 }
4824 .to_platform_input(),
4825 cx,
4826 );
4827 window.draw(cx).clear(cx);
4828 })
4829 .unwrap();
4830 assert_eq!(*hover_transitions.borrow(), [true]);
4831 }
4832
4833 struct TestTooltipView;
4834
4835 impl Render for TestTooltipView {
4836 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4837 div().w(px(20.)).h(px(20.)).child("tooltip")
4838 }
4839 }
4840
4841 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4842
4843 struct TooltipCaptureElement {
4844 child: AnyElement,
4845 captured_active_tooltip: CapturedActiveTooltip,
4846 }
4847
4848 impl IntoElement for TooltipCaptureElement {
4849 type Element = Self;
4850
4851 fn into_element(self) -> Self::Element {
4852 self
4853 }
4854 }
4855
4856 impl Element for TooltipCaptureElement {
4857 type RequestLayoutState = ();
4858 type PrepaintState = ();
4859
4860 fn id(&self) -> Option<ElementId> {
4861 None
4862 }
4863
4864 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4865 None
4866 }
4867
4868 fn request_layout(
4869 &mut self,
4870 _id: Option<&GlobalElementId>,
4871 _inspector_id: Option<&InspectorElementId>,
4872 window: &mut Window,
4873 cx: &mut App,
4874 ) -> (LayoutId, Self::RequestLayoutState) {
4875 (self.child.request_layout(window, cx), ())
4876 }
4877
4878 fn prepaint(
4879 &mut self,
4880 _id: Option<&GlobalElementId>,
4881 _inspector_id: Option<&InspectorElementId>,
4882 _bounds: Bounds<Pixels>,
4883 _request_layout: &mut Self::RequestLayoutState,
4884 window: &mut Window,
4885 cx: &mut App,
4886 ) -> Self::PrepaintState {
4887 self.child.prepaint(window, cx);
4888 }
4889
4890 fn paint(
4891 &mut self,
4892 _id: Option<&GlobalElementId>,
4893 _inspector_id: Option<&InspectorElementId>,
4894 _bounds: Bounds<Pixels>,
4895 _request_layout: &mut Self::RequestLayoutState,
4896 _prepaint: &mut Self::PrepaintState,
4897 window: &mut Window,
4898 cx: &mut App,
4899 ) {
4900 self.child.paint(window, cx);
4901 window.with_global_id("target".into(), |global_id, window| {
4902 window.with_element_state::<InteractiveElementState, _>(
4903 global_id,
4904 |state, _window| {
4905 let state = state.unwrap();
4906 *self.captured_active_tooltip.borrow_mut() =
4907 state.active_tooltip.as_ref().map(Rc::downgrade);
4908 ((), state)
4909 },
4910 )
4911 });
4912 }
4913 }
4914
4915 struct TooltipOwner {
4916 captured_active_tooltip: CapturedActiveTooltip,
4917 show_delay_override: Option<Duration>,
4918 }
4919
4920 impl Render for TooltipOwner {
4921 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4922 TooltipCaptureElement {
4923 child: div()
4924 .size_full()
4925 .child(
4926 div()
4927 .id("target")
4928 .w(px(50.))
4929 .h(px(50.))
4930 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4931 .when_some(self.show_delay_override, |this, delay| {
4932 this.tooltip_show_delay(delay)
4933 }),
4934 )
4935 .into_any_element(),
4936 captured_active_tooltip: self.captured_active_tooltip.clone(),
4937 }
4938 }
4939 }
4940
4941 #[test]
4942 fn scroll_handle_aligns_wide_children_to_left_edge() {
4943 let handle = ScrollHandle::new();
4944 {
4945 let mut state = handle.0.borrow_mut();
4946 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4947 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4948 state.overflow.x = Overflow::Scroll;
4949 state.active_item = Some(ScrollActiveItem {
4950 index: 0,
4951 strategy: ScrollStrategy::default(),
4952 });
4953 }
4954
4955 handle.scroll_to_active_item();
4956
4957 assert_eq!(handle.offset().x, px(-25.));
4958 }
4959
4960 #[test]
4961 fn scroll_handle_aligns_tall_children_to_top_edge() {
4962 let handle = ScrollHandle::new();
4963 {
4964 let mut state = handle.0.borrow_mut();
4965 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4966 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4967 state.overflow.y = Overflow::Scroll;
4968 state.active_item = Some(ScrollActiveItem {
4969 index: 0,
4970 strategy: ScrollStrategy::default(),
4971 });
4972 }
4973
4974 handle.scroll_to_active_item();
4975
4976 assert_eq!(handle.offset().y, px(-25.));
4977 }
4978
4979 #[test]
4980 fn long_press_shows_tooltip_until_touch_ends() {
4981 let (mut test_app, any_window, captured_active_tooltip) = create_tooltip_owner_test(None);
4982 let active_tooltip = captured_active_tooltip
4983 .borrow()
4984 .clone()
4985 .unwrap()
4986 .upgrade()
4987 .unwrap();
4988 let touch_id = TouchId(1);
4989 let touch_position = point(px(49.), px(10.));
4990
4991 test_app
4992 .update_window(any_window, |_, window, cx| {
4993 window.dispatch_event(
4994 TouchEvent {
4995 id: touch_id,
4996 phase: TouchPhase::Started,
4997 position: touch_position,
4998 predicted_position: None,
4999 force: None,
5000 }
5001 .to_platform_input(),
5002 cx,
5003 );
5004 })
5005 .unwrap();
5006 test_app
5007 .dispatcher
5008 .advance_clock(GestureTuning::default().long_press_duration + Duration::from_millis(1));
5009 test_app.run_until_parked();
5010
5011 assert!(matches!(
5012 active_tooltip.borrow().as_ref(),
5013 Some(ActiveTooltip::Visible { .. })
5014 ));
5015
5016 let moved_position = point(px(55.), px(10.));
5017 test_app
5018 .update_window(any_window, |_, window, cx| {
5019 window.dispatch_event(
5020 TouchEvent {
5021 id: touch_id,
5022 phase: TouchPhase::Moved,
5023 position: moved_position,
5024 predicted_position: None,
5025 force: None,
5026 }
5027 .to_platform_input(),
5028 cx,
5029 );
5030 window.draw(cx).clear(cx);
5031 })
5032 .unwrap();
5033 assert!(matches!(
5034 active_tooltip.borrow().as_ref(),
5035 Some(ActiveTooltip::Visible { .. })
5036 ));
5037
5038 test_app
5039 .update_window(any_window, |_, window, cx| {
5040 window.dispatch_event(
5041 TouchEvent {
5042 id: touch_id,
5043 phase: TouchPhase::Ended,
5044 position: moved_position,
5045 predicted_position: None,
5046 force: None,
5047 }
5048 .to_platform_input(),
5049 cx,
5050 );
5051 })
5052 .unwrap();
5053
5054 assert!(active_tooltip.borrow().is_none());
5055 }
5056
5057 fn setup_tooltip_owner_test(
5058 show_delay_override: Option<Duration>,
5059 ) -> (
5060 TestAppContext,
5061 crate::AnyWindowHandle,
5062 CapturedActiveTooltip,
5063 ) {
5064 let (mut test_app, any_window, captured_active_tooltip) =
5065 create_tooltip_owner_test(show_delay_override);
5066
5067 test_app
5068 .update_window(any_window, |_, window, cx| {
5069 window.dispatch_event(
5070 MouseMoveEvent {
5071 position: point(px(10.), px(10.)),
5072 modifiers: Default::default(),
5073 pressed_button: None,
5074 }
5075 .to_platform_input(),
5076 cx,
5077 );
5078 })
5079 .unwrap();
5080
5081 test_app
5082 .update_window(any_window, |_, window, cx| {
5083 window.draw(cx).clear(cx);
5084 })
5085 .unwrap();
5086
5087 (test_app, any_window, captured_active_tooltip)
5088 }
5089
5090 fn create_tooltip_owner_test(
5091 show_delay_override: Option<Duration>,
5092 ) -> (
5093 TestAppContext,
5094 crate::AnyWindowHandle,
5095 CapturedActiveTooltip,
5096 ) {
5097 let mut test_app = TestAppContext::single();
5098 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
5099 let window = test_app.add_window({
5100 let captured_active_tooltip = captured_active_tooltip.clone();
5101 move |_, _| TooltipOwner {
5102 captured_active_tooltip,
5103 show_delay_override,
5104 }
5105 });
5106 let any_window = window.into();
5107
5108 test_app
5109 .update_window(any_window, |_, window, cx| {
5110 window.draw(cx).clear(cx);
5111 })
5112 .unwrap();
5113
5114 (test_app, any_window, captured_active_tooltip)
5115 }
5116
5117 #[test]
5118 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
5119 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5120
5121 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5122 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5123 assert!(matches!(
5124 active_tooltip.borrow().as_ref(),
5125 Some(ActiveTooltip::WaitingForShow { .. })
5126 ));
5127
5128 test_app
5129 .update_window(any_window, |_, window, _| {
5130 window.remove_window();
5131 })
5132 .unwrap();
5133 test_app.run_until_parked();
5134 drop(active_tooltip);
5135
5136 assert!(weak_active_tooltip.upgrade().is_none());
5137 }
5138
5139 #[test]
5140 fn tooltip_respects_custom_show_delay() {
5141 let extra_delay = Duration::from_secs(1);
5142 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
5143 let (mut test_app, _any_window, captured_active_tooltip) =
5144 setup_tooltip_owner_test(Some(show_delay_override));
5145
5146 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5147 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5148
5149 test_app
5150 .dispatcher
5151 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5152 test_app.run_until_parked();
5153
5154 assert!(matches!(
5155 active_tooltip.borrow().as_ref(),
5156 Some(ActiveTooltip::WaitingForShow { .. })
5157 ));
5158
5159 test_app.dispatcher.advance_clock(extra_delay);
5160 test_app.run_until_parked();
5161
5162 assert!(matches!(
5163 active_tooltip.borrow().as_ref(),
5164 Some(ActiveTooltip::Visible { .. })
5165 ));
5166 }
5167
5168 #[test]
5169 fn tooltip_is_released_when_its_owner_disappears() {
5170 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5171
5172 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5173 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5174
5175 test_app
5176 .dispatcher
5177 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5178 test_app.run_until_parked();
5179
5180 assert!(matches!(
5181 active_tooltip.borrow().as_ref(),
5182 Some(ActiveTooltip::Visible { .. })
5183 ));
5184
5185 test_app
5186 .update_window(any_window, |_, window, _| {
5187 window.remove_window();
5188 })
5189 .unwrap();
5190 test_app.run_until_parked();
5191 drop(active_tooltip);
5192
5193 assert!(weak_active_tooltip.upgrade().is_none());
5194 }
5195
5196 #[test]
5197 fn tooltip_hides_after_mouse_leaves_origin() {
5198 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
5199
5200 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
5201 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
5202
5203 test_app
5204 .dispatcher
5205 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
5206 test_app.run_until_parked();
5207
5208 assert!(matches!(
5209 active_tooltip.borrow().as_ref(),
5210 Some(ActiveTooltip::Visible { .. })
5211 ));
5212
5213 test_app
5214 .update_window(any_window, |_, window, cx| {
5215 window.dispatch_event(
5216 MouseMoveEvent {
5217 position: point(px(75.), px(75.)),
5218 modifiers: Default::default(),
5219 pressed_button: None,
5220 }
5221 .to_platform_input(),
5222 cx,
5223 );
5224 })
5225 .unwrap();
5226
5227 assert!(active_tooltip.borrow().is_none());
5228 }
5229
5230 struct MouseDownOutOwner {
5231 mouse_down_out_count: Rc<RefCell<usize>>,
5232 }
5233
5234 impl Render for MouseDownOutOwner {
5235 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5236 let mouse_down_out_count = self.mouse_down_out_count.clone();
5237 div()
5238 .size_full()
5239 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
5240 move |_, _, _| {
5241 *mouse_down_out_count.borrow_mut() += 1;
5242 },
5243 ))
5244 }
5245 }
5246
5247 #[test]
5248 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
5249 let mut test_app = TestAppContext::single();
5250 let mouse_down_out_count = Rc::new(RefCell::new(0));
5251 let window = test_app.add_window({
5252 let mouse_down_out_count = mouse_down_out_count.clone();
5253 move |_, _| MouseDownOutOwner {
5254 mouse_down_out_count,
5255 }
5256 });
5257 let any_window: AnyWindowHandle = window.into();
5258
5259 fn dispatch_mouse_down_outside_target(
5260 test_app: &mut TestAppContext,
5261 any_window: AnyWindowHandle,
5262 ) {
5263 test_app
5264 .update_window(any_window, |_, window, cx| {
5265 window.dispatch_event(
5266 MouseDownEvent {
5267 position: point(px(75.), px(75.)),
5268 button: MouseButton::Left,
5269 modifiers: Default::default(),
5270 click_count: 1,
5271 first_mouse: false,
5272 }
5273 .to_platform_input(),
5274 cx,
5275 );
5276 })
5277 .unwrap();
5278 }
5279
5280 test_app
5281 .update_window(any_window, |_, window, cx| {
5282 window.draw(cx).clear(cx);
5283 })
5284 .unwrap();
5285
5286 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5287 assert_eq!(
5288 *mouse_down_out_count.borrow(),
5289 1,
5290 "mouse down outside the element should fire mouse-down-out listeners"
5291 );
5292
5293 test_app
5294 .update_window(any_window, |_, window, cx| {
5295 cx.set_prompt_builder(crate::fallback_prompt_renderer);
5296 let _receiver =
5297 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
5298 assert!(window.has_active_prompt());
5299 window.draw(cx).clear(cx);
5300 })
5301 .unwrap();
5302
5303 dispatch_mouse_down_outside_target(&mut test_app, any_window);
5304 assert_eq!(
5305 *mouse_down_out_count.borrow(),
5306 1,
5307 "mouse down over an active prompt should not fire mouse-down-out listeners"
5308 );
5309 }
5310
5311 #[test]
5312 fn test_accessibility_id_builder_writes_author_id() {
5313 let mut element = div()
5314 .id("buffer-font-size")
5315 .accessibility_id("settings.buffer-font-size");
5316 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5317
5318 element.interactivity().write_a11y_info(&mut node);
5319
5320 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5321 }
5322
5323 #[test]
5324 fn test_write_a11y_info_string_and_numeric_properties() {
5325 let mut interactivity = Interactivity::default();
5326 interactivity.aria.author_id = Some("settings.buffer-font-size".into());
5327 interactivity.aria.label = Some("Buffer Font Size".into());
5328 interactivity.aria.value = Some("15".into());
5329 interactivity.aria.placeholder = Some("Search".into());
5330 interactivity.aria.numeric_value = Some(15.0);
5331 interactivity.aria.min_numeric_value = Some(6.0);
5332 interactivity.aria.max_numeric_value = Some(72.0);
5333 interactivity.aria.numeric_value_step = Some(1.0);
5334
5335 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
5336 interactivity.write_a11y_info(&mut node);
5337
5338 assert_eq!(node.author_id(), Some("settings.buffer-font-size"));
5339 assert_eq!(node.label(), Some("Buffer Font Size"));
5340 assert_eq!(node.value(), Some("15"));
5341 assert_eq!(node.placeholder(), Some("Search"));
5342 assert_eq!(node.numeric_value(), Some(15.0));
5343 assert_eq!(node.min_numeric_value(), Some(6.0));
5344 assert_eq!(node.max_numeric_value(), Some(72.0));
5345 assert_eq!(node.numeric_value_step(), Some(1.0));
5346 }
5347
5348 struct KeyboardActivationTest {
5351 focus_a: FocusHandle,
5352 focus_b: FocusHandle,
5353 clicks: Rc<RefCell<Vec<&'static str>>>,
5354 }
5355
5356 impl Render for KeyboardActivationTest {
5357 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5358 let clicks_a = self.clicks.clone();
5359 let clicks_b = self.clicks.clone();
5360 div()
5361 .size_full()
5362 .child(
5363 div()
5364 .id("a")
5365 .w(px(50.))
5366 .h(px(50.))
5367 .track_focus(&self.focus_a)
5368 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
5369 )
5370 .child(
5371 div()
5372 .id("b")
5373 .w(px(50.))
5374 .h(px(50.))
5375 .track_focus(&self.focus_b)
5376 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
5377 )
5378 }
5379 }
5380
5381 fn setup_keyboard_activation_test() -> (
5382 TestAppContext,
5383 AnyWindowHandle,
5384 Rc<RefCell<Vec<&'static str>>>,
5385 FocusHandle,
5386 FocusHandle,
5387 ) {
5388 let mut cx = TestAppContext::single();
5389 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
5390 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
5391 let window = cx.add_window({
5392 let focus_a = focus_a.clone();
5393 let focus_b = focus_b.clone();
5394 let clicks = clicks.clone();
5395 move |_, _| KeyboardActivationTest {
5396 focus_a,
5397 focus_b,
5398 clicks,
5399 }
5400 });
5401 (cx, window.into(), clicks, focus_a, focus_b)
5402 }
5403
5404 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
5407 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
5408 .unwrap();
5409 cx.run_until_parked();
5410 cx.update_window(window, |_, window, cx| {
5411 window.draw(cx).clear(cx);
5412 })
5413 .unwrap();
5414 }
5415
5416 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5417 let keystroke = Keystroke::parse(key).unwrap();
5418 cx.update_window(window, |_, window, cx| {
5419 window.dispatch_event(
5420 KeyDownEvent {
5421 keystroke,
5422 is_held: false,
5423 prefer_character_input: false,
5424 }
5425 .to_platform_input(),
5426 cx,
5427 );
5428 })
5429 .unwrap();
5430 }
5431
5432 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
5433 let keystroke = Keystroke::parse(key).unwrap();
5434 cx.update_window(window, |_, window, cx| {
5435 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
5436 })
5437 .unwrap();
5438 }
5439
5440 #[test]
5442 fn keyboard_activation_fires_click_on_same_element() {
5443 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5444
5445 focus_and_draw(&mut cx, window, &focus_a);
5446 key_down(&mut cx, window, "enter");
5447 key_up(&mut cx, window, "enter");
5448
5449 assert_eq!(*clicks.borrow(), vec!["a"]);
5450 }
5451
5452 #[test]
5457 fn keyboard_activation_does_not_leak_across_focus_change() {
5458 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5459
5460 focus_and_draw(&mut cx, window, &focus_a);
5462 key_down(&mut cx, window, "enter");
5463
5464 focus_and_draw(&mut cx, window, &focus_b);
5466 key_up(&mut cx, window, "enter");
5467
5468 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5471 }
5472
5473 #[test]
5478 fn keyboard_activation_does_not_leak_when_focus_returns() {
5479 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
5480
5481 focus_and_draw(&mut cx, window, &focus_a);
5483 key_down(&mut cx, window, "enter");
5484
5485 focus_and_draw(&mut cx, window, &focus_b);
5488 focus_and_draw(&mut cx, window, &focus_a);
5489 key_up(&mut cx, window, "enter");
5490
5491 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5493 }
5494
5495 #[test]
5500 fn keyboard_activation_cleared_by_intervening_key_release() {
5501 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5502
5503 focus_and_draw(&mut cx, window, &focus_a);
5504 key_down(&mut cx, window, "escape");
5505 key_down(&mut cx, window, "space");
5506 key_up(&mut cx, window, "escape");
5507 key_up(&mut cx, window, "space");
5508
5509 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5510 }
5511
5512 #[test]
5516 fn keyboard_activation_does_not_distinguish_space_and_enter() {
5517 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5518
5519 focus_and_draw(&mut cx, window, &focus_a);
5520 key_down(&mut cx, window, "space");
5521 key_up(&mut cx, window, "enter");
5522
5523 assert_eq!(*clicks.borrow(), vec!["a"]);
5524 }
5525
5526 #[test]
5529 fn keyboard_activation_cleared_by_intervening_keydown() {
5530 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5531
5532 focus_and_draw(&mut cx, window, &focus_a);
5533 key_down(&mut cx, window, "enter");
5534 key_down(&mut cx, window, "a");
5535 key_up(&mut cx, window, "enter");
5536
5537 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5538 }
5539
5540 #[test]
5543 fn keyboard_activation_ignores_modified_keys() {
5544 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
5545
5546 focus_and_draw(&mut cx, window, &focus_a);
5547 key_down(&mut cx, window, "cmd-enter");
5548 key_up(&mut cx, window, "cmd-enter");
5549
5550 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
5551 }
5552
5553 struct TabGroupFocus {
5557 group_a: FocusHandle,
5558 item_a: FocusHandle,
5559 group_b: FocusHandle,
5560 item_b: FocusHandle,
5561 }
5562
5563 impl Render for TabGroupFocus {
5564 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5565 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
5566 div()
5567 .track_focus(container)
5568 .tab_group()
5569 .child(div().track_focus(item))
5570 }
5571 div()
5572 .child(group(&self.group_a, &self.item_a))
5573 .child(group(&self.group_b, &self.item_b))
5574 }
5575 }
5576
5577 #[test]
5581 fn focus_next_from_tab_group_container_enters_that_group() {
5582 let mut cx = TestAppContext::single();
5583 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
5584 (
5585 cx.focus_handle(),
5586 cx.focus_handle().tab_stop(true),
5587 cx.focus_handle(),
5588 cx.focus_handle().tab_stop(true),
5589 )
5590 });
5591 let window: AnyWindowHandle = cx
5592 .add_window({
5593 let (group_a, item_a, group_b, item_b) =
5594 (group_a, item_a, group_b.clone(), item_b.clone());
5595 move |_, _| TabGroupFocus {
5596 group_a,
5597 item_a,
5598 group_b,
5599 item_b,
5600 }
5601 })
5602 .into();
5603 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5604 .unwrap();
5605
5606 let focused = cx
5608 .update_window(window, |_, window, cx| {
5609 window.focus(&group_b, cx);
5610 window.focus_next(cx);
5611 window.focused(cx).map(|handle| handle.id)
5612 })
5613 .unwrap();
5614
5615 assert_eq!(focused, Some(item_b.id));
5616 }
5617
5618 #[gpui::test]
5619 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5620 cx: &mut TestAppContext,
5621 ) {
5622 struct PaddedContainer {
5623 scroll_handle: ScrollHandle,
5624 }
5625
5626 impl Render for PaddedContainer {
5627 fn render(
5628 &mut self,
5629 _window: &mut Window,
5630 _cx: &mut Context<Self>,
5631 ) -> impl IntoElement {
5632 div().size_full().child(
5635 div()
5636 .id("container")
5637 .h(px(50.))
5638 .w(px(100.))
5639 .py(px(4.25))
5640 .overflow_y_scroll()
5641 .track_scroll(&self.scroll_handle)
5642 .child(div().w_full().h(px(42.))),
5643 )
5644 }
5645 }
5646
5647 let scroll_handle = ScrollHandle::new();
5648 let window: AnyWindowHandle = cx
5649 .add_window({
5650 let scroll_handle = scroll_handle.clone();
5651 move |_, _| PaddedContainer { scroll_handle }
5652 })
5653 .into();
5654 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5655 .unwrap();
5656
5657 assert_eq!(scroll_handle.max_offset().y, px(0.));
5658 }
5659
5660 struct ContentSizedGrid;
5661
5662 impl Render for ContentSizedGrid {
5663 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5664 let widths = [px(100.), px(200.), px(50.)];
5665 div().size_full().child(
5666 div()
5667 .w_full()
5668 .grid()
5669 .grid_cols_max_content(widths.len() as u16)
5670 .children(widths.into_iter().enumerate().map(|(index, width)| {
5671 div()
5672 .debug_selector(move || format!("cell-{index}"))
5673 .w(width)
5674 .h(px(10.))
5675 })),
5676 )
5677 }
5678 }
5679
5680 #[gpui::test]
5681 fn grid_cols_max_content_sizes_columns_to_their_content(cx: &mut TestAppContext) {
5682 let window = cx.add_window(|_, _| ContentSizedGrid);
5683 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
5684 .unwrap();
5685
5686 let mut bounds = |selector: &'static str| {
5687 cx.update_window(window.into(), |_, window, _| {
5688 window.rendered_frame.debug_bounds.get(selector).copied()
5689 })
5690 .unwrap()
5691 .unwrap_or_else(|| panic!("{selector} was not rendered"))
5692 };
5693
5694 assert_eq!(bounds("cell-0").origin.x, px(0.));
5695 assert_eq!(bounds("cell-1").origin.x, px(100.));
5696 assert_eq!(bounds("cell-2").origin.x, px(300.));
5697 }
5698}