1use crate::{
19 Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent, DispatchPhase,
20 Display, Element, ElementId, Entity, EntityId, ExternalDragPayload, ExternalDragPayloadSource,
21 FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, HitboxId, InspectorElementId,
22 IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, KeyboardButton, KeyboardClickEvent,
23 LayoutId, ModifiersChangedEvent, MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent,
24 MouseMoveEvent, MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement,
25 PinchEvent, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style,
26 StyleRefinement, Styled, Task, TooltipId, Visibility, Window, WindowControlArea, point, px,
27 size,
28};
29use collections::HashMap;
30use gpui_util::ResultExt;
31use refineable::Refineable;
32use smallvec::SmallVec;
33use stacksafe::{StackSafe, stacksafe};
34use std::{
35 any::{Any, TypeId},
36 cell::RefCell,
37 cmp::Ordering,
38 fmt::Debug,
39 marker::PhantomData,
40 mem,
41 rc::Rc,
42 sync::Arc,
43 time::Duration,
44};
45
46use super::ImageCacheProvider;
47
48const DRAG_THRESHOLD: f64 = 2.;
49const DEFAULT_TOOLTIP_SHOW_DELAY: Duration = Duration::from_millis(500);
50const HOVERABLE_TOOLTIP_HIDE_DELAY: Duration = Duration::from_millis(500);
51
52pub struct GroupStyle {
54 pub group: SharedString,
56
57 pub style: Box<StyleRefinement>,
60}
61
62pub struct DragMoveEvent<T> {
64 pub event: MouseMoveEvent,
66
67 pub bounds: Bounds<Pixels>,
69 drag: PhantomData<T>,
70 dragged_item: Arc<dyn Any>,
71}
72
73impl<T: 'static> DragMoveEvent<T> {
74 pub fn drag<'b>(&self, cx: &'b App) -> &'b T {
76 cx.active_drag
77 .as_ref()
78 .and_then(|drag| drag.value.downcast_ref::<T>())
79 .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
80 }
81
82 pub fn dragged_item(&self) -> &dyn Any {
84 self.dragged_item.as_ref()
85 }
86}
87
88impl Interactivity {
89 #[cfg(any(feature = "inspector", debug_assertions))]
91 #[track_caller]
92 pub fn new() -> Interactivity {
93 Interactivity {
94 source_location: Some(core::panic::Location::caller()),
95 ..Default::default()
96 }
97 }
98
99 #[cfg(not(any(feature = "inspector", debug_assertions)))]
101 pub fn new() -> Interactivity {
102 Interactivity::default()
103 }
104
105 pub fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
107 #[cfg(any(feature = "inspector", debug_assertions))]
108 {
109 self.source_location
110 }
111
112 #[cfg(not(any(feature = "inspector", debug_assertions)))]
113 {
114 None
115 }
116 }
117
118 pub fn on_mouse_down(
123 &mut self,
124 button: MouseButton,
125 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
126 ) {
127 self.mouse_down_listeners
128 .push(Box::new(move |event, phase, hitbox, window, cx| {
129 if phase == DispatchPhase::Bubble
130 && event.button == button
131 && hitbox.is_hovered(window)
132 {
133 (listener)(event, window, cx)
134 }
135 }));
136 }
137
138 pub fn capture_any_mouse_down(
143 &mut self,
144 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
145 ) {
146 self.mouse_down_listeners
147 .push(Box::new(move |event, phase, hitbox, window, cx| {
148 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
149 (listener)(event, window, cx)
150 }
151 }));
152 }
153
154 pub fn on_any_mouse_down(
159 &mut self,
160 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
161 ) {
162 self.mouse_down_listeners
163 .push(Box::new(move |event, phase, hitbox, window, cx| {
164 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
165 (listener)(event, window, cx)
166 }
167 }));
168 }
169
170 pub fn on_mouse_pressure(
175 &mut self,
176 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
177 ) {
178 self.mouse_pressure_listeners
179 .push(Box::new(move |event, phase, hitbox, window, cx| {
180 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
181 (listener)(event, window, cx)
182 }
183 }));
184 }
185
186 pub fn capture_mouse_pressure(
191 &mut self,
192 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
193 ) {
194 self.mouse_pressure_listeners
195 .push(Box::new(move |event, phase, hitbox, window, cx| {
196 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
197 (listener)(event, window, cx)
198 }
199 }));
200 }
201
202 pub fn on_mouse_up(
207 &mut self,
208 button: MouseButton,
209 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
210 ) {
211 self.mouse_up_listeners
212 .push(Box::new(move |event, phase, hitbox, window, cx| {
213 if phase == DispatchPhase::Bubble
214 && event.button == button
215 && hitbox.is_hovered(window)
216 {
217 (listener)(event, window, cx)
218 }
219 }));
220 }
221
222 pub fn capture_any_mouse_up(
227 &mut self,
228 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
229 ) {
230 self.mouse_up_listeners
231 .push(Box::new(move |event, phase, hitbox, window, cx| {
232 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
233 (listener)(event, window, cx)
234 }
235 }));
236 }
237
238 pub fn on_any_mouse_up(
243 &mut self,
244 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
245 ) {
246 self.mouse_up_listeners
247 .push(Box::new(move |event, phase, hitbox, window, cx| {
248 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
249 (listener)(event, window, cx)
250 }
251 }));
252 }
253
254 pub fn on_mouse_down_out(
260 &mut self,
261 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
262 ) {
263 self.mouse_down_listeners
264 .push(Box::new(move |event, phase, hitbox, window, cx| {
265 if phase == DispatchPhase::Capture
266 && !window.has_active_prompt()
267 && !hitbox.contains(&window.mouse_position())
268 {
269 (listener)(event, window, cx)
270 }
271 }));
272 }
273
274 pub fn on_mouse_up_out(
280 &mut self,
281 button: MouseButton,
282 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
283 ) {
284 self.mouse_up_listeners
285 .push(Box::new(move |event, phase, hitbox, window, cx| {
286 if phase == DispatchPhase::Capture
287 && event.button == button
288 && !hitbox.is_hovered(window)
289 {
290 (listener)(event, window, cx);
291 }
292 }));
293 }
294
295 pub fn on_mouse_move(
300 &mut self,
301 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
302 ) {
303 self.mouse_move_listeners
304 .push(Box::new(move |event, phase, hitbox, window, cx| {
305 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
306 (listener)(event, window, cx);
307 }
308 }));
309 }
310
311 pub fn on_mouse_exit(
316 &mut self,
317 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
318 ) {
319 self.mouse_exit_listeners
320 .push(Box::new(move |event, phase, hitbox, window, cx| {
321 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
322 (listener)(event, window, cx);
323 }
324 }));
325 }
326
327 pub fn on_drag_move<T>(
335 &mut self,
336 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
337 ) where
338 T: 'static,
339 {
340 self.mouse_move_listeners
341 .push(Box::new(move |event, phase, hitbox, window, cx| {
342 if phase == DispatchPhase::Capture
343 && let Some(drag) = &cx.active_drag
344 && drag.value.as_ref().type_id() == TypeId::of::<T>()
345 {
346 (listener)(
347 &DragMoveEvent {
348 event: event.clone(),
349 bounds: hitbox.bounds,
350 drag: PhantomData,
351 dragged_item: Arc::clone(&drag.value),
352 },
353 window,
354 cx,
355 );
356 }
357 }));
358 }
359
360 pub fn on_scroll_wheel(
365 &mut self,
366 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
367 ) {
368 self.scroll_wheel_listeners
369 .push(Box::new(move |event, phase, hitbox, window, cx| {
370 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
371 (listener)(event, window, cx);
372 }
373 }));
374 }
375
376 pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
380 self.pinch_listeners
381 .push(Box::new(move |event, phase, hitbox, window, cx| {
382 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
383 (listener)(event, window, cx);
384 }
385 }));
386 }
387
388 pub fn capture_pinch(
392 &mut self,
393 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
394 ) {
395 self.pinch_listeners
396 .push(Box::new(move |event, phase, _hitbox, window, cx| {
397 if phase == DispatchPhase::Capture {
398 (listener)(event, window, cx);
399 } else {
400 cx.propagate();
401 }
402 }));
403 }
404
405 pub fn capture_action<A: Action>(
410 &mut self,
411 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
412 ) {
413 self.action_listeners.push((
414 TypeId::of::<A>(),
415 Box::new(move |action, phase, window, cx| {
416 let action = action.downcast_ref().unwrap();
417 if phase == DispatchPhase::Capture {
418 (listener)(action, window, cx)
419 } else {
420 cx.propagate();
421 }
422 }),
423 ));
424 }
425
426 #[track_caller]
431 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
432 self.action_listeners.push((
433 TypeId::of::<A>(),
434 Box::new(move |action, phase, window, cx| {
435 let action = action.downcast_ref().unwrap();
436 if phase == DispatchPhase::Bubble {
437 (listener)(action, window, cx)
438 }
439 }),
440 ));
441 }
442
443 pub fn on_boxed_action(
450 &mut self,
451 action: &dyn Action,
452 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
453 ) {
454 let action = action.boxed_clone();
455 self.action_listeners.push((
456 (*action).type_id(),
457 Box::new(move |_, phase, window, cx| {
458 if phase == DispatchPhase::Bubble {
459 (listener)(&*action, window, cx)
460 }
461 }),
462 ));
463 }
464
465 pub fn on_key_down(
470 &mut self,
471 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
472 ) {
473 self.key_down_listeners
474 .push(Box::new(move |event, phase, window, cx| {
475 if phase == DispatchPhase::Bubble {
476 (listener)(event, window, cx)
477 }
478 }));
479 }
480
481 pub fn capture_key_down(
486 &mut self,
487 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
488 ) {
489 self.key_down_listeners
490 .push(Box::new(move |event, phase, window, cx| {
491 if phase == DispatchPhase::Capture {
492 listener(event, window, cx)
493 }
494 }));
495 }
496
497 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
502 self.key_up_listeners
503 .push(Box::new(move |event, phase, window, cx| {
504 if phase == DispatchPhase::Bubble {
505 listener(event, window, cx)
506 }
507 }));
508 }
509
510 pub fn capture_key_up(
515 &mut self,
516 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
517 ) {
518 self.key_up_listeners
519 .push(Box::new(move |event, phase, window, cx| {
520 if phase == DispatchPhase::Capture {
521 listener(event, window, cx)
522 }
523 }));
524 }
525
526 pub fn on_modifiers_changed(
531 &mut self,
532 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
533 ) {
534 self.modifiers_changed_listeners
535 .push(Box::new(move |event, window, cx| {
536 listener(event, window, cx)
537 }));
538 }
539
540 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
545 self.drop_listeners.push((
546 TypeId::of::<T>(),
547 Box::new(move |dragged_value, window, cx| {
548 listener(dragged_value.downcast_ref().unwrap(), window, cx);
549 }),
550 ));
551 }
552
553 pub fn can_drop(
556 &mut self,
557 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
558 ) {
559 self.can_drop_predicate = Some(Box::new(predicate));
560 }
561
562 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
567 where
568 Self: Sized,
569 {
570 self.click_listeners.push(Rc::new(move |event, window, cx| {
571 listener(event, window, cx)
572 }));
573 }
574
575 pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
580 where
581 Self: Sized,
582 {
583 self.aux_click_listeners
584 .push(Rc::new(move |event, window, cx| {
585 listener(event, window, cx)
586 }));
587 }
588
589 pub fn on_drag<T, W>(
596 &mut self,
597 value: T,
598 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
599 ) where
600 Self: Sized,
601 T: 'static,
602 W: 'static + Render,
603 {
604 debug_assert!(
605 self.drag_listener.is_none(),
606 "calling on_drag more than once on the same element is not supported"
607 );
608 self.drag_listener = Some(DragListener {
609 value: Arc::new(value),
610 render: Box::new(move |value, offset, window, cx| {
611 constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
612 }),
613 external_payload: None,
614 });
615 }
616
617 pub fn external_drag_payload<T>(
622 &mut self,
623 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
624 ) where
625 Self: Sized,
626 T: 'static,
627 {
628 let Some(drag_listener) = self.drag_listener.as_mut() else {
629 debug_assert!(false, "external_drag_payload must be called after on_drag");
630 return;
631 };
632 debug_assert!(
633 drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
634 "external_drag_payload must use the same dragged value type as on_drag"
635 );
636 debug_assert!(
637 drag_listener.external_payload.is_none(),
638 "calling external_drag_payload more than once on the same element is not supported"
639 );
640 drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
641 resolver(value.downcast_ref::<T>()?, window, cx)
642 }));
643 }
644
645 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
651 where
652 Self: Sized,
653 {
654 debug_assert!(
655 self.hover_listener.is_none(),
656 "calling on_hover more than once on the same element is not supported"
657 );
658 self.hover_listener = Some(Box::new(listener));
659 }
660
661 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
664 where
665 Self: Sized,
666 {
667 debug_assert!(
668 self.tooltip_builder.is_none(),
669 "calling tooltip more than once on the same element is not supported"
670 );
671 self.tooltip_builder = Some(TooltipBuilder {
672 build: Rc::new(build_tooltip),
673 hoverable: false,
674 });
675 }
676
677 pub fn hoverable_tooltip(
681 &mut self,
682 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
683 ) where
684 Self: Sized,
685 {
686 debug_assert!(
687 self.tooltip_builder.is_none(),
688 "calling tooltip more than once on the same element is not supported"
689 );
690 self.tooltip_builder = Some(TooltipBuilder {
691 build: Rc::new(build_tooltip),
692 hoverable: true,
693 });
694 }
695
696 pub fn tooltip_show_delay(&mut self, delay: Duration) {
699 self.tooltip_show_delay = Some(delay);
700 }
701
702 pub fn occlude_mouse(&mut self) {
707 self.hitbox_behavior = HitboxBehavior::BlockMouse;
708 }
709
710 pub fn window_control_area(&mut self, area: WindowControlArea) {
713 self.window_control = Some(area);
714 }
715
716 pub fn block_mouse_except_scroll(&mut self) {
721 self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
722 }
723
724 fn has_pinch_listeners(&self) -> bool {
725 !self.pinch_listeners.is_empty()
726 }
727}
728
729pub trait InteractiveElement: Sized {
732 fn interactivity(&mut self) -> &mut Interactivity;
734
735 fn group(mut self, group: impl Into<SharedString>) -> Self {
737 self.interactivity().group = Some(group.into());
738 self
739 }
740
741 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
743 self.interactivity().element_id = Some(id.into());
744
745 Stateful { element: self }
746 }
747
748 fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
752 self.interactivity().focusable = true;
753 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
754 self
755 }
756
757 fn tab_stop(mut self, tab_stop: bool) -> Self {
764 self.interactivity().tab_stop = tab_stop;
765 self
766 }
767
768 fn tab_index(mut self, index: isize) -> Self {
773 self.interactivity().focusable = true;
774 self.interactivity().tab_index = Some(index);
775 self.interactivity().tab_stop = true;
776 self
777 }
778
779 fn tab_group(mut self) -> Self {
784 self.interactivity().tab_group = true;
785 if self.interactivity().tab_index.is_none() {
786 self.interactivity().tab_index = Some(0);
787 }
788 self
789 }
790
791 fn key_context<C, E>(mut self, key_context: C) -> Self
794 where
795 C: TryInto<KeyContext, Error = E>,
796 E: std::fmt::Display,
797 {
798 if let Some(key_context) = key_context.try_into().log_err() {
799 self.interactivity().key_context = Some(key_context);
800 }
801 self
802 }
803
804 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
806 debug_assert!(
807 self.interactivity().hover_style.is_none(),
808 "hover style already set"
809 );
810 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
811 self
812 }
813
814 fn group_hover(
816 mut self,
817 group_name: impl Into<SharedString>,
818 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
819 ) -> Self {
820 self.interactivity().group_hover_style = Some(GroupStyle {
821 group: group_name.into(),
822 style: Box::new(f(StyleRefinement::default())),
823 });
824 self
825 }
826
827 fn on_mouse_down(
832 mut self,
833 button: MouseButton,
834 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
835 ) -> Self {
836 self.interactivity().on_mouse_down(button, listener);
837 self
838 }
839
840 #[cfg(any(test, feature = "test-support"))]
841 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
845 self.interactivity().debug_selector = Some(f());
846 self
847 }
848
849 #[cfg(not(any(test, feature = "test-support")))]
850 #[inline]
854 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
855 self
856 }
857
858 fn capture_any_mouse_down(
863 mut self,
864 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
865 ) -> Self {
866 self.interactivity().capture_any_mouse_down(listener);
867 self
868 }
869
870 fn on_any_mouse_down(
875 mut self,
876 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
877 ) -> Self {
878 self.interactivity().on_any_mouse_down(listener);
879 self
880 }
881
882 fn on_mouse_up(
887 mut self,
888 button: MouseButton,
889 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
890 ) -> Self {
891 self.interactivity().on_mouse_up(button, listener);
892 self
893 }
894
895 fn capture_any_mouse_up(
900 mut self,
901 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
902 ) -> Self {
903 self.interactivity().capture_any_mouse_up(listener);
904 self
905 }
906
907 fn on_mouse_pressure(
912 mut self,
913 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
914 ) -> Self {
915 self.interactivity().on_mouse_pressure(listener);
916 self
917 }
918
919 fn capture_mouse_pressure(
924 mut self,
925 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
926 ) -> Self {
927 self.interactivity().capture_mouse_pressure(listener);
928 self
929 }
930
931 fn on_mouse_down_out(
937 mut self,
938 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
939 ) -> Self {
940 self.interactivity().on_mouse_down_out(listener);
941 self
942 }
943
944 fn on_mouse_up_out(
950 mut self,
951 button: MouseButton,
952 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
953 ) -> Self {
954 self.interactivity().on_mouse_up_out(button, listener);
955 self
956 }
957
958 fn on_mouse_move(
963 mut self,
964 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
965 ) -> Self {
966 self.interactivity().on_mouse_move(listener);
967 self
968 }
969
970 fn on_mouse_exit(
975 mut self,
976 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
977 ) -> Self {
978 self.interactivity().on_mouse_exit(listener);
979 self
980 }
981
982 fn on_drag_move<T: 'static>(
990 mut self,
991 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
992 ) -> Self {
993 self.interactivity().on_drag_move(listener);
994 self
995 }
996
997 fn on_scroll_wheel(
1002 mut self,
1003 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
1004 ) -> Self {
1005 self.interactivity().on_scroll_wheel(listener);
1006 self
1007 }
1008
1009 fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
1014 self.interactivity().on_pinch(listener);
1015 self
1016 }
1017
1018 fn capture_pinch(
1023 mut self,
1024 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
1025 ) -> Self {
1026 self.interactivity().capture_pinch(listener);
1027 self
1028 }
1029 fn capture_action<A: Action>(
1034 mut self,
1035 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1036 ) -> Self {
1037 self.interactivity().capture_action(listener);
1038 self
1039 }
1040
1041 #[track_caller]
1046 fn on_action<A: Action>(
1047 mut self,
1048 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1049 ) -> Self {
1050 self.interactivity().on_action(listener);
1051 self
1052 }
1053
1054 fn on_boxed_action(
1061 mut self,
1062 action: &dyn Action,
1063 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1064 ) -> Self {
1065 self.interactivity().on_boxed_action(action, listener);
1066 self
1067 }
1068
1069 fn on_key_down(
1074 mut self,
1075 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1076 ) -> Self {
1077 self.interactivity().on_key_down(listener);
1078 self
1079 }
1080
1081 fn capture_key_down(
1086 mut self,
1087 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1088 ) -> Self {
1089 self.interactivity().capture_key_down(listener);
1090 self
1091 }
1092
1093 fn on_key_up(
1098 mut self,
1099 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1100 ) -> Self {
1101 self.interactivity().on_key_up(listener);
1102 self
1103 }
1104
1105 fn capture_key_up(
1110 mut self,
1111 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1112 ) -> Self {
1113 self.interactivity().capture_key_up(listener);
1114 self
1115 }
1116
1117 fn on_modifiers_changed(
1122 mut self,
1123 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1124 ) -> Self {
1125 self.interactivity().on_modifiers_changed(listener);
1126 self
1127 }
1128
1129 fn drag_over<S: 'static>(
1131 mut self,
1132 f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1133 ) -> Self {
1134 self.interactivity().drag_over_styles.push((
1135 TypeId::of::<S>(),
1136 Box::new(move |currently_dragged: &dyn Any, window, cx| {
1137 f(
1138 StyleRefinement::default(),
1139 currently_dragged.downcast_ref::<S>().unwrap(),
1140 window,
1141 cx,
1142 )
1143 }),
1144 ));
1145 self
1146 }
1147
1148 fn group_drag_over<S: 'static>(
1150 mut self,
1151 group_name: impl Into<SharedString>,
1152 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1153 ) -> Self {
1154 self.interactivity().group_drag_over_styles.push((
1155 TypeId::of::<S>(),
1156 GroupStyle {
1157 group: group_name.into(),
1158 style: Box::new(f(StyleRefinement::default())),
1159 },
1160 ));
1161 self
1162 }
1163
1164 fn on_drop<T: 'static>(
1169 mut self,
1170 listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1171 ) -> Self {
1172 self.interactivity().on_drop(listener);
1173 self
1174 }
1175
1176 fn can_drop(
1179 mut self,
1180 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1181 ) -> Self {
1182 self.interactivity().can_drop(predicate);
1183 self
1184 }
1185
1186 fn occlude(mut self) -> Self {
1190 self.interactivity().occlude_mouse();
1191 self
1192 }
1193
1194 fn window_control_area(mut self, area: WindowControlArea) -> Self {
1197 self.interactivity().window_control_area(area);
1198 self
1199 }
1200
1201 fn block_mouse_except_scroll(mut self) -> Self {
1206 self.interactivity().block_mouse_except_scroll();
1207 self
1208 }
1209
1210 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1213 where
1214 Self: Sized,
1215 {
1216 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1217 self
1218 }
1219
1220 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1223 where
1224 Self: Sized,
1225 {
1226 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1227 self
1228 }
1229
1230 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1235 where
1236 Self: Sized,
1237 {
1238 self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1239 self
1240 }
1241}
1242
1243pub trait StatefulInteractiveElement: InteractiveElement {
1246 fn role(mut self, role: accesskit::Role) -> Self {
1250 debug_assert!(
1251 role != accesskit::Role::GenericContainer,
1252 "GenericContainer is filtered out of the a11y tree and has no effect"
1253 );
1254 self.interactivity().override_role = Some(role);
1255 self
1256 }
1257
1258 fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1260 self.interactivity().aria.label = Some(label.into());
1261 self
1262 }
1263
1264 fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
1269 self.interactivity().aria.description = Some(description.into());
1270 self
1271 }
1272
1273 fn aria_keyshortcuts(mut self, keyshortcuts: impl Into<SharedString>) -> Self {
1279 self.interactivity().aria.keyshortcuts = Some(keyshortcuts.into());
1280 self
1281 }
1282
1283 fn aria_active_descendant(mut self) -> Self {
1299 self.interactivity().report_active_descendant_focus = true;
1300 self
1301 }
1302
1303 fn a11y_synthetic_children(
1313 mut self,
1314 f: impl FnOnce(&mut crate::A11ySubtreeBuilder) + 'static,
1315 ) -> Self {
1316 self.interactivity().a11y_synthetic_children = Some(Box::new(f));
1317 self
1318 }
1319
1320 fn aria_selected(mut self, selected: bool) -> Self {
1322 self.interactivity().aria.selected = Some(selected);
1323 self
1324 }
1325
1326 fn aria_expanded(mut self, expanded: bool) -> Self {
1328 self.interactivity().aria.expanded = Some(expanded);
1329 self
1330 }
1331
1332 fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1334 self.interactivity().aria.toggled = Some(toggled);
1335 self
1336 }
1337
1338 fn aria_numeric_value(mut self, value: f64) -> Self {
1340 self.interactivity().aria.numeric_value = Some(value);
1341 self
1342 }
1343
1344 fn aria_numeric_value_step(mut self, step: f64) -> Self {
1347 self.interactivity().aria.numeric_value_step = Some(step);
1348 self
1349 }
1350
1351 fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
1354 self.interactivity().aria.value = Some(value.into());
1355 self
1356 }
1357
1358 fn aria_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1361 self.interactivity().aria.placeholder = Some(placeholder.into());
1362 self
1363 }
1364
1365 fn aria_min_numeric_value(mut self, value: f64) -> Self {
1367 self.interactivity().aria.min_numeric_value = Some(value);
1368 self
1369 }
1370
1371 fn aria_max_numeric_value(mut self, value: f64) -> Self {
1373 self.interactivity().aria.max_numeric_value = Some(value);
1374 self
1375 }
1376
1377 fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1379 self.interactivity().aria.orientation = Some(orientation);
1380 self
1381 }
1382
1383 fn aria_level(mut self, level: usize) -> Self {
1385 self.interactivity().aria.level = Some(level);
1386 self
1387 }
1388
1389 fn aria_position_in_set(mut self, position: usize) -> Self {
1391 self.interactivity().aria.position_in_set = Some(position);
1392 self
1393 }
1394
1395 fn aria_size_of_set(mut self, size: usize) -> Self {
1397 self.interactivity().aria.size_of_set = Some(size);
1398 self
1399 }
1400
1401 fn aria_row_index(mut self, index: usize) -> Self {
1403 self.interactivity().aria.row_index = Some(index);
1404 self
1405 }
1406
1407 fn aria_column_index(mut self, index: usize) -> Self {
1409 self.interactivity().aria.column_index = Some(index);
1410 self
1411 }
1412
1413 fn aria_row_count(mut self, count: usize) -> Self {
1415 self.interactivity().aria.row_count = Some(count);
1416 self
1417 }
1418
1419 fn aria_column_count(mut self, count: usize) -> Self {
1421 self.interactivity().aria.column_count = Some(count);
1422 self
1423 }
1424
1425 fn on_a11y_action(
1430 mut self,
1431 action: accesskit::Action,
1432 listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1433 + 'static,
1434 ) -> Self {
1435 self.interactivity()
1436 .a11y_action_listeners
1437 .push((action, Box::new(listener)));
1438 self
1439 }
1440
1441 fn focusable(mut self) -> Self {
1443 self.interactivity().focusable = true;
1444 self
1445 }
1446
1447 fn overflow_scroll(mut self) -> Self {
1449 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1450 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1451 self
1452 }
1453
1454 fn overflow_x_scroll(mut self) -> Self {
1456 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1457 self
1458 }
1459
1460 fn overflow_y_scroll(mut self) -> Self {
1462 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1463 self
1464 }
1465
1466 fn restrict_scroll_to_axis(mut self) -> Self {
1470 self.interactivity().base_style.restrict_scroll_to_axis = Some(true);
1471 self
1472 }
1473
1474 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1476 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1477 self
1478 }
1479
1480 fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1482 self.interactivity().scroll_anchor = scroll_anchor;
1483 self
1484 }
1485
1486 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1488 where
1489 Self: Sized,
1490 {
1491 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1492 self
1493 }
1494
1495 fn group_active(
1497 mut self,
1498 group_name: impl Into<SharedString>,
1499 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1500 ) -> Self
1501 where
1502 Self: Sized,
1503 {
1504 self.interactivity().group_active_style = Some(GroupStyle {
1505 group: group_name.into(),
1506 style: Box::new(f(StyleRefinement::default())),
1507 });
1508 self
1509 }
1510
1511 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1516 where
1517 Self: Sized,
1518 {
1519 self.interactivity().on_click(listener);
1520 self
1521 }
1522
1523 fn on_aux_click(
1528 mut self,
1529 listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1530 ) -> Self
1531 where
1532 Self: Sized,
1533 {
1534 self.interactivity().on_aux_click(listener);
1535 self
1536 }
1537
1538 fn on_drag<T, W>(
1546 mut self,
1547 value: T,
1548 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1549 ) -> Self
1550 where
1551 Self: Sized,
1552 T: 'static,
1553 W: 'static + Render,
1554 {
1555 self.interactivity().on_drag(value, constructor);
1556 self
1557 }
1558
1559 fn external_drag_payload<T>(
1565 mut self,
1566 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
1567 ) -> Self
1568 where
1569 Self: Sized,
1570 T: 'static,
1571 {
1572 self.interactivity().external_drag_payload(resolver);
1573 self
1574 }
1575
1576 fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1582 where
1583 Self: Sized,
1584 {
1585 self.interactivity().on_hover(listener);
1586 self
1587 }
1588
1589 fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1592 where
1593 Self: Sized,
1594 {
1595 self.interactivity().tooltip(build_tooltip);
1596 self
1597 }
1598
1599 fn hoverable_tooltip(
1603 mut self,
1604 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1605 ) -> Self
1606 where
1607 Self: Sized,
1608 {
1609 self.interactivity().hoverable_tooltip(build_tooltip);
1610 self
1611 }
1612
1613 fn tooltip_show_delay(mut self, delay: Duration) -> Self
1616 where
1617 Self: Sized,
1618 {
1619 self.interactivity().tooltip_show_delay(delay);
1620 self
1621 }
1622}
1623
1624pub(crate) type MouseDownListener =
1625 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1626pub(crate) type MouseUpListener =
1627 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1628pub(crate) type MousePressureListener =
1629 Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1630pub(crate) type MouseMoveListener =
1631 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1632pub(crate) type MouseExitListener =
1633 Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1634
1635pub(crate) type ScrollWheelListener =
1636 Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1637
1638pub(crate) type PinchListener =
1639 Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1640
1641pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1642
1643pub(crate) struct DragListener {
1644 value: Arc<dyn Any>,
1645 render: Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>,
1646 external_payload: Option<ExternalDragPayloadResolver>,
1647}
1648
1649type ExternalDragPayloadResolver =
1650 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
1651
1652type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1653
1654type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1655
1656pub(crate) struct TooltipBuilder {
1657 build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1658 hoverable: bool,
1659}
1660
1661pub(crate) type KeyDownListener =
1662 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1663
1664pub(crate) type KeyUpListener =
1665 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1666
1667pub(crate) type ModifiersChangedListener =
1668 Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1669
1670pub(crate) type ActionListener =
1671 Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1672
1673#[track_caller]
1675pub fn div() -> Div {
1676 Div {
1677 interactivity: Interactivity::new(),
1678 children: SmallVec::default(),
1679 prepaint_listener: None,
1680 image_cache: None,
1681 prepaint_order_fn: None,
1682 }
1683}
1684
1685pub struct Div {
1687 interactivity: Interactivity,
1688 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1689 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1690 image_cache: Option<Box<dyn ImageCacheProvider>>,
1691 prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1692}
1693
1694impl Div {
1695 pub fn on_children_prepainted(
1698 mut self,
1699 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1700 ) -> Self {
1701 self.prepaint_listener = Some(Box::new(listener));
1702 self
1703 }
1704
1705 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1707 self.image_cache = Some(Box::new(cache));
1708 self
1709 }
1710
1711 pub fn with_dynamic_prepaint_order(
1720 mut self,
1721 order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1722 ) -> Self {
1723 self.prepaint_order_fn = Some(Box::new(order_fn));
1724 self
1725 }
1726}
1727
1728pub struct DivFrameState {
1735 child_layout_ids: SmallVec<[LayoutId; 2]>,
1736}
1737
1738#[derive(Clone)]
1740pub struct DivInspectorState {
1741 #[cfg(any(feature = "inspector", debug_assertions))]
1745 pub base_style: Box<StyleRefinement>,
1746 pub bounds: Bounds<Pixels>,
1748 pub content_size: Size<Pixels>,
1750}
1751
1752impl Styled for Div {
1753 fn style(&mut self) -> &mut StyleRefinement {
1754 &mut self.interactivity.base_style
1755 }
1756}
1757
1758impl InteractiveElement for Div {
1759 fn interactivity(&mut self) -> &mut Interactivity {
1760 &mut self.interactivity
1761 }
1762}
1763
1764impl ParentElement for Div {
1765 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1766 self.children
1767 .extend(elements.into_iter().map(StackSafe::new))
1768 }
1769}
1770
1771impl Element for Div {
1772 type RequestLayoutState = DivFrameState;
1773 type PrepaintState = Option<Hitbox>;
1774
1775 fn id(&self) -> Option<ElementId> {
1776 self.interactivity.element_id.clone()
1777 }
1778
1779 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1780 self.interactivity.source_location()
1781 }
1782
1783 fn a11y_role(&self) -> Option<accesskit::Role> {
1784 self.interactivity
1787 .override_role
1788 .filter(|role| *role != accesskit::Role::GenericContainer)
1789 }
1790
1791 fn write_a11y_info(&self, node: &mut accesskit::Node) {
1792 self.interactivity.write_a11y_info(node);
1793 }
1794
1795 fn a11y_synthetic_children(
1796 &mut self,
1797 _prepaint: &mut Self::PrepaintState,
1798 builder: &mut crate::A11ySubtreeBuilder,
1799 ) {
1800 if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
1801 f(builder);
1802 }
1803 }
1804
1805 #[stacksafe]
1806 fn request_layout(
1807 &mut self,
1808 global_id: Option<&GlobalElementId>,
1809 inspector_id: Option<&InspectorElementId>,
1810 window: &mut Window,
1811 cx: &mut App,
1812 ) -> (LayoutId, Self::RequestLayoutState) {
1813 let mut child_layout_ids = SmallVec::new();
1814 let image_cache = self
1815 .image_cache
1816 .as_mut()
1817 .map(|provider| provider.provide(window, cx));
1818
1819 let layout_id = window.with_image_cache(image_cache, |window| {
1820 self.interactivity.request_layout(
1821 global_id,
1822 inspector_id,
1823 window,
1824 cx,
1825 |style, window, cx| {
1826 window.with_text_style(style.text_style().cloned(), |window| {
1827 child_layout_ids = self
1828 .children
1829 .iter_mut()
1830 .map(|child| child.request_layout(window, cx))
1831 .collect::<SmallVec<_>>();
1832 window.request_layout(style, child_layout_ids.iter().copied(), cx)
1833 })
1834 },
1835 )
1836 });
1837
1838 (layout_id, DivFrameState { child_layout_ids })
1839 }
1840
1841 #[stacksafe]
1842 fn prepaint(
1843 &mut self,
1844 global_id: Option<&GlobalElementId>,
1845 inspector_id: Option<&InspectorElementId>,
1846 bounds: Bounds<Pixels>,
1847 request_layout: &mut Self::RequestLayoutState,
1848 window: &mut Window,
1849 cx: &mut App,
1850 ) -> Option<Hitbox> {
1851 let image_cache = self
1852 .image_cache
1853 .as_mut()
1854 .map(|provider| provider.provide(window, cx));
1855
1856 let has_prepaint_listener = self.prepaint_listener.is_some();
1857 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1858 request_layout.child_layout_ids.len()
1859 } else {
1860 0
1861 });
1862
1863 let mut child_min = point(Pixels::MAX, Pixels::MAX);
1864 let mut child_max = Point::default();
1865 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1866 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1867 }
1868 let content_size = if request_layout.child_layout_ids.is_empty() {
1869 bounds.size
1870 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1871 let mut state = scroll_handle.0.borrow_mut();
1872 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1873 for child_layout_id in &request_layout.child_layout_ids {
1874 let child_bounds = window.layout_bounds(*child_layout_id);
1875 child_min = child_min.min(&child_bounds.origin);
1876 child_max = child_max.max(&child_bounds.bottom_right());
1877 state.child_bounds.push(child_bounds);
1878 }
1879 (child_max - child_min).into()
1880 } else {
1881 for child_layout_id in &request_layout.child_layout_ids {
1882 let child_bounds = window.layout_bounds(*child_layout_id);
1883 child_min = child_min.min(&child_bounds.origin);
1884 child_max = child_max.max(&child_bounds.bottom_right());
1885
1886 if has_prepaint_listener {
1887 children_bounds.push(child_bounds);
1888 }
1889 }
1890 (child_max - child_min).into()
1891 };
1892
1893 if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1894 scroll_handle.scroll_to_active_item();
1895 }
1896
1897 self.interactivity.prepaint(
1898 global_id,
1899 inspector_id,
1900 bounds,
1901 content_size,
1902 window,
1903 cx,
1904 |style, scroll_offset, hitbox, window, cx| {
1905 if style.display == Display::None {
1907 return hitbox;
1908 }
1909
1910 window.with_image_cache(image_cache, |window| {
1911 window.with_element_offset(scroll_offset, |window| {
1912 if let Some(order_fn) = &self.prepaint_order_fn {
1913 let order = order_fn(window, cx);
1914 for idx in order {
1915 if let Some(child) = self.children.get_mut(idx) {
1916 child.prepaint(window, cx);
1917 }
1918 }
1919 } else {
1920 for child in &mut self.children {
1921 child.prepaint(window, cx);
1922 }
1923 }
1924 });
1925
1926 if let Some(listener) = self.prepaint_listener.as_ref() {
1927 listener(children_bounds, window, cx);
1928 }
1929 });
1930
1931 hitbox
1932 },
1933 )
1934 }
1935
1936 #[stacksafe]
1937 fn paint(
1938 &mut self,
1939 global_id: Option<&GlobalElementId>,
1940 inspector_id: Option<&InspectorElementId>,
1941 bounds: Bounds<Pixels>,
1942 _request_layout: &mut Self::RequestLayoutState,
1943 hitbox: &mut Option<Hitbox>,
1944 window: &mut Window,
1945 cx: &mut App,
1946 ) {
1947 let image_cache = self
1948 .image_cache
1949 .as_mut()
1950 .map(|provider| provider.provide(window, cx));
1951
1952 window.with_image_cache(image_cache, |window| {
1953 self.interactivity.paint(
1954 global_id,
1955 inspector_id,
1956 bounds,
1957 hitbox.as_ref(),
1958 window,
1959 cx,
1960 |style, window, cx| {
1961 if style.display == Display::None {
1963 return;
1964 }
1965
1966 for child in &mut self.children {
1967 child.paint(window, cx);
1968 }
1969 },
1970 )
1971 });
1972 }
1973}
1974
1975impl IntoElement for Div {
1976 type Element = Self;
1977
1978 fn into_element(self) -> Self::Element {
1979 self
1980 }
1981}
1982
1983#[derive(Default)]
1984pub(crate) struct AriaProperties {
1985 pub(crate) label: Option<SharedString>,
1986 pub(crate) description: Option<SharedString>,
1987 pub(crate) keyshortcuts: Option<SharedString>,
1988 pub(crate) selected: Option<bool>,
1989 pub(crate) expanded: Option<bool>,
1990 pub(crate) toggled: Option<accesskit::Toggled>,
1991 pub(crate) numeric_value: Option<f64>,
1992 pub(crate) min_numeric_value: Option<f64>,
1993 pub(crate) max_numeric_value: Option<f64>,
1994 pub(crate) numeric_value_step: Option<f64>,
1995 pub(crate) value: Option<SharedString>,
1996 pub(crate) placeholder: Option<SharedString>,
1997 pub(crate) orientation: Option<accesskit::Orientation>,
1998 pub(crate) level: Option<usize>,
1999 pub(crate) position_in_set: Option<usize>,
2000 pub(crate) size_of_set: Option<usize>,
2001 pub(crate) row_index: Option<usize>,
2002 pub(crate) column_index: Option<usize>,
2003 pub(crate) row_count: Option<usize>,
2004 pub(crate) column_count: Option<usize>,
2005}
2006
2007#[derive(Default)]
2010pub struct Interactivity {
2011 pub element_id: Option<ElementId>,
2013 pub active: Option<bool>,
2015 pub hovered: Option<bool>,
2018 pub(crate) tooltip_id: Option<TooltipId>,
2019 pub(crate) content_size: Size<Pixels>,
2020 pub(crate) key_context: Option<KeyContext>,
2021 pub(crate) focusable: bool,
2022 pub(crate) tracked_focus_handle: Option<FocusHandle>,
2023 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2024 pub(crate) scroll_anchor: Option<ScrollAnchor>,
2025 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2026 pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2027 pub(crate) group: Option<SharedString>,
2028 pub base_style: Box<StyleRefinement>,
2031 pub(crate) focus_style: Option<Box<StyleRefinement>>,
2032 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2033 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2034 pub(crate) hover_style: Option<Box<StyleRefinement>>,
2035 pub(crate) group_hover_style: Option<GroupStyle>,
2036 pub(crate) active_style: Option<Box<StyleRefinement>>,
2037 pub(crate) group_active_style: Option<GroupStyle>,
2038 pub(crate) drag_over_styles: Vec<(
2039 TypeId,
2040 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2041 )>,
2042 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
2043 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
2044 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
2045 pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
2046 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
2047 pub(crate) mouse_exit_listeners: Vec<MouseExitListener>,
2048 pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
2049 pub(crate) pinch_listeners: Vec<PinchListener>,
2050 pub(crate) key_down_listeners: Vec<KeyDownListener>,
2051 pub(crate) key_up_listeners: Vec<KeyUpListener>,
2052 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
2053 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
2054 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
2055 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
2056 pub(crate) click_listeners: Vec<ClickListener>,
2057 pub(crate) aux_click_listeners: Vec<ClickListener>,
2058 pub(crate) drag_listener: Option<DragListener>,
2059 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2060 pub(crate) tooltip_builder: Option<TooltipBuilder>,
2061 pub(crate) tooltip_show_delay: Option<Duration>,
2062 pub(crate) window_control: Option<WindowControlArea>,
2063 pub(crate) hitbox_behavior: HitboxBehavior,
2064 pub(crate) tab_index: Option<isize>,
2065 pub(crate) tab_group: bool,
2066 pub(crate) tab_stop: bool,
2067
2068 pub(crate) a11y_action_listeners:
2069 Vec<(accesskit::Action, crate::window::a11y::A11yActionListener)>,
2070 pub(crate) a11y_synthetic_children: Option<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2071 pub(crate) report_active_descendant_focus: bool,
2072 pub(crate) override_role: Option<accesskit::Role>,
2073 pub(crate) aria: AriaProperties,
2074
2075 #[cfg(any(feature = "inspector", debug_assertions))]
2076 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2077
2078 #[cfg(any(test, feature = "test-support"))]
2079 pub(crate) debug_selector: Option<String>,
2080}
2081
2082impl Interactivity {
2083 pub fn request_layout(
2085 &mut self,
2086 global_id: Option<&GlobalElementId>,
2087 _inspector_id: Option<&InspectorElementId>,
2088 window: &mut Window,
2089 cx: &mut App,
2090 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2091 ) -> LayoutId {
2092 #[cfg(any(feature = "inspector", debug_assertions))]
2093 window.with_inspector_state(
2094 _inspector_id,
2095 cx,
2096 |inspector_state: &mut Option<DivInspectorState>, _window| {
2097 if let Some(inspector_state) = inspector_state {
2098 self.base_style = inspector_state.base_style.clone();
2099 } else {
2100 *inspector_state = Some(DivInspectorState {
2101 base_style: self.base_style.clone(),
2102 bounds: Default::default(),
2103 content_size: Default::default(),
2104 })
2105 }
2106 },
2107 );
2108
2109 window.with_optional_element_state::<InteractiveElementState, _>(
2110 global_id,
2111 |element_state, window| {
2112 let mut element_state =
2113 element_state.map(|element_state| element_state.unwrap_or_default());
2114
2115 if let Some(element_state) = element_state.as_ref()
2116 && cx.has_active_drag()
2117 {
2118 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2119 *pending_mouse_down.borrow_mut() = None;
2120 }
2121 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2122 *clicked_state.borrow_mut() = ElementClickedState::default();
2123 }
2124 }
2125
2126 if self.focusable
2131 && self.tracked_focus_handle.is_none()
2132 && let Some(element_state) = element_state.as_mut()
2133 {
2134 let mut handle = element_state
2135 .focus_handle
2136 .get_or_insert_with(|| cx.focus_handle())
2137 .clone()
2138 .tab_stop(self.tab_stop);
2139
2140 if let Some(index) = self.tab_index {
2141 handle = handle.tab_index(index);
2142 }
2143
2144 self.tracked_focus_handle = Some(handle);
2145 }
2146
2147 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2148 let scroll_handle_state = scroll_handle.0.borrow();
2149 self.scroll_offset = Some(scroll_handle_state.offset.clone());
2150 self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2151 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2152 || self.base_style.overflow.y == Some(Overflow::Scroll))
2153 && let Some(element_state) = element_state.as_mut()
2154 {
2155 self.scroll_offset = Some(
2156 element_state
2157 .scroll_offset
2158 .get_or_insert_with(Rc::default)
2159 .clone(),
2160 );
2161 self.ongoing_scroll = Some(
2162 element_state
2163 .ongoing_scroll
2164 .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2165 .clone(),
2166 );
2167 }
2168
2169 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2170 let layout_id = f(style, window, cx);
2171 (layout_id, element_state)
2172 },
2173 )
2174 }
2175
2176 pub fn prepaint<R>(
2178 &mut self,
2179 global_id: Option<&GlobalElementId>,
2180 _inspector_id: Option<&InspectorElementId>,
2181 bounds: Bounds<Pixels>,
2182 content_size: Size<Pixels>,
2183 window: &mut Window,
2184 cx: &mut App,
2185 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2186 ) -> R {
2187 self.content_size = content_size;
2188
2189 #[cfg(any(feature = "inspector", debug_assertions))]
2190 window.with_inspector_state(
2191 _inspector_id,
2192 cx,
2193 |inspector_state: &mut Option<DivInspectorState>, _window| {
2194 if let Some(inspector_state) = inspector_state {
2195 inspector_state.bounds = bounds;
2196 inspector_state.content_size = content_size;
2197 }
2198 },
2199 );
2200
2201 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2202 window.set_focus_handle(focus_handle, cx);
2203
2204 if window.a11y.is_active() {
2205 if let Some(global_id) = global_id {
2206 let node_id = global_id.accesskit_node_id();
2207 window.a11y.set_focusable(node_id, focus_handle.id);
2208 if focus_handle.is_focused(window) {
2209 window.a11y.set_focus(node_id);
2210 }
2211 } else if focus_handle.is_focused(window) {
2212 window
2216 .a11y
2217 .note_focus_without_node(focus_handle.id, "it has no element id");
2218 }
2219 }
2220 }
2221
2222 if self.report_active_descendant_focus && window.a11y.is_active() {
2223 if let Some(global_id) = global_id {
2224 window
2225 .a11y
2226 .set_active_descendant(global_id.accesskit_node_id());
2227 }
2228 }
2229 window.with_optional_element_state::<InteractiveElementState, _>(
2230 global_id,
2231 |element_state, window| {
2232 let mut element_state =
2233 element_state.map(|element_state| element_state.unwrap_or_default());
2234 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2235
2236 if let Some(element_state) = element_state.as_mut() {
2237 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2238 let clicked_state = clicked_state.borrow();
2239 self.active = Some(clicked_state.element);
2240 }
2241 if self.hover_style.is_some() || self.group_hover_style.is_some() {
2242 element_state
2243 .hover_state
2244 .get_or_insert_with(Default::default);
2245 }
2246 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2247 if self.tooltip_builder.is_some() {
2248 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2249 } else {
2250 element_state.active_tooltip.take();
2252 }
2253 }
2254 }
2255
2256 window.with_text_style(style.text_style().cloned(), |window| {
2257 window.with_content_mask(
2258 style.overflow_mask(bounds, window.rem_size()),
2259 |window| {
2260 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2261 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2262 } else {
2263 None
2264 };
2265
2266 let scroll_offset =
2267 self.clamp_scroll_position(bounds, &style, window, cx);
2268 let result = f(&style, scroll_offset, hitbox, window, cx);
2269 (result, element_state)
2270 },
2271 )
2272 })
2273 },
2274 )
2275 }
2276
2277 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2278 self.hitbox_behavior != HitboxBehavior::Normal
2279 || self.window_control.is_some()
2280 || style.mouse_cursor.is_some()
2281 || self.group.is_some()
2282 || self.scroll_offset.is_some()
2283 || self.tracked_focus_handle.is_some()
2284 || self.hover_style.is_some()
2285 || self.group_hover_style.is_some()
2286 || self.hover_listener.is_some()
2287 || !self.mouse_up_listeners.is_empty()
2288 || !self.mouse_pressure_listeners.is_empty()
2289 || !self.mouse_down_listeners.is_empty()
2290 || !self.mouse_move_listeners.is_empty()
2291 || !self.mouse_exit_listeners.is_empty()
2292 || !self.click_listeners.is_empty()
2293 || !self.aux_click_listeners.is_empty()
2294 || !self.scroll_wheel_listeners.is_empty()
2295 || self.has_pinch_listeners()
2296 || self.drag_listener.is_some()
2297 || !self.drop_listeners.is_empty()
2298 || !self.drag_over_styles.is_empty()
2299 || self.tooltip_builder.is_some()
2300 || window.is_inspector_picking(cx)
2301 }
2302
2303 fn clamp_scroll_position(
2304 &self,
2305 bounds: Bounds<Pixels>,
2306 style: &Style,
2307 window: &mut Window,
2308 _cx: &mut App,
2309 ) -> Point<Pixels> {
2310 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2311 const ROUNDING_FACTOR: f32 = 100.0;
2312 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2313 }
2314
2315 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2316 let mut scroll_to_bottom = false;
2317 let mut tracked_scroll_handle = self
2318 .tracked_scroll_handle
2319 .as_ref()
2320 .map(|handle| handle.0.borrow_mut());
2321 if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2322 scroll_handle_state.overflow = style.overflow;
2323 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2324 }
2325
2326 let rem_size = window.rem_size();
2327 let padding = style
2332 .padding
2333 .to_pixels(bounds.size.into(), rem_size)
2334 .map(|edge| window.pixel_snap(*edge));
2335 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2336 let padded_content_size = self.content_size + padding_size;
2343 let scroll_max = Point::from(padded_content_size - bounds.size)
2344 .map(round_to_two_decimals)
2345 .max(&Default::default());
2346 let mut scroll_offset = scroll_offset.borrow_mut();
2349
2350 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2351 if scroll_to_bottom {
2352 scroll_offset.y = -scroll_max.y;
2353 } else {
2354 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2355 }
2356
2357 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2358 scroll_handle_state.max_offset = scroll_max;
2359 scroll_handle_state.bounds = bounds;
2360 }
2361
2362 *scroll_offset
2363 } else {
2364 Point::default()
2365 }
2366 }
2367
2368 pub fn paint(
2377 &mut self,
2378 global_id: Option<&GlobalElementId>,
2379 _inspector_id: Option<&InspectorElementId>,
2380 bounds: Bounds<Pixels>,
2381 hitbox: Option<&Hitbox>,
2382 window: &mut Window,
2383 cx: &mut App,
2384 f: impl FnOnce(&Style, &mut Window, &mut App),
2385 ) {
2386 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2387 window.with_optional_element_state::<InteractiveElementState, _>(
2388 global_id,
2389 |element_state, window| {
2390 let mut element_state =
2391 element_state.map(|element_state| element_state.unwrap_or_default());
2392
2393 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2394
2395 #[cfg(any(feature = "test-support", test))]
2396 if let Some(debug_selector) = &self.debug_selector {
2397 window
2398 .next_frame
2399 .debug_bounds
2400 .insert(debug_selector.clone(), bounds);
2401 }
2402
2403 self.paint_hover_group_handler(window, cx);
2404
2405 if style.visibility == Visibility::Hidden {
2406 return ((), element_state);
2407 }
2408
2409 let mut tab_group = None;
2410 if self.tab_group {
2411 tab_group = self.tab_index;
2412 }
2413
2414 window.with_element_opacity(style.opacity, |window| {
2415 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2416 window.with_text_style(style.text_style().cloned(), |window| {
2417 window.with_content_mask(
2418 style.overflow_mask(bounds, window.rem_size()),
2419 |window| {
2420 window.with_tab_group(tab_group, |window| {
2421 if let Some(focus_handle) = &self.tracked_focus_handle {
2430 window.next_frame.tab_stops.insert(focus_handle);
2431 }
2432 if let Some(hitbox) = hitbox {
2433 #[cfg(debug_assertions)]
2434 self.paint_debug_info(
2435 global_id, hitbox, &style, window, cx,
2436 );
2437
2438 if let Some(drag) = cx.active_drag.as_ref() {
2439 if let Some(mouse_cursor) = drag.cursor_style {
2440 window.set_window_cursor_style(mouse_cursor);
2441 }
2442 } else {
2443 if let Some(mouse_cursor) = style.mouse_cursor {
2444 window.set_cursor_style(mouse_cursor, hitbox);
2445 }
2446 }
2447
2448 if let Some(group) = self.group.clone() {
2449 GroupHitboxes::push(group, hitbox.id, cx);
2450 }
2451
2452 if let Some(area) = self.window_control {
2453 window.insert_window_control_hitbox(
2454 area,
2455 hitbox.clone(),
2456 );
2457 }
2458
2459 self.paint_mouse_listeners(
2460 hitbox,
2461 element_state.as_mut(),
2462 window,
2463 cx,
2464 );
2465 self.paint_scroll_listener(hitbox, &style, window, cx);
2466 }
2467
2468 self.paint_keyboard_listeners(window, cx);
2469
2470 if window.a11y.is_active() {
2471 if let Some(global_id) = global_id {
2472 if !self.a11y_action_listeners.is_empty() {
2473 let node_id = global_id.accesskit_node_id();
2474 for (action, listener) in
2475 self.a11y_action_listeners.drain(..)
2476 {
2477 window.on_a11y_action(
2478 node_id, action, listener,
2479 );
2480 }
2481 }
2482 }
2483 }
2484
2485 f(&style, window, cx);
2486
2487 if let Some(_hitbox) = hitbox {
2488 #[cfg(any(feature = "inspector", debug_assertions))]
2489 window.insert_inspector_hitbox(
2490 _hitbox.id,
2491 _inspector_id,
2492 cx,
2493 );
2494
2495 if let Some(group) = self.group.as_ref() {
2496 GroupHitboxes::pop(group, cx);
2497 }
2498 }
2499 })
2500 },
2501 );
2502 });
2503 });
2504 });
2505
2506 ((), element_state)
2507 },
2508 );
2509 }
2510
2511 #[cfg(debug_assertions)]
2512 fn paint_debug_info(
2513 &self,
2514 global_id: Option<&GlobalElementId>,
2515 hitbox: &Hitbox,
2516 style: &Style,
2517 window: &mut Window,
2518 cx: &mut App,
2519 ) {
2520 use crate::{BorderStyle, TextAlign};
2521
2522 if let Some(global_id) = global_id
2523 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2524 && hitbox.is_hovered(window)
2525 {
2526 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2527 let element_id = format!("{global_id:?}");
2528 let str_len = element_id.len();
2529
2530 let render_debug_text = |window: &mut Window| {
2531 if let Some(text) = window
2532 .text_system()
2533 .shape_text(
2534 element_id.into(),
2535 FONT_SIZE,
2536 &[window.text_style().to_run(str_len)],
2537 None,
2538 None,
2539 )
2540 .ok()
2541 .and_then(|mut text| text.pop())
2542 {
2543 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2544 .ok();
2545
2546 let text_bounds = crate::Bounds {
2547 origin: hitbox.origin,
2548 size: text.size(FONT_SIZE),
2549 };
2550 if let Some(source_location) = self.source_location
2551 && text_bounds.contains(&window.mouse_position())
2552 && window.modifiers().secondary()
2553 {
2554 let secondary_held = window.modifiers().secondary();
2555 window.on_key_event({
2556 move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2557 if e.modifiers.secondary() != secondary_held
2558 && text_bounds.contains(&window.mouse_position())
2559 {
2560 window.refresh();
2561 }
2562 }
2563 });
2564
2565 let was_hovered = hitbox.is_hovered(window);
2566 let current_view = window.current_view();
2567 window.on_mouse_event({
2568 let hitbox = hitbox.clone();
2569 move |_: &MouseMoveEvent, phase, window, cx| {
2570 if phase == DispatchPhase::Capture {
2571 let hovered = hitbox.is_hovered(window);
2572 if hovered != was_hovered {
2573 cx.notify(current_view)
2574 }
2575 }
2576 }
2577 });
2578
2579 window.on_mouse_event({
2580 let hitbox = hitbox.clone();
2581 move |e: &crate::MouseDownEvent, phase, window, cx| {
2582 if text_bounds.contains(&e.position)
2583 && phase.capture()
2584 && hitbox.is_hovered(window)
2585 {
2586 cx.stop_propagation();
2587 let Ok(dir) = std::env::current_dir() else {
2588 return;
2589 };
2590
2591 eprintln!(
2592 "This element was created at:\n{}:{}:{}",
2593 dir.join(source_location.file()).to_string_lossy(),
2594 source_location.line(),
2595 source_location.column()
2596 );
2597 }
2598 }
2599 });
2600 window.paint_quad(crate::outline(
2601 crate::Bounds {
2602 origin: hitbox.origin
2603 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2604 size: crate::Size {
2605 width: text_bounds.size.width,
2606 height: crate::px(1.),
2607 },
2608 },
2609 crate::red(),
2610 BorderStyle::default(),
2611 ))
2612 }
2613 }
2614 };
2615
2616 window.with_text_style(
2617 Some(crate::TextStyleRefinement {
2618 color: Some(crate::red()),
2619 line_height: Some(FONT_SIZE.into()),
2620 background_color: Some(crate::white()),
2621 ..Default::default()
2622 }),
2623 render_debug_text,
2624 )
2625 }
2626 }
2627
2628 fn paint_mouse_listeners(
2629 &mut self,
2630 hitbox: &Hitbox,
2631 element_state: Option<&mut InteractiveElementState>,
2632 window: &mut Window,
2633 cx: &mut App,
2634 ) {
2635 let is_focused = self
2636 .tracked_focus_handle
2637 .as_ref()
2638 .map(|handle| handle.is_focused(window))
2639 .unwrap_or(false);
2640
2641 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2645 let hitbox = hitbox.clone();
2646 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2647 if phase == DispatchPhase::Bubble
2648 && hitbox.is_hovered(window)
2649 && !window.default_prevented()
2650 {
2651 window.focus(&focus_handle, cx);
2652 window.prevent_default();
2655 }
2656 });
2657 }
2658
2659 for listener in self.mouse_down_listeners.drain(..) {
2660 let hitbox = hitbox.clone();
2661 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2662 listener(event, phase, &hitbox, window, cx);
2663 })
2664 }
2665
2666 for listener in self.mouse_up_listeners.drain(..) {
2667 let hitbox = hitbox.clone();
2668 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2669 listener(event, phase, &hitbox, window, cx);
2670 })
2671 }
2672
2673 for listener in self.mouse_pressure_listeners.drain(..) {
2674 let hitbox = hitbox.clone();
2675 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2676 listener(event, phase, &hitbox, window, cx);
2677 })
2678 }
2679
2680 for listener in self.mouse_move_listeners.drain(..) {
2681 let hitbox = hitbox.clone();
2682 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2683 listener(event, phase, &hitbox, window, cx);
2684 })
2685 }
2686
2687 for listener in self.mouse_exit_listeners.drain(..) {
2688 let hitbox = hitbox.clone();
2689 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2690 listener(event, phase, &hitbox, window, cx);
2691 })
2692 }
2693
2694 for listener in self.scroll_wheel_listeners.drain(..) {
2695 let hitbox = hitbox.clone();
2696 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2697 listener(event, phase, &hitbox, window, cx);
2698 })
2699 }
2700
2701 for listener in self.pinch_listeners.drain(..) {
2702 let hitbox = hitbox.clone();
2703 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2704 listener(event, phase, &hitbox, window, cx);
2705 })
2706 }
2707
2708 if self.hover_style.is_some()
2709 || self.base_style.mouse_cursor.is_some()
2710 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2711 {
2712 let hitbox = hitbox.clone();
2713 let hover_state = self.hover_style.as_ref().and_then(|_| {
2714 element_state
2715 .as_ref()
2716 .and_then(|state| state.hover_state.as_ref())
2717 .cloned()
2718 });
2719 let current_view = window.current_view();
2720
2721 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2722 let hovered = hitbox.is_hovered(window);
2723 let was_hovered = hover_state
2724 .as_ref()
2725 .is_some_and(|state| state.borrow().element);
2726 if phase == DispatchPhase::Capture && hovered != was_hovered {
2727 if let Some(hover_state) = &hover_state {
2728 hover_state.borrow_mut().element = hovered;
2729 cx.notify(current_view);
2730 }
2731 }
2732 });
2733 }
2734
2735 if let Some(group_hover) = self.group_hover_style.as_ref() {
2736 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2737 let hover_state = element_state
2738 .as_ref()
2739 .and_then(|element| element.hover_state.as_ref())
2740 .cloned();
2741 let current_view = window.current_view();
2742
2743 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2744 let group_hovered = group_hitbox_id.is_hovered(window);
2745 let was_group_hovered = hover_state
2746 .as_ref()
2747 .is_some_and(|state| state.borrow().group);
2748 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2749 if let Some(hover_state) = &hover_state {
2750 hover_state.borrow_mut().group = group_hovered;
2751 cx.notify(current_view);
2752 }
2753 }
2754 });
2755 }
2756 }
2757
2758 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2759
2760 let mut drag_listener = mem::take(&mut self.drag_listener);
2761 let drop_listeners = mem::take(&mut self.drop_listeners);
2762 let click_listeners = mem::take(&mut self.click_listeners);
2763 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2764 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2765
2766 if !drop_listeners.is_empty() {
2767 let hitbox = hitbox.clone();
2768 window.on_mouse_event({
2769 move |_: &MouseUpEvent, phase, window, cx| {
2770 if let Some(drag) = &cx.active_drag
2771 && phase == DispatchPhase::Bubble
2772 && hitbox.is_hovered(window)
2773 {
2774 let drag_state_type = drag.value.as_ref().type_id();
2775 for (drop_state_type, listener) in &drop_listeners {
2776 if *drop_state_type == drag_state_type {
2777 let drag = cx
2778 .active_drag
2779 .take()
2780 .expect("checked for type drag state type above");
2781
2782 let mut can_drop = true;
2783 if let Some(predicate) = &can_drop_predicate {
2784 can_drop = predicate(drag.value.as_ref(), window, cx);
2785 }
2786
2787 if can_drop {
2788 listener(drag.value.as_ref(), window, cx);
2789 window.refresh();
2790 cx.stop_propagation();
2791 }
2792 }
2793 }
2794 }
2795 }
2796 });
2797 }
2798
2799 if let Some(element_state) = element_state {
2800 if !click_listeners.is_empty()
2801 || !aux_click_listeners.is_empty()
2802 || drag_listener.is_some()
2803 {
2804 let pending_mouse_down = element_state
2805 .pending_mouse_down
2806 .get_or_insert_with(Default::default)
2807 .clone();
2808
2809 let pending_keyboard_down = element_state
2810 .pending_keyboard_down
2811 .get_or_insert_with(Default::default)
2812 .clone();
2813
2814 let clicked_state = element_state
2815 .clicked_state
2816 .get_or_insert_with(Default::default)
2817 .clone();
2818
2819 window.on_mouse_event({
2820 let pending_mouse_down = pending_mouse_down.clone();
2821 let hitbox = hitbox.clone();
2822 let has_aux_click_listeners = !aux_click_listeners.is_empty();
2823 move |event: &MouseDownEvent, phase, window, _cx| {
2824 if phase == DispatchPhase::Bubble
2825 && (event.button == MouseButton::Left || has_aux_click_listeners)
2826 && hitbox.is_hovered(window)
2827 {
2828 *pending_mouse_down.borrow_mut() = Some(event.clone());
2829 window.refresh();
2830 }
2831 }
2832 });
2833
2834 window.on_mouse_event({
2835 let pending_mouse_down = pending_mouse_down.clone();
2836 let hitbox = hitbox.clone();
2837 move |event: &MouseMoveEvent, phase, window, cx| {
2838 if phase == DispatchPhase::Capture {
2839 return;
2840 }
2841
2842 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2843 if let Some(mouse_down) = pending_mouse_down.clone()
2844 && !cx.has_active_drag()
2845 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2846 && let Some(listener) = drag_listener.take()
2847 && mouse_down.button == MouseButton::Left
2848 {
2849 *clicked_state.borrow_mut() = ElementClickedState::default();
2850 let cursor_offset = event.position - hitbox.origin;
2851 let drag = (listener.render)(
2852 listener.value.as_ref(),
2853 cursor_offset,
2854 window,
2855 cx,
2856 );
2857 let external_payload_source =
2858 listener.external_payload.map(|external_payload| {
2859 let value = listener.value.clone();
2860 Box::new(move |window: &mut Window, cx: &mut App| {
2861 external_payload(value.as_ref(), window, cx)
2862 })
2863 as ExternalDragPayloadSource
2864 });
2865 cx.active_drag = Some(AnyDrag {
2866 view: drag,
2867 value: listener.value,
2868 cursor_offset,
2869 cursor_style: drag_cursor_style,
2870 external_payload_source,
2871 });
2872 pending_mouse_down.take();
2873 window.refresh();
2874 cx.stop_propagation();
2875 }
2876 }
2877 });
2878
2879 if is_focused {
2880 window.on_key_event({
2890 let pending_keyboard_down = pending_keyboard_down.clone();
2891 move |event: &KeyDownEvent, phase, window, _cx| {
2892 if phase.bubble() && !window.default_prevented() {
2893 let stroke = &event.keystroke;
2894 let is_activation_key = (stroke.key.eq("enter")
2895 || stroke.key.eq("space"))
2896 && !stroke.modifiers.modified();
2897 *pending_keyboard_down.borrow_mut() =
2898 is_activation_key.then_some(window.focus_generation);
2899 }
2900 }
2901 });
2902
2903 window.on_key_event({
2905 let click_listeners = click_listeners.clone();
2906 let hitbox = hitbox.clone();
2907 move |event: &KeyUpEvent, phase, window, cx| {
2908 if phase.bubble() && !window.default_prevented() {
2909 let stroke = &event.keystroke;
2910 let keyboard_button = if stroke.key.eq("enter") {
2911 Some(KeyboardButton::Enter)
2912 } else if stroke.key.eq("space") {
2913 Some(KeyboardButton::Space)
2914 } else {
2915 None
2916 };
2917
2918 if let Some(button) = keyboard_button
2919 && !stroke.modifiers.modified()
2920 {
2921 let pending =
2922 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
2923 if pending != Some(window.focus_generation) {
2924 return;
2925 }
2926
2927 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2928 button,
2929 bounds: hitbox.bounds,
2930 });
2931
2932 for listener in &click_listeners {
2933 listener(&click_event, window, cx);
2934 }
2935 } else {
2936 *pending_keyboard_down.borrow_mut() = None;
2940 }
2941 }
2942 }
2943 });
2944 }
2945
2946 window.on_mouse_event({
2947 let mut captured_mouse_down = None;
2948 let hitbox = hitbox.clone();
2949 move |event: &MouseUpEvent, phase, window, cx| match phase {
2950 DispatchPhase::Capture => {
2954 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2955 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2956 captured_mouse_down = pending_mouse_down.take();
2957 window.refresh();
2958 } else if pending_mouse_down.is_some() {
2959 pending_mouse_down.take();
2965 window.refresh();
2966 }
2967 }
2968 DispatchPhase::Bubble => {
2970 if let Some(mouse_down) = captured_mouse_down.take() {
2971 let btn = mouse_down.button;
2972
2973 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2974 down: mouse_down,
2975 up: event.clone(),
2976 });
2977
2978 match btn {
2979 MouseButton::Left => {
2980 for listener in &click_listeners {
2981 listener(&mouse_click, window, cx);
2982 }
2983 }
2984 _ => {
2985 for listener in &aux_click_listeners {
2986 listener(&mouse_click, window, cx);
2987 }
2988 }
2989 }
2990 }
2991 }
2992 }
2993 });
2994 }
2995
2996 if let Some(hover_listener) = self.hover_listener.take() {
2997 let was_hovered = element_state
2998 .hover_listener_state
2999 .get_or_insert_with(Default::default)
3000 .clone();
3001 let has_mouse_down = element_state
3002 .pending_mouse_down
3003 .get_or_insert_with(Default::default)
3004 .clone();
3005 let hover_listener = Rc::new(hover_listener);
3006 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3007 let mut was_hovered = was_hovered.borrow_mut();
3008 if is_hovered != *was_hovered {
3009 *was_hovered = is_hovered;
3010 drop(was_hovered);
3011 hover_listener(&is_hovered, window, cx);
3012 }
3013 };
3014
3015 window.on_mouse_event({
3016 let update_hover = update_hover.clone();
3017 let hitbox = hitbox.clone();
3018 move |_: &MouseMoveEvent, phase, window, cx| {
3019 if phase == DispatchPhase::Bubble {
3020 let is_hovered = has_mouse_down.borrow().is_none()
3021 && !cx.has_active_drag()
3022 && hitbox.is_hovered(window);
3023 update_hover(is_hovered, window, cx);
3024 }
3025 }
3026 });
3027
3028 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3031 if phase == DispatchPhase::Bubble {
3032 update_hover(false, window, cx);
3033 }
3034 });
3035 }
3036
3037 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3038 let active_tooltip = element_state
3039 .active_tooltip
3040 .get_or_insert_with(Default::default)
3041 .clone();
3042 let pending_mouse_down = element_state
3043 .pending_mouse_down
3044 .get_or_insert_with(Default::default)
3045 .clone();
3046
3047 let tooltip_is_hoverable = tooltip_builder.hoverable;
3048 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3049 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3050 });
3051 let check_is_hovered_during_prepaint = Rc::new({
3053 let pending_mouse_down = pending_mouse_down.clone();
3054 let source_bounds = hitbox.bounds;
3055 move |window: &Window| {
3056 !window.last_input_was_keyboard()
3057 && pending_mouse_down.borrow().is_none()
3058 && source_bounds.contains(&window.mouse_position())
3059 }
3060 });
3061 let check_is_hovered = Rc::new({
3062 let hitbox = hitbox.clone();
3063 move |window: &Window| {
3064 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3065 }
3066 });
3067 register_tooltip_mouse_handlers(
3068 &active_tooltip,
3069 self.tooltip_id,
3070 build_tooltip,
3071 check_is_hovered,
3072 check_is_hovered_during_prepaint,
3073 self.tooltip_show_delay,
3074 window,
3075 );
3076 }
3077
3078 let active_state = element_state
3081 .clicked_state
3082 .get_or_insert_with(Default::default)
3083 .clone();
3084
3085 {
3086 let active_state = active_state.clone();
3087 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3088 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3089 *active_state.borrow_mut() = ElementClickedState::default();
3090 window.refresh();
3091 }
3092 });
3093 }
3094
3095 {
3096 let active_group_hitbox = self
3097 .group_active_style
3098 .as_ref()
3099 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3100 let hitbox = hitbox.clone();
3101 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3102 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3103 let group_hovered = active_group_hitbox
3104 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3105 let element_hovered = hitbox.is_hovered(window);
3106 if group_hovered || element_hovered {
3107 *active_state.borrow_mut() = ElementClickedState {
3108 group: group_hovered,
3109 element: element_hovered,
3110 };
3111 window.refresh();
3112 }
3113 }
3114 });
3115 }
3116 }
3117 }
3118
3119 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3120 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3121 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3122 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3123 let action_listeners = mem::take(&mut self.action_listeners);
3124 if let Some(context) = self.key_context.clone() {
3125 window.set_key_context(context);
3126 }
3127
3128 for listener in key_down_listeners {
3129 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3130 listener(event, phase, window, cx);
3131 })
3132 }
3133
3134 for listener in key_up_listeners {
3135 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3136 listener(event, phase, window, cx);
3137 })
3138 }
3139
3140 for listener in modifiers_changed_listeners {
3141 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3142 listener(event, window, cx);
3143 })
3144 }
3145
3146 for (action_type, listener) in action_listeners {
3147 window.on_action(action_type, listener)
3148 }
3149 }
3150
3151 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3152 let group_hitbox = self
3153 .group_hover_style
3154 .as_ref()
3155 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3156
3157 if let Some(group_hitbox) = group_hitbox {
3158 let was_hovered = group_hitbox.is_hovered(window);
3159 let current_view = window.current_view();
3160 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3161 let hovered = group_hitbox.is_hovered(window);
3162 if phase == DispatchPhase::Capture && hovered != was_hovered {
3163 cx.notify(current_view);
3164 }
3165 });
3166 }
3167 }
3168
3169 fn paint_scroll_listener(
3170 &self,
3171 hitbox: &Hitbox,
3172 style: &Style,
3173 window: &mut Window,
3174 _cx: &mut App,
3175 ) {
3176 if let Some(scroll_offset) = self.scroll_offset.clone() {
3177 let ongoing_scroll = self.ongoing_scroll.clone();
3178 let overflow = style.overflow;
3179 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3180 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3181 let line_height = window.line_height();
3182 let hitbox = hitbox.clone();
3183 let current_view = window.current_view();
3184 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
3185 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3186 let mut scroll_offset = scroll_offset.borrow_mut();
3187 let old_scroll_offset = *scroll_offset;
3188 let mut delta = event.delta.pixel_delta(line_height);
3189
3190 if restrict_scroll_to_axis
3191 && event.delta.precise()
3192 && let Some(ongoing_scroll) = &ongoing_scroll
3193 {
3194 ongoing_scroll
3195 .borrow_mut()
3196 .filter(&mut delta, event.touch_phase);
3197 }
3198
3199 let mut delta_x = match overflow.x {
3200 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3201 Overflow::Scroll
3202 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3203 {
3204 delta.y
3205 }
3206 _ => Pixels::ZERO,
3207 };
3208 let mut delta_y = match overflow.y {
3209 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3210 Overflow::Scroll
3211 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3212 {
3213 delta.x
3214 }
3215 _ => Pixels::ZERO,
3216 };
3217 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3218 if delta_x.abs() > delta_y.abs() {
3219 delta_y = Pixels::ZERO;
3220 } else {
3221 delta_x = Pixels::ZERO;
3222 }
3223 }
3224 scroll_offset.y += delta_y;
3225 scroll_offset.x += delta_x;
3226 if *scroll_offset != old_scroll_offset {
3227 cx.notify(current_view);
3228 }
3229 }
3230 });
3231 }
3232 }
3233
3234 pub fn compute_style(
3236 &self,
3237 global_id: Option<&GlobalElementId>,
3238 hitbox: Option<&Hitbox>,
3239 window: &mut Window,
3240 cx: &mut App,
3241 ) -> Style {
3242 window.with_optional_element_state(global_id, |element_state, window| {
3243 let mut element_state =
3244 element_state.map(|element_state| element_state.unwrap_or_default());
3245 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3246 (style, element_state)
3247 })
3248 }
3249
3250 fn compute_style_internal(
3252 &self,
3253 hitbox: Option<&Hitbox>,
3254 element_state: Option<&mut InteractiveElementState>,
3255 window: &mut Window,
3256 cx: &mut App,
3257 ) -> Style {
3258 let mut style = Style::default();
3259 style.refine(&self.base_style);
3260
3261 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3262 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3263 && focus_handle.within_focused(window, cx)
3264 {
3265 style.refine(in_focus_style);
3266 }
3267
3268 if let Some(focus_style) = self.focus_style.as_ref()
3269 && focus_handle.is_focused(window)
3270 {
3271 style.refine(focus_style);
3272 }
3273
3274 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3275 && focus_handle.is_focused(window)
3276 && window.last_input_was_keyboard()
3277 {
3278 style.refine(focus_visible_style);
3279 }
3280 }
3281
3282 if !cx.has_active_drag() {
3283 if let Some(group_hover) = self.group_hover_style.as_ref() {
3284 let is_group_hovered =
3285 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3286 group_hitbox_id.is_hovered(window)
3287 } else if let Some(element_state) = element_state.as_ref() {
3288 element_state
3289 .hover_state
3290 .as_ref()
3291 .map(|state| state.borrow().group)
3292 .unwrap_or(false)
3293 } else {
3294 false
3295 };
3296
3297 if is_group_hovered {
3298 style.refine(&group_hover.style);
3299 }
3300 }
3301
3302 if let Some(hover_style) = self.hover_style.as_ref() {
3303 let is_hovered = if let Some(hitbox) = hitbox {
3304 hitbox.is_hovered(window)
3305 } else if let Some(element_state) = element_state.as_ref() {
3306 element_state
3307 .hover_state
3308 .as_ref()
3309 .map(|state| state.borrow().element)
3310 .unwrap_or(false)
3311 } else {
3312 false
3313 };
3314
3315 if is_hovered {
3316 style.refine(hover_style);
3317 }
3318 }
3319 }
3320
3321 if let Some(hitbox) = hitbox {
3322 if let Some(drag) = cx.active_drag.take() {
3323 let mut can_drop = true;
3324 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3325 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3326 }
3327
3328 if can_drop {
3329 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3330 if let Some(group_hitbox_id) =
3331 GroupHitboxes::get(&group_drag_style.group, cx)
3332 && *state_type == drag.value.as_ref().type_id()
3333 && group_hitbox_id.is_hovered(window)
3334 {
3335 style.refine(&group_drag_style.style);
3336 }
3337 }
3338
3339 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3340 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3341 {
3342 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3343 }
3344 }
3345 }
3346
3347 style.mouse_cursor = drag.cursor_style;
3348 cx.active_drag = Some(drag);
3349 }
3350 }
3351
3352 if let Some(element_state) = element_state {
3353 let clicked_state = element_state
3354 .clicked_state
3355 .get_or_insert_with(Default::default)
3356 .borrow();
3357 if clicked_state.group
3358 && let Some(group) = self.group_active_style.as_ref()
3359 {
3360 style.refine(&group.style)
3361 }
3362
3363 if let Some(active_style) = self.active_style.as_ref()
3364 && clicked_state.element
3365 {
3366 style.refine(active_style)
3367 }
3368 }
3369
3370 style
3371 }
3372
3373 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3374 if let Some(label) = &self.aria.label {
3375 node.set_label(label.to_string());
3376 }
3377 if let Some(description) = &self.aria.description {
3378 node.set_description(description.to_string());
3379 }
3380 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3381 node.set_keyboard_shortcut(keyshortcuts.to_string());
3382 }
3383 if let Some(selected) = self.aria.selected {
3384 node.set_selected(selected);
3385 }
3386 if let Some(expanded) = self.aria.expanded {
3387 node.set_expanded(expanded);
3388 }
3389 if let Some(toggled) = self.aria.toggled {
3390 node.set_toggled(toggled);
3391 }
3392 if let Some(value) = self.aria.numeric_value {
3393 node.set_numeric_value(value);
3394 }
3395 if let Some(value) = self.aria.min_numeric_value {
3396 node.set_min_numeric_value(value);
3397 }
3398 if let Some(value) = self.aria.max_numeric_value {
3399 node.set_max_numeric_value(value);
3400 }
3401 if let Some(step) = self.aria.numeric_value_step {
3402 node.set_numeric_value_step(step);
3403 }
3404 if let Some(value) = &self.aria.value {
3405 node.set_value(value.to_string());
3406 }
3407 if let Some(placeholder) = &self.aria.placeholder {
3408 node.set_placeholder(placeholder.to_string());
3409 }
3410 if let Some(orientation) = self.aria.orientation {
3411 node.set_orientation(orientation);
3412 }
3413 if let Some(level) = self.aria.level {
3414 node.set_level(level);
3415 }
3416 if let Some(position) = self.aria.position_in_set {
3417 node.set_position_in_set(position);
3418 }
3419 if let Some(size) = self.aria.size_of_set {
3420 node.set_size_of_set(size);
3421 }
3422 if let Some(index) = self.aria.row_index {
3423 node.set_row_index(index);
3424 }
3425 if let Some(index) = self.aria.column_index {
3426 node.set_column_index(index);
3427 }
3428 if let Some(count) = self.aria.row_count {
3429 node.set_row_count(count);
3430 }
3431 if let Some(count) = self.aria.column_count {
3432 node.set_column_count(count);
3433 }
3434 if !self.click_listeners.is_empty() {
3435 node.add_action(accesskit::Action::Click);
3436 }
3437 if self.tracked_focus_handle.is_some() || self.focusable {
3438 node.add_action(accesskit::Action::Focus);
3439 }
3440 for (action, _) in &self.a11y_action_listeners {
3441 node.add_action(*action);
3442 }
3443 }
3444}
3445
3446#[derive(Default)]
3449pub struct InteractiveElementState {
3450 pub(crate) focus_handle: Option<FocusHandle>,
3451 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3452 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3453 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3454 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3455 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3463 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3464 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3465 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3466}
3467
3468#[derive(Copy, Clone, Default, Eq, PartialEq)]
3470pub struct ElementClickedState {
3471 pub group: bool,
3473
3474 pub element: bool,
3476}
3477
3478impl ElementClickedState {
3479 fn is_clicked(&self) -> bool {
3480 self.group || self.element
3481 }
3482}
3483
3484#[derive(Copy, Clone, Default, Eq, PartialEq)]
3486pub struct ElementHoverState {
3487 pub group: bool,
3489
3490 pub element: bool,
3492}
3493
3494pub(crate) enum ActiveTooltip {
3495 WaitingForShow { _task: Task<()> },
3497 Visible {
3499 tooltip: AnyTooltip,
3500 is_hoverable: bool,
3501 },
3502 WaitingForHide {
3505 tooltip: AnyTooltip,
3506 _task: Task<()>,
3507 },
3508}
3509
3510pub(crate) fn clear_active_tooltip(
3511 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3512 window: &mut Window,
3513) {
3514 match active_tooltip.borrow_mut().take() {
3515 None => {}
3516 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3517 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3518 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3519 }
3520}
3521
3522pub(crate) fn clear_active_tooltip_if_not_hoverable(
3523 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3524 window: &mut Window,
3525) {
3526 let should_clear = match active_tooltip.borrow().as_ref() {
3527 None => false,
3528 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3529 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3530 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3531 };
3532 if should_clear {
3533 active_tooltip.borrow_mut().take();
3534 window.refresh();
3535 }
3536}
3537
3538pub(crate) fn set_tooltip_on_window(
3539 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3540 window: &mut Window,
3541) -> Option<TooltipId> {
3542 let tooltip = match active_tooltip.borrow().as_ref() {
3543 None => return None,
3544 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3545 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3546 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3547 };
3548 Some(window.set_tooltip(tooltip))
3549}
3550
3551pub(crate) fn register_tooltip_mouse_handlers(
3552 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3553 tooltip_id: Option<TooltipId>,
3554 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3555 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3556 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3557 show_delay: Option<Duration>,
3558 window: &mut Window,
3559) {
3560 let current_view = window.current_view();
3561 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3562
3563 window.on_mouse_event({
3564 let active_tooltip = active_tooltip.clone();
3565 let build_tooltip = build_tooltip.clone();
3566 let check_is_hovered = check_is_hovered.clone();
3567 move |_: &MouseMoveEvent, phase, window, cx| {
3568 handle_tooltip_mouse_move(
3569 &active_tooltip,
3570 &build_tooltip,
3571 &check_is_hovered,
3572 &check_is_hovered_during_prepaint,
3573 tooltip_id,
3574 current_view,
3575 phase,
3576 show_delay,
3577 window,
3578 cx,
3579 )
3580 }
3581 });
3582
3583 window.on_mouse_event({
3584 let active_tooltip = active_tooltip.clone();
3585 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3586 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3587 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3588 }
3589 }
3590 });
3591
3592 window.on_mouse_event({
3593 let active_tooltip = active_tooltip.clone();
3594 move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
3595 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3596 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3597 }
3598 }
3599 });
3600}
3601
3602fn handle_tooltip_mouse_move(
3614 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3615 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3616 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3617 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3618 tooltip_id: Option<TooltipId>,
3619 current_view: EntityId,
3620 phase: DispatchPhase,
3621 show_delay: Duration,
3622 window: &mut Window,
3623 cx: &mut App,
3624) {
3625 enum Action {
3628 None,
3629 CancelShow,
3630 ScheduleShow,
3631 CheckVisible,
3632 }
3633
3634 let action = match active_tooltip.borrow().as_ref() {
3635 None => {
3636 let is_hovered = check_is_hovered(window);
3637 if is_hovered && phase.bubble() {
3638 Action::ScheduleShow
3639 } else {
3640 Action::None
3641 }
3642 }
3643 Some(ActiveTooltip::WaitingForShow { .. }) => {
3644 let is_hovered = check_is_hovered(window);
3645 if is_hovered {
3646 Action::None
3647 } else {
3648 Action::CancelShow
3649 }
3650 }
3651 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3652 if phase.capture()
3653 && !check_is_hovered(window)
3654 && (!*is_hoverable
3655 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3656 {
3657 Action::CheckVisible
3658 } else {
3659 Action::None
3660 }
3661 }
3662 Some(ActiveTooltip::WaitingForHide { .. }) => {
3663 if phase.capture()
3664 && (check_is_hovered(window)
3665 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3666 {
3667 Action::CheckVisible
3668 } else {
3669 Action::None
3670 }
3671 }
3672 };
3673
3674 match action {
3675 Action::None => {}
3676 Action::CancelShow => {
3677 active_tooltip.borrow_mut().take();
3679 }
3680 Action::ScheduleShow => {
3681 let delayed_show_task = window.spawn(cx, {
3682 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3683 let build_tooltip = build_tooltip.clone();
3684 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3685 async move |cx| {
3686 cx.background_executor().timer(show_delay).await;
3687 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3688 return;
3689 };
3690 cx.update(|window, cx| {
3691 let new_tooltip =
3692 build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3693 let weak_active_tooltip = Rc::downgrade(&active_tooltip);
3694 ActiveTooltip::Visible {
3695 tooltip: AnyTooltip {
3696 view,
3697 mouse_position: window.mouse_position(),
3698 check_visible_and_update: Rc::new(
3699 move |tooltip_bounds, window, cx| {
3700 let Some(active_tooltip) =
3701 weak_active_tooltip.upgrade()
3702 else {
3703 return false;
3704 };
3705 handle_tooltip_check_visible_and_update(
3706 &active_tooltip,
3707 tooltip_is_hoverable,
3708 &check_is_hovered_during_prepaint,
3709 tooltip_bounds,
3710 window,
3711 cx,
3712 )
3713 },
3714 ),
3715 },
3716 is_hoverable: tooltip_is_hoverable,
3717 }
3718 });
3719 *active_tooltip.borrow_mut() = new_tooltip;
3720 window.refresh();
3721 })
3722 .ok();
3723 }
3724 });
3725 active_tooltip
3726 .borrow_mut()
3727 .replace(ActiveTooltip::WaitingForShow {
3728 _task: delayed_show_task,
3729 });
3730 }
3731 Action::CheckVisible => cx.notify(current_view),
3732 }
3733}
3734
3735fn handle_tooltip_check_visible_and_update(
3739 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3740 tooltip_is_hoverable: bool,
3741 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3742 tooltip_bounds: Bounds<Pixels>,
3743 window: &mut Window,
3744 cx: &mut App,
3745) -> bool {
3746 enum Action {
3749 None,
3750 Hide,
3751 ScheduleHide(AnyTooltip),
3752 CancelHide(AnyTooltip),
3753 }
3754
3755 let is_hovered = check_is_hovered(window)
3756 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
3757 let action = match active_tooltip.borrow().as_ref() {
3758 Some(ActiveTooltip::Visible { tooltip, .. }) => {
3759 if is_hovered {
3760 Action::None
3761 } else {
3762 if tooltip_is_hoverable {
3763 Action::ScheduleHide(tooltip.clone())
3764 } else {
3765 Action::Hide
3766 }
3767 }
3768 }
3769 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
3770 if is_hovered {
3771 Action::CancelHide(tooltip.clone())
3772 } else {
3773 Action::None
3774 }
3775 }
3776 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
3777 };
3778
3779 match action {
3780 Action::None => {}
3781 Action::Hide => clear_active_tooltip(active_tooltip, window),
3782 Action::ScheduleHide(tooltip) => {
3783 let delayed_hide_task = window.spawn(cx, {
3784 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3785 async move |cx| {
3786 cx.background_executor()
3787 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
3788 .await;
3789 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3790 return;
3791 };
3792 if active_tooltip.borrow_mut().take().is_some() {
3793 cx.update(|window, _cx| window.refresh()).ok();
3794 }
3795 }
3796 });
3797 active_tooltip
3798 .borrow_mut()
3799 .replace(ActiveTooltip::WaitingForHide {
3800 tooltip,
3801 _task: delayed_hide_task,
3802 });
3803 }
3804 Action::CancelHide(tooltip) => {
3805 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
3807 tooltip,
3808 is_hoverable: true,
3809 });
3810 }
3811 }
3812
3813 active_tooltip.borrow().is_some()
3814}
3815
3816#[derive(Default)]
3817pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
3818
3819impl Global for GroupHitboxes {}
3820
3821impl GroupHitboxes {
3822 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
3823 cx.default_global::<Self>()
3824 .0
3825 .get(name)
3826 .and_then(|bounds_stack| bounds_stack.last())
3827 .cloned()
3828 }
3829
3830 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
3831 cx.default_global::<Self>()
3832 .0
3833 .entry(name)
3834 .or_default()
3835 .push(hitbox_id);
3836 }
3837
3838 pub fn pop(name: &SharedString, cx: &mut App) {
3839 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
3840 }
3841}
3842
3843pub struct Stateful<E> {
3845 pub(crate) element: E,
3846}
3847
3848impl<E> Styled for Stateful<E>
3849where
3850 E: Styled,
3851{
3852 fn style(&mut self) -> &mut StyleRefinement {
3853 self.element.style()
3854 }
3855}
3856
3857impl<E> StatefulInteractiveElement for Stateful<E>
3858where
3859 E: Element,
3860 Self: InteractiveElement,
3861{
3862}
3863
3864impl<E> InteractiveElement for Stateful<E>
3865where
3866 E: InteractiveElement,
3867{
3868 fn interactivity(&mut self) -> &mut Interactivity {
3869 self.element.interactivity()
3870 }
3871}
3872
3873impl<E> Element for Stateful<E>
3874where
3875 E: Element,
3876{
3877 type RequestLayoutState = E::RequestLayoutState;
3878 type PrepaintState = E::PrepaintState;
3879
3880 fn id(&self) -> Option<ElementId> {
3881 self.element.id()
3882 }
3883
3884 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3885 self.element.source_location()
3886 }
3887
3888 fn a11y_role(&self) -> Option<accesskit::Role> {
3889 self.element.a11y_role()
3890 }
3891
3892 fn write_a11y_info(&self, node: &mut accesskit::Node) {
3893 self.element.write_a11y_info(node);
3894 }
3895
3896 fn a11y_synthetic_children(
3897 &mut self,
3898 prepaint: &mut Self::PrepaintState,
3899 builder: &mut crate::A11ySubtreeBuilder,
3900 ) {
3901 self.element.a11y_synthetic_children(prepaint, builder);
3902 }
3903
3904 fn request_layout(
3905 &mut self,
3906 id: Option<&GlobalElementId>,
3907 inspector_id: Option<&InspectorElementId>,
3908 window: &mut Window,
3909 cx: &mut App,
3910 ) -> (LayoutId, Self::RequestLayoutState) {
3911 self.element.request_layout(id, inspector_id, window, cx)
3912 }
3913
3914 fn prepaint(
3915 &mut self,
3916 id: Option<&GlobalElementId>,
3917 inspector_id: Option<&InspectorElementId>,
3918 bounds: Bounds<Pixels>,
3919 state: &mut Self::RequestLayoutState,
3920 window: &mut Window,
3921 cx: &mut App,
3922 ) -> E::PrepaintState {
3923 self.element
3924 .prepaint(id, inspector_id, bounds, state, window, cx)
3925 }
3926
3927 fn paint(
3928 &mut self,
3929 id: Option<&GlobalElementId>,
3930 inspector_id: Option<&InspectorElementId>,
3931 bounds: Bounds<Pixels>,
3932 request_layout: &mut Self::RequestLayoutState,
3933 prepaint: &mut Self::PrepaintState,
3934 window: &mut Window,
3935 cx: &mut App,
3936 ) {
3937 self.element.paint(
3938 id,
3939 inspector_id,
3940 bounds,
3941 request_layout,
3942 prepaint,
3943 window,
3944 cx,
3945 );
3946 }
3947}
3948
3949impl<E> IntoElement for Stateful<E>
3950where
3951 E: Element,
3952{
3953 type Element = Self;
3954
3955 fn into_element(self) -> Self::Element {
3956 self
3957 }
3958}
3959
3960impl<E> ParentElement for Stateful<E>
3961where
3962 E: ParentElement,
3963{
3964 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
3965 self.element.extend(elements)
3966 }
3967}
3968
3969#[derive(Clone)]
3972pub struct ScrollAnchor {
3973 handle: ScrollHandle,
3974 last_origin: Rc<RefCell<Point<Pixels>>>,
3975}
3976
3977impl ScrollAnchor {
3978 pub fn for_handle(handle: ScrollHandle) -> Self {
3980 Self {
3981 handle,
3982 last_origin: Default::default(),
3983 }
3984 }
3985 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
3987 let this = self.clone();
3988
3989 window.on_next_frame(move |_, _| {
3990 let viewport_bounds = this.handle.bounds();
3991 let self_bounds = *this.last_origin.borrow();
3992 this.handle.set_offset(viewport_bounds.origin - self_bounds);
3993 });
3994 }
3995}
3996
3997#[derive(Default, Debug)]
3998struct ScrollHandleState {
3999 offset: Rc<RefCell<Point<Pixels>>>,
4000 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4001 bounds: Bounds<Pixels>,
4002 max_offset: Point<Pixels>,
4003 child_bounds: Vec<Bounds<Pixels>>,
4004 scroll_to_bottom: bool,
4005 overflow: Point<Overflow>,
4006 active_item: Option<ScrollActiveItem>,
4007}
4008
4009#[derive(Default, Debug, Clone, Copy)]
4010struct ScrollActiveItem {
4011 index: usize,
4012 strategy: ScrollStrategy,
4013}
4014
4015#[derive(Default, Debug, Clone, Copy)]
4016enum ScrollStrategy {
4017 #[default]
4018 FirstVisible,
4019 Top,
4020}
4021
4022#[derive(Clone, Debug)]
4026pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4027
4028impl Default for ScrollHandle {
4029 fn default() -> Self {
4030 Self::new()
4031 }
4032}
4033
4034impl ScrollHandle {
4035 pub fn new() -> Self {
4037 Self(Rc::default())
4038 }
4039
4040 pub fn offset(&self) -> Point<Pixels> {
4042 *self.0.borrow().offset.borrow()
4043 }
4044
4045 pub fn max_offset(&self) -> Point<Pixels> {
4047 self.0.borrow().max_offset
4048 }
4049
4050 pub fn top_item(&self) -> usize {
4052 let state = self.0.borrow();
4053 let top = state.bounds.top() - state.offset.borrow().y;
4054
4055 match state.child_bounds.binary_search_by(|bounds| {
4056 if top < bounds.top() {
4057 Ordering::Greater
4058 } else if top > bounds.bottom() {
4059 Ordering::Less
4060 } else {
4061 Ordering::Equal
4062 }
4063 }) {
4064 Ok(ix) => ix,
4065 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4066 }
4067 }
4068
4069 pub fn bottom_item(&self) -> usize {
4071 let state = self.0.borrow();
4072 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4073
4074 match state.child_bounds.binary_search_by(|bounds| {
4075 if bottom < bounds.top() {
4076 Ordering::Greater
4077 } else if bottom > bounds.bottom() {
4078 Ordering::Less
4079 } else {
4080 Ordering::Equal
4081 }
4082 }) {
4083 Ok(ix) => ix,
4084 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4085 }
4086 }
4087
4088 pub fn bounds(&self) -> Bounds<Pixels> {
4090 self.0.borrow().bounds
4091 }
4092
4093 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4095 self.0.borrow().child_bounds.get(ix).cloned()
4096 }
4097
4098 pub fn scroll_to_item(&self, ix: usize) {
4100 let mut state = self.0.borrow_mut();
4101 state.active_item = Some(ScrollActiveItem {
4102 index: ix,
4103 strategy: ScrollStrategy::default(),
4104 });
4105 }
4106
4107 pub fn scroll_to_top_of_item(&self, ix: usize) {
4110 let mut state = self.0.borrow_mut();
4111 state.active_item = Some(ScrollActiveItem {
4112 index: ix,
4113 strategy: ScrollStrategy::Top,
4114 });
4115 }
4116
4117 fn scroll_to_active_item(&self) {
4121 let mut state = self.0.borrow_mut();
4122
4123 let Some(active_item) = state.active_item else {
4124 return;
4125 };
4126
4127 let active_item = match state.child_bounds.get(active_item.index) {
4128 Some(bounds) => {
4129 let mut scroll_offset = state.offset.borrow_mut();
4130
4131 match active_item.strategy {
4132 ScrollStrategy::FirstVisible => {
4133 if state.overflow.y == Overflow::Scroll {
4134 let child_height = bounds.size.height;
4135 let viewport_height = state.bounds.size.height;
4136 if child_height > viewport_height {
4137 scroll_offset.y = state.bounds.top() - bounds.top();
4138 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4139 scroll_offset.y = state.bounds.top() - bounds.top();
4140 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4141 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4142 }
4143 }
4144 }
4145 ScrollStrategy::Top => {
4146 scroll_offset.y = state.bounds.top() - bounds.top();
4147 }
4148 }
4149
4150 if state.overflow.x == Overflow::Scroll {
4151 let child_width = bounds.size.width;
4152 let viewport_width = state.bounds.size.width;
4153 if child_width > viewport_width {
4154 scroll_offset.x = state.bounds.left() - bounds.left();
4155 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4156 scroll_offset.x = state.bounds.left() - bounds.left();
4157 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4158 scroll_offset.x = state.bounds.right() - bounds.right();
4159 }
4160 }
4161 None
4162 }
4163 None => Some(active_item),
4164 };
4165 state.active_item = active_item;
4166 }
4167
4168 pub fn scroll_to_bottom(&self) {
4170 let mut state = self.0.borrow_mut();
4171 state.scroll_to_bottom = true;
4172 }
4173
4174 pub fn set_offset(&self, mut position: Point<Pixels>) {
4178 let state = self.0.borrow();
4179 *state.offset.borrow_mut() = position;
4180 }
4181
4182 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4184 let ix = self.top_item();
4185 let state = self.0.borrow();
4186
4187 if let Some(child_bounds) = state.child_bounds.get(ix) {
4188 (
4189 ix,
4190 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4191 )
4192 } else {
4193 (ix, px(0.))
4194 }
4195 }
4196
4197 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4199 let ix = self.bottom_item();
4200 let state = self.0.borrow();
4201
4202 if let Some(child_bounds) = state.child_bounds.get(ix) {
4203 (
4204 ix,
4205 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4206 )
4207 } else {
4208 (ix, px(0.))
4209 }
4210 }
4211
4212 pub fn children_count(&self) -> usize {
4214 self.0.borrow().child_bounds.len()
4215 }
4216}
4217
4218#[cfg(test)]
4219mod tests {
4220 use super::*;
4221 use crate::{
4222 AnyWindowHandle, AppContext as _, Context, InputEvent, Keystroke, MouseMoveEvent,
4223 TestAppContext, canvas, util::FluentBuilder as _,
4224 };
4225 use std::{cell::Cell, rc::Weak};
4226
4227 struct GroupHoverTestView {
4228 render_count: Rc<Cell<usize>>,
4229 anonymous_paint_count: Rc<Cell<usize>>,
4230 stateful_width: Rc<Cell<Pixels>>,
4231 }
4232
4233 impl Render for GroupHoverTestView {
4234 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4235 self.render_count.set(self.render_count.get() + 1);
4236 let anonymous_paint_count = self.anonymous_paint_count.clone();
4237 let stateful_width = self.stateful_width.clone();
4238 div().size_full().child(
4239 div()
4240 .ml(px(20.))
4241 .mt(px(20.))
4242 .size(px(50.))
4243 .relative()
4244 .group("hover-group")
4245 .child(
4246 div()
4247 .absolute()
4248 .size_full()
4249 .invisible()
4250 .group_hover("hover-group", |style| style.visible())
4251 .child(canvas(
4252 |_, _, _| {},
4253 move |_, _, _, _| {
4254 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4255 },
4256 )),
4257 )
4258 .child(
4259 div()
4260 .id("stateful-group-hover-target")
4261 .absolute()
4262 .top_0()
4263 .left_0()
4264 .size(px(10.))
4265 .group_hover("hover-group", |style| style.size(px(20.)))
4266 .child(canvas(
4267 move |bounds, _, _| stateful_width.set(bounds.size.width),
4268 |_, _, _, _| {},
4269 )),
4270 ),
4271 )
4272 }
4273 }
4274
4275 #[gpui::test]
4276 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4277 let render_count = Rc::new(Cell::new(0));
4278 let anonymous_paint_count = Rc::new(Cell::new(0));
4279 let stateful_width = Rc::new(Cell::new(px(0.)));
4280 let window = cx.add_window({
4281 let render_count = render_count.clone();
4282 let anonymous_paint_count = anonymous_paint_count.clone();
4283 let stateful_width = stateful_width.clone();
4284 move |_, _| GroupHoverTestView {
4285 render_count,
4286 anonymous_paint_count,
4287 stateful_width,
4288 }
4289 });
4290 let window = AnyWindowHandle::from(window);
4291
4292 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4293 .unwrap();
4294 assert_eq!(anonymous_paint_count.get(), 0);
4295 assert_eq!(stateful_width.get(), px(10.));
4296
4297 let move_mouse = |cx: &mut TestAppContext, position| {
4298 cx.update_window(window, |_, window, cx| {
4299 window.simulate_mouse_move(position, cx)
4300 })
4301 .unwrap();
4302 };
4303
4304 let initial_render_count = render_count.get();
4305 move_mouse(cx, point(px(25.), px(25.)));
4306 assert_eq!(render_count.get(), initial_render_count + 1);
4307 assert_eq!(anonymous_paint_count.get(), 1);
4308 assert_eq!(stateful_width.get(), px(20.));
4309
4310 move_mouse(cx, point(px(30.), px(30.)));
4311 assert_eq!(render_count.get(), initial_render_count + 1);
4312 assert_eq!(anonymous_paint_count.get(), 1);
4313 assert_eq!(stateful_width.get(), px(20.));
4314
4315 move_mouse(cx, point(px(5.), px(5.)));
4316 assert_eq!(render_count.get(), initial_render_count + 2);
4317 assert_eq!(anonymous_paint_count.get(), 1);
4318 assert_eq!(stateful_width.get(), px(10.));
4319
4320 move_mouse(cx, point(px(10.), px(10.)));
4321 assert_eq!(render_count.get(), initial_render_count + 2);
4322 assert_eq!(anonymous_paint_count.get(), 1);
4323 assert_eq!(stateful_width.get(), px(10.));
4324 }
4325
4326 struct TestTooltipView;
4327
4328 impl Render for TestTooltipView {
4329 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4330 div().w(px(20.)).h(px(20.)).child("tooltip")
4331 }
4332 }
4333
4334 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4335
4336 struct TooltipCaptureElement {
4337 child: AnyElement,
4338 captured_active_tooltip: CapturedActiveTooltip,
4339 }
4340
4341 impl IntoElement for TooltipCaptureElement {
4342 type Element = Self;
4343
4344 fn into_element(self) -> Self::Element {
4345 self
4346 }
4347 }
4348
4349 impl Element for TooltipCaptureElement {
4350 type RequestLayoutState = ();
4351 type PrepaintState = ();
4352
4353 fn id(&self) -> Option<ElementId> {
4354 None
4355 }
4356
4357 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4358 None
4359 }
4360
4361 fn request_layout(
4362 &mut self,
4363 _id: Option<&GlobalElementId>,
4364 _inspector_id: Option<&InspectorElementId>,
4365 window: &mut Window,
4366 cx: &mut App,
4367 ) -> (LayoutId, Self::RequestLayoutState) {
4368 (self.child.request_layout(window, cx), ())
4369 }
4370
4371 fn prepaint(
4372 &mut self,
4373 _id: Option<&GlobalElementId>,
4374 _inspector_id: Option<&InspectorElementId>,
4375 _bounds: Bounds<Pixels>,
4376 _request_layout: &mut Self::RequestLayoutState,
4377 window: &mut Window,
4378 cx: &mut App,
4379 ) -> Self::PrepaintState {
4380 self.child.prepaint(window, cx);
4381 }
4382
4383 fn paint(
4384 &mut self,
4385 _id: Option<&GlobalElementId>,
4386 _inspector_id: Option<&InspectorElementId>,
4387 _bounds: Bounds<Pixels>,
4388 _request_layout: &mut Self::RequestLayoutState,
4389 _prepaint: &mut Self::PrepaintState,
4390 window: &mut Window,
4391 cx: &mut App,
4392 ) {
4393 self.child.paint(window, cx);
4394 window.with_global_id("target".into(), |global_id, window| {
4395 window.with_element_state::<InteractiveElementState, _>(
4396 global_id,
4397 |state, _window| {
4398 let state = state.unwrap();
4399 *self.captured_active_tooltip.borrow_mut() =
4400 state.active_tooltip.as_ref().map(Rc::downgrade);
4401 ((), state)
4402 },
4403 )
4404 });
4405 }
4406 }
4407
4408 struct TooltipOwner {
4409 captured_active_tooltip: CapturedActiveTooltip,
4410 show_delay_override: Option<Duration>,
4411 }
4412
4413 impl Render for TooltipOwner {
4414 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4415 TooltipCaptureElement {
4416 child: div()
4417 .size_full()
4418 .child(
4419 div()
4420 .id("target")
4421 .w(px(50.))
4422 .h(px(50.))
4423 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4424 .when_some(self.show_delay_override, |this, delay| {
4425 this.tooltip_show_delay(delay)
4426 }),
4427 )
4428 .into_any_element(),
4429 captured_active_tooltip: self.captured_active_tooltip.clone(),
4430 }
4431 }
4432 }
4433
4434 #[test]
4435 fn scroll_handle_aligns_wide_children_to_left_edge() {
4436 let handle = ScrollHandle::new();
4437 {
4438 let mut state = handle.0.borrow_mut();
4439 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4440 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4441 state.overflow.x = Overflow::Scroll;
4442 state.active_item = Some(ScrollActiveItem {
4443 index: 0,
4444 strategy: ScrollStrategy::default(),
4445 });
4446 }
4447
4448 handle.scroll_to_active_item();
4449
4450 assert_eq!(handle.offset().x, px(-25.));
4451 }
4452
4453 #[test]
4454 fn scroll_handle_aligns_tall_children_to_top_edge() {
4455 let handle = ScrollHandle::new();
4456 {
4457 let mut state = handle.0.borrow_mut();
4458 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4459 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4460 state.overflow.y = Overflow::Scroll;
4461 state.active_item = Some(ScrollActiveItem {
4462 index: 0,
4463 strategy: ScrollStrategy::default(),
4464 });
4465 }
4466
4467 handle.scroll_to_active_item();
4468
4469 assert_eq!(handle.offset().y, px(-25.));
4470 }
4471
4472 fn setup_tooltip_owner_test(
4473 show_delay_override: Option<Duration>,
4474 ) -> (
4475 TestAppContext,
4476 crate::AnyWindowHandle,
4477 CapturedActiveTooltip,
4478 ) {
4479 let mut test_app = TestAppContext::single();
4480 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
4481 let window = test_app.add_window({
4482 let captured_active_tooltip = captured_active_tooltip.clone();
4483 move |_, _| TooltipOwner {
4484 captured_active_tooltip,
4485 show_delay_override,
4486 }
4487 });
4488 let any_window = window.into();
4489
4490 test_app
4491 .update_window(any_window, |_, window, cx| {
4492 window.draw(cx).clear(cx);
4493 })
4494 .unwrap();
4495
4496 test_app
4497 .update_window(any_window, |_, window, cx| {
4498 window.dispatch_event(
4499 MouseMoveEvent {
4500 position: point(px(10.), px(10.)),
4501 modifiers: Default::default(),
4502 pressed_button: None,
4503 }
4504 .to_platform_input(),
4505 cx,
4506 );
4507 })
4508 .unwrap();
4509
4510 test_app
4511 .update_window(any_window, |_, window, cx| {
4512 window.draw(cx).clear(cx);
4513 })
4514 .unwrap();
4515
4516 (test_app, any_window, captured_active_tooltip)
4517 }
4518
4519 #[test]
4520 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
4521 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4522
4523 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4524 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4525 assert!(matches!(
4526 active_tooltip.borrow().as_ref(),
4527 Some(ActiveTooltip::WaitingForShow { .. })
4528 ));
4529
4530 test_app
4531 .update_window(any_window, |_, window, _| {
4532 window.remove_window();
4533 })
4534 .unwrap();
4535 test_app.run_until_parked();
4536 drop(active_tooltip);
4537
4538 assert!(weak_active_tooltip.upgrade().is_none());
4539 }
4540
4541 #[test]
4542 fn tooltip_respects_custom_show_delay() {
4543 let extra_delay = Duration::from_secs(1);
4544 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
4545 let (mut test_app, _any_window, captured_active_tooltip) =
4546 setup_tooltip_owner_test(Some(show_delay_override));
4547
4548 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4549 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4550
4551 test_app
4552 .dispatcher
4553 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4554 test_app.run_until_parked();
4555
4556 assert!(matches!(
4557 active_tooltip.borrow().as_ref(),
4558 Some(ActiveTooltip::WaitingForShow { .. })
4559 ));
4560
4561 test_app.dispatcher.advance_clock(extra_delay);
4562 test_app.run_until_parked();
4563
4564 assert!(matches!(
4565 active_tooltip.borrow().as_ref(),
4566 Some(ActiveTooltip::Visible { .. })
4567 ));
4568 }
4569
4570 #[test]
4571 fn tooltip_is_released_when_its_owner_disappears() {
4572 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4573
4574 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4575 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4576
4577 test_app
4578 .dispatcher
4579 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4580 test_app.run_until_parked();
4581
4582 assert!(matches!(
4583 active_tooltip.borrow().as_ref(),
4584 Some(ActiveTooltip::Visible { .. })
4585 ));
4586
4587 test_app
4588 .update_window(any_window, |_, window, _| {
4589 window.remove_window();
4590 })
4591 .unwrap();
4592 test_app.run_until_parked();
4593 drop(active_tooltip);
4594
4595 assert!(weak_active_tooltip.upgrade().is_none());
4596 }
4597
4598 #[test]
4599 fn tooltip_hides_after_mouse_leaves_origin() {
4600 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4601
4602 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4603 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4604
4605 test_app
4606 .dispatcher
4607 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4608 test_app.run_until_parked();
4609
4610 assert!(matches!(
4611 active_tooltip.borrow().as_ref(),
4612 Some(ActiveTooltip::Visible { .. })
4613 ));
4614
4615 test_app
4616 .update_window(any_window, |_, window, cx| {
4617 window.dispatch_event(
4618 MouseMoveEvent {
4619 position: point(px(75.), px(75.)),
4620 modifiers: Default::default(),
4621 pressed_button: None,
4622 }
4623 .to_platform_input(),
4624 cx,
4625 );
4626 })
4627 .unwrap();
4628
4629 assert!(active_tooltip.borrow().is_none());
4630 }
4631
4632 struct MouseDownOutOwner {
4633 mouse_down_out_count: Rc<RefCell<usize>>,
4634 }
4635
4636 impl Render for MouseDownOutOwner {
4637 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4638 let mouse_down_out_count = self.mouse_down_out_count.clone();
4639 div()
4640 .size_full()
4641 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
4642 move |_, _, _| {
4643 *mouse_down_out_count.borrow_mut() += 1;
4644 },
4645 ))
4646 }
4647 }
4648
4649 #[test]
4650 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
4651 let mut test_app = TestAppContext::single();
4652 let mouse_down_out_count = Rc::new(RefCell::new(0));
4653 let window = test_app.add_window({
4654 let mouse_down_out_count = mouse_down_out_count.clone();
4655 move |_, _| MouseDownOutOwner {
4656 mouse_down_out_count,
4657 }
4658 });
4659 let any_window: AnyWindowHandle = window.into();
4660
4661 fn dispatch_mouse_down_outside_target(
4662 test_app: &mut TestAppContext,
4663 any_window: AnyWindowHandle,
4664 ) {
4665 test_app
4666 .update_window(any_window, |_, window, cx| {
4667 window.dispatch_event(
4668 MouseDownEvent {
4669 position: point(px(75.), px(75.)),
4670 button: MouseButton::Left,
4671 modifiers: Default::default(),
4672 click_count: 1,
4673 first_mouse: false,
4674 }
4675 .to_platform_input(),
4676 cx,
4677 );
4678 })
4679 .unwrap();
4680 }
4681
4682 test_app
4683 .update_window(any_window, |_, window, cx| {
4684 window.draw(cx).clear(cx);
4685 })
4686 .unwrap();
4687
4688 dispatch_mouse_down_outside_target(&mut test_app, any_window);
4689 assert_eq!(
4690 *mouse_down_out_count.borrow(),
4691 1,
4692 "mouse down outside the element should fire mouse-down-out listeners"
4693 );
4694
4695 test_app
4696 .update_window(any_window, |_, window, cx| {
4697 cx.set_prompt_builder(crate::fallback_prompt_renderer);
4698 let _receiver =
4699 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
4700 assert!(window.has_active_prompt());
4701 window.draw(cx).clear(cx);
4702 })
4703 .unwrap();
4704
4705 dispatch_mouse_down_outside_target(&mut test_app, any_window);
4706 assert_eq!(
4707 *mouse_down_out_count.borrow(),
4708 1,
4709 "mouse down over an active prompt should not fire mouse-down-out listeners"
4710 );
4711 }
4712
4713 #[test]
4714 fn test_write_a11y_info_string_and_numeric_properties() {
4715 let mut interactivity = Interactivity::default();
4716 interactivity.aria.label = Some("Buffer Font Size".into());
4717 interactivity.aria.value = Some("15".into());
4718 interactivity.aria.placeholder = Some("Search".into());
4719 interactivity.aria.numeric_value = Some(15.0);
4720 interactivity.aria.min_numeric_value = Some(6.0);
4721 interactivity.aria.max_numeric_value = Some(72.0);
4722 interactivity.aria.numeric_value_step = Some(1.0);
4723
4724 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
4725 interactivity.write_a11y_info(&mut node);
4726
4727 assert_eq!(node.label(), Some("Buffer Font Size"));
4728 assert_eq!(node.value(), Some("15"));
4729 assert_eq!(node.placeholder(), Some("Search"));
4730 assert_eq!(node.numeric_value(), Some(15.0));
4731 assert_eq!(node.min_numeric_value(), Some(6.0));
4732 assert_eq!(node.max_numeric_value(), Some(72.0));
4733 assert_eq!(node.numeric_value_step(), Some(1.0));
4734 }
4735
4736 struct KeyboardActivationTest {
4739 focus_a: FocusHandle,
4740 focus_b: FocusHandle,
4741 clicks: Rc<RefCell<Vec<&'static str>>>,
4742 }
4743
4744 impl Render for KeyboardActivationTest {
4745 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4746 let clicks_a = self.clicks.clone();
4747 let clicks_b = self.clicks.clone();
4748 div()
4749 .size_full()
4750 .child(
4751 div()
4752 .id("a")
4753 .w(px(50.))
4754 .h(px(50.))
4755 .track_focus(&self.focus_a)
4756 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
4757 )
4758 .child(
4759 div()
4760 .id("b")
4761 .w(px(50.))
4762 .h(px(50.))
4763 .track_focus(&self.focus_b)
4764 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
4765 )
4766 }
4767 }
4768
4769 fn setup_keyboard_activation_test() -> (
4770 TestAppContext,
4771 AnyWindowHandle,
4772 Rc<RefCell<Vec<&'static str>>>,
4773 FocusHandle,
4774 FocusHandle,
4775 ) {
4776 let mut cx = TestAppContext::single();
4777 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
4778 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
4779 let window = cx.add_window({
4780 let focus_a = focus_a.clone();
4781 let focus_b = focus_b.clone();
4782 let clicks = clicks.clone();
4783 move |_, _| KeyboardActivationTest {
4784 focus_a,
4785 focus_b,
4786 clicks,
4787 }
4788 });
4789 (cx, window.into(), clicks, focus_a, focus_b)
4790 }
4791
4792 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
4795 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
4796 .unwrap();
4797 cx.run_until_parked();
4798 cx.update_window(window, |_, window, cx| {
4799 window.draw(cx).clear(cx);
4800 })
4801 .unwrap();
4802 }
4803
4804 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4805 let keystroke = Keystroke::parse(key).unwrap();
4806 cx.update_window(window, |_, window, cx| {
4807 window.dispatch_event(
4808 KeyDownEvent {
4809 keystroke,
4810 is_held: false,
4811 prefer_character_input: false,
4812 }
4813 .to_platform_input(),
4814 cx,
4815 );
4816 })
4817 .unwrap();
4818 }
4819
4820 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4821 let keystroke = Keystroke::parse(key).unwrap();
4822 cx.update_window(window, |_, window, cx| {
4823 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
4824 })
4825 .unwrap();
4826 }
4827
4828 #[test]
4830 fn keyboard_activation_fires_click_on_same_element() {
4831 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4832
4833 focus_and_draw(&mut cx, window, &focus_a);
4834 key_down(&mut cx, window, "enter");
4835 key_up(&mut cx, window, "enter");
4836
4837 assert_eq!(*clicks.borrow(), vec!["a"]);
4838 }
4839
4840 #[test]
4845 fn keyboard_activation_does_not_leak_across_focus_change() {
4846 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
4847
4848 focus_and_draw(&mut cx, window, &focus_a);
4850 key_down(&mut cx, window, "enter");
4851
4852 focus_and_draw(&mut cx, window, &focus_b);
4854 key_up(&mut cx, window, "enter");
4855
4856 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4859 }
4860
4861 #[test]
4866 fn keyboard_activation_does_not_leak_when_focus_returns() {
4867 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
4868
4869 focus_and_draw(&mut cx, window, &focus_a);
4871 key_down(&mut cx, window, "enter");
4872
4873 focus_and_draw(&mut cx, window, &focus_b);
4876 focus_and_draw(&mut cx, window, &focus_a);
4877 key_up(&mut cx, window, "enter");
4878
4879 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4881 }
4882
4883 #[test]
4888 fn keyboard_activation_cleared_by_intervening_key_release() {
4889 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4890
4891 focus_and_draw(&mut cx, window, &focus_a);
4892 key_down(&mut cx, window, "escape");
4893 key_down(&mut cx, window, "space");
4894 key_up(&mut cx, window, "escape");
4895 key_up(&mut cx, window, "space");
4896
4897 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4898 }
4899
4900 #[test]
4904 fn keyboard_activation_does_not_distinguish_space_and_enter() {
4905 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4906
4907 focus_and_draw(&mut cx, window, &focus_a);
4908 key_down(&mut cx, window, "space");
4909 key_up(&mut cx, window, "enter");
4910
4911 assert_eq!(*clicks.borrow(), vec!["a"]);
4912 }
4913
4914 #[test]
4917 fn keyboard_activation_cleared_by_intervening_keydown() {
4918 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4919
4920 focus_and_draw(&mut cx, window, &focus_a);
4921 key_down(&mut cx, window, "enter");
4922 key_down(&mut cx, window, "a");
4923 key_up(&mut cx, window, "enter");
4924
4925 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4926 }
4927
4928 #[test]
4931 fn keyboard_activation_ignores_modified_keys() {
4932 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4933
4934 focus_and_draw(&mut cx, window, &focus_a);
4935 key_down(&mut cx, window, "cmd-enter");
4936 key_up(&mut cx, window, "cmd-enter");
4937
4938 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4939 }
4940
4941 struct TabGroupFocus {
4945 group_a: FocusHandle,
4946 item_a: FocusHandle,
4947 group_b: FocusHandle,
4948 item_b: FocusHandle,
4949 }
4950
4951 impl Render for TabGroupFocus {
4952 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4953 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
4954 div()
4955 .track_focus(container)
4956 .tab_group()
4957 .child(div().track_focus(item))
4958 }
4959 div()
4960 .child(group(&self.group_a, &self.item_a))
4961 .child(group(&self.group_b, &self.item_b))
4962 }
4963 }
4964
4965 #[test]
4969 fn focus_next_from_tab_group_container_enters_that_group() {
4970 let mut cx = TestAppContext::single();
4971 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
4972 (
4973 cx.focus_handle(),
4974 cx.focus_handle().tab_stop(true),
4975 cx.focus_handle(),
4976 cx.focus_handle().tab_stop(true),
4977 )
4978 });
4979 let window: AnyWindowHandle = cx
4980 .add_window({
4981 let (group_a, item_a, group_b, item_b) =
4982 (group_a, item_a, group_b.clone(), item_b.clone());
4983 move |_, _| TabGroupFocus {
4984 group_a,
4985 item_a,
4986 group_b,
4987 item_b,
4988 }
4989 })
4990 .into();
4991 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4992 .unwrap();
4993
4994 let focused = cx
4996 .update_window(window, |_, window, cx| {
4997 window.focus(&group_b, cx);
4998 window.focus_next(cx);
4999 window.focused(cx).map(|handle| handle.id)
5000 })
5001 .unwrap();
5002
5003 assert_eq!(focused, Some(item_b.id));
5004 }
5005
5006 #[gpui::test]
5007 fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5008 cx: &mut TestAppContext,
5009 ) {
5010 struct PaddedContainer {
5011 scroll_handle: ScrollHandle,
5012 }
5013
5014 impl Render for PaddedContainer {
5015 fn render(
5016 &mut self,
5017 _window: &mut Window,
5018 _cx: &mut Context<Self>,
5019 ) -> impl IntoElement {
5020 div().size_full().child(
5023 div()
5024 .id("container")
5025 .h(px(50.))
5026 .w(px(100.))
5027 .py(px(4.25))
5028 .overflow_y_scroll()
5029 .track_scroll(&self.scroll_handle)
5030 .child(div().w_full().h(px(42.))),
5031 )
5032 }
5033 }
5034
5035 let scroll_handle = ScrollHandle::new();
5036 let window: AnyWindowHandle = cx
5037 .add_window({
5038 let scroll_handle = scroll_handle.clone();
5039 move |_, _| PaddedContainer { scroll_handle }
5040 })
5041 .into();
5042 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5043 .unwrap();
5044
5045 assert_eq!(scroll_handle.max_offset().y, px(0.));
5046 }
5047}