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