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.padding.to_pixels(bounds.size.into(), rem_size);
2328 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2329 let padded_content_size = self.content_size + padding_size;
2336 let scroll_max = Point::from(padded_content_size - bounds.size)
2337 .map(round_to_two_decimals)
2338 .max(&Default::default());
2339 let mut scroll_offset = scroll_offset.borrow_mut();
2342
2343 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2344 if scroll_to_bottom {
2345 scroll_offset.y = -scroll_max.y;
2346 } else {
2347 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2348 }
2349
2350 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2351 scroll_handle_state.max_offset = scroll_max;
2352 scroll_handle_state.bounds = bounds;
2353 }
2354
2355 *scroll_offset
2356 } else {
2357 Point::default()
2358 }
2359 }
2360
2361 pub fn paint(
2370 &mut self,
2371 global_id: Option<&GlobalElementId>,
2372 _inspector_id: Option<&InspectorElementId>,
2373 bounds: Bounds<Pixels>,
2374 hitbox: Option<&Hitbox>,
2375 window: &mut Window,
2376 cx: &mut App,
2377 f: impl FnOnce(&Style, &mut Window, &mut App),
2378 ) {
2379 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2380 window.with_optional_element_state::<InteractiveElementState, _>(
2381 global_id,
2382 |element_state, window| {
2383 let mut element_state =
2384 element_state.map(|element_state| element_state.unwrap_or_default());
2385
2386 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2387
2388 #[cfg(any(feature = "test-support", test))]
2389 if let Some(debug_selector) = &self.debug_selector {
2390 window
2391 .next_frame
2392 .debug_bounds
2393 .insert(debug_selector.clone(), bounds);
2394 }
2395
2396 self.paint_hover_group_handler(window, cx);
2397
2398 if style.visibility == Visibility::Hidden {
2399 return ((), element_state);
2400 }
2401
2402 let mut tab_group = None;
2403 if self.tab_group {
2404 tab_group = self.tab_index;
2405 }
2406
2407 window.with_element_opacity(style.opacity, |window| {
2408 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2409 window.with_text_style(style.text_style().cloned(), |window| {
2410 window.with_content_mask(
2411 style.overflow_mask(bounds, window.rem_size()),
2412 |window| {
2413 window.with_tab_group(tab_group, |window| {
2414 if let Some(focus_handle) = &self.tracked_focus_handle {
2423 window.next_frame.tab_stops.insert(focus_handle);
2424 }
2425 if let Some(hitbox) = hitbox {
2426 #[cfg(debug_assertions)]
2427 self.paint_debug_info(
2428 global_id, hitbox, &style, window, cx,
2429 );
2430
2431 if let Some(drag) = cx.active_drag.as_ref() {
2432 if let Some(mouse_cursor) = drag.cursor_style {
2433 window.set_window_cursor_style(mouse_cursor);
2434 }
2435 } else {
2436 if let Some(mouse_cursor) = style.mouse_cursor {
2437 window.set_cursor_style(mouse_cursor, hitbox);
2438 }
2439 }
2440
2441 if let Some(group) = self.group.clone() {
2442 GroupHitboxes::push(group, hitbox.id, cx);
2443 }
2444
2445 if let Some(area) = self.window_control {
2446 window.insert_window_control_hitbox(
2447 area,
2448 hitbox.clone(),
2449 );
2450 }
2451
2452 self.paint_mouse_listeners(
2453 hitbox,
2454 element_state.as_mut(),
2455 window,
2456 cx,
2457 );
2458 self.paint_scroll_listener(hitbox, &style, window, cx);
2459 }
2460
2461 self.paint_keyboard_listeners(window, cx);
2462
2463 if window.a11y.is_active() {
2464 if let Some(global_id) = global_id {
2465 if !self.a11y_action_listeners.is_empty() {
2466 let node_id = global_id.accesskit_node_id();
2467 for (action, listener) in
2468 self.a11y_action_listeners.drain(..)
2469 {
2470 window.on_a11y_action(
2471 node_id, action, listener,
2472 );
2473 }
2474 }
2475 }
2476 }
2477
2478 f(&style, window, cx);
2479
2480 if let Some(_hitbox) = hitbox {
2481 #[cfg(any(feature = "inspector", debug_assertions))]
2482 window.insert_inspector_hitbox(
2483 _hitbox.id,
2484 _inspector_id,
2485 cx,
2486 );
2487
2488 if let Some(group) = self.group.as_ref() {
2489 GroupHitboxes::pop(group, cx);
2490 }
2491 }
2492 })
2493 },
2494 );
2495 });
2496 });
2497 });
2498
2499 ((), element_state)
2500 },
2501 );
2502 }
2503
2504 #[cfg(debug_assertions)]
2505 fn paint_debug_info(
2506 &self,
2507 global_id: Option<&GlobalElementId>,
2508 hitbox: &Hitbox,
2509 style: &Style,
2510 window: &mut Window,
2511 cx: &mut App,
2512 ) {
2513 use crate::{BorderStyle, TextAlign};
2514
2515 if let Some(global_id) = global_id
2516 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2517 && hitbox.is_hovered(window)
2518 {
2519 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2520 let element_id = format!("{global_id:?}");
2521 let str_len = element_id.len();
2522
2523 let render_debug_text = |window: &mut Window| {
2524 if let Some(text) = window
2525 .text_system()
2526 .shape_text(
2527 element_id.into(),
2528 FONT_SIZE,
2529 &[window.text_style().to_run(str_len)],
2530 None,
2531 None,
2532 )
2533 .ok()
2534 .and_then(|mut text| text.pop())
2535 {
2536 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2537 .ok();
2538
2539 let text_bounds = crate::Bounds {
2540 origin: hitbox.origin,
2541 size: text.size(FONT_SIZE),
2542 };
2543 if let Some(source_location) = self.source_location
2544 && text_bounds.contains(&window.mouse_position())
2545 && window.modifiers().secondary()
2546 {
2547 let secondary_held = window.modifiers().secondary();
2548 window.on_key_event({
2549 move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2550 if e.modifiers.secondary() != secondary_held
2551 && text_bounds.contains(&window.mouse_position())
2552 {
2553 window.refresh();
2554 }
2555 }
2556 });
2557
2558 let was_hovered = hitbox.is_hovered(window);
2559 let current_view = window.current_view();
2560 window.on_mouse_event({
2561 let hitbox = hitbox.clone();
2562 move |_: &MouseMoveEvent, phase, window, cx| {
2563 if phase == DispatchPhase::Capture {
2564 let hovered = hitbox.is_hovered(window);
2565 if hovered != was_hovered {
2566 cx.notify(current_view)
2567 }
2568 }
2569 }
2570 });
2571
2572 window.on_mouse_event({
2573 let hitbox = hitbox.clone();
2574 move |e: &crate::MouseDownEvent, phase, window, cx| {
2575 if text_bounds.contains(&e.position)
2576 && phase.capture()
2577 && hitbox.is_hovered(window)
2578 {
2579 cx.stop_propagation();
2580 let Ok(dir) = std::env::current_dir() else {
2581 return;
2582 };
2583
2584 eprintln!(
2585 "This element was created at:\n{}:{}:{}",
2586 dir.join(source_location.file()).to_string_lossy(),
2587 source_location.line(),
2588 source_location.column()
2589 );
2590 }
2591 }
2592 });
2593 window.paint_quad(crate::outline(
2594 crate::Bounds {
2595 origin: hitbox.origin
2596 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2597 size: crate::Size {
2598 width: text_bounds.size.width,
2599 height: crate::px(1.),
2600 },
2601 },
2602 crate::red(),
2603 BorderStyle::default(),
2604 ))
2605 }
2606 }
2607 };
2608
2609 window.with_text_style(
2610 Some(crate::TextStyleRefinement {
2611 color: Some(crate::red()),
2612 line_height: Some(FONT_SIZE.into()),
2613 background_color: Some(crate::white()),
2614 ..Default::default()
2615 }),
2616 render_debug_text,
2617 )
2618 }
2619 }
2620
2621 fn paint_mouse_listeners(
2622 &mut self,
2623 hitbox: &Hitbox,
2624 element_state: Option<&mut InteractiveElementState>,
2625 window: &mut Window,
2626 cx: &mut App,
2627 ) {
2628 let is_focused = self
2629 .tracked_focus_handle
2630 .as_ref()
2631 .map(|handle| handle.is_focused(window))
2632 .unwrap_or(false);
2633
2634 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2638 let hitbox = hitbox.clone();
2639 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2640 if phase == DispatchPhase::Bubble
2641 && hitbox.is_hovered(window)
2642 && !window.default_prevented()
2643 {
2644 window.focus(&focus_handle, cx);
2645 window.prevent_default();
2648 }
2649 });
2650 }
2651
2652 for listener in self.mouse_down_listeners.drain(..) {
2653 let hitbox = hitbox.clone();
2654 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2655 listener(event, phase, &hitbox, window, cx);
2656 })
2657 }
2658
2659 for listener in self.mouse_up_listeners.drain(..) {
2660 let hitbox = hitbox.clone();
2661 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2662 listener(event, phase, &hitbox, window, cx);
2663 })
2664 }
2665
2666 for listener in self.mouse_pressure_listeners.drain(..) {
2667 let hitbox = hitbox.clone();
2668 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2669 listener(event, phase, &hitbox, window, cx);
2670 })
2671 }
2672
2673 for listener in self.mouse_move_listeners.drain(..) {
2674 let hitbox = hitbox.clone();
2675 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2676 listener(event, phase, &hitbox, window, cx);
2677 })
2678 }
2679
2680 for listener in self.mouse_exit_listeners.drain(..) {
2681 let hitbox = hitbox.clone();
2682 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2683 listener(event, phase, &hitbox, window, cx);
2684 })
2685 }
2686
2687 for listener in self.scroll_wheel_listeners.drain(..) {
2688 let hitbox = hitbox.clone();
2689 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2690 listener(event, phase, &hitbox, window, cx);
2691 })
2692 }
2693
2694 for listener in self.pinch_listeners.drain(..) {
2695 let hitbox = hitbox.clone();
2696 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2697 listener(event, phase, &hitbox, window, cx);
2698 })
2699 }
2700
2701 if self.hover_style.is_some()
2702 || self.base_style.mouse_cursor.is_some()
2703 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2704 {
2705 let hitbox = hitbox.clone();
2706 let hover_state = self.hover_style.as_ref().and_then(|_| {
2707 element_state
2708 .as_ref()
2709 .and_then(|state| state.hover_state.as_ref())
2710 .cloned()
2711 });
2712 let current_view = window.current_view();
2713
2714 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2715 let hovered = hitbox.is_hovered(window);
2716 let was_hovered = hover_state
2717 .as_ref()
2718 .is_some_and(|state| state.borrow().element);
2719 if phase == DispatchPhase::Capture && hovered != was_hovered {
2720 if let Some(hover_state) = &hover_state {
2721 hover_state.borrow_mut().element = hovered;
2722 cx.notify(current_view);
2723 }
2724 }
2725 });
2726 }
2727
2728 if let Some(group_hover) = self.group_hover_style.as_ref() {
2729 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2730 let hover_state = element_state
2731 .as_ref()
2732 .and_then(|element| element.hover_state.as_ref())
2733 .cloned();
2734 let current_view = window.current_view();
2735
2736 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2737 let group_hovered = group_hitbox_id.is_hovered(window);
2738 let was_group_hovered = hover_state
2739 .as_ref()
2740 .is_some_and(|state| state.borrow().group);
2741 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2742 if let Some(hover_state) = &hover_state {
2743 hover_state.borrow_mut().group = group_hovered;
2744 cx.notify(current_view);
2745 }
2746 }
2747 });
2748 }
2749 }
2750
2751 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2752
2753 let mut drag_listener = mem::take(&mut self.drag_listener);
2754 let drop_listeners = mem::take(&mut self.drop_listeners);
2755 let click_listeners = mem::take(&mut self.click_listeners);
2756 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2757 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2758
2759 if !drop_listeners.is_empty() {
2760 let hitbox = hitbox.clone();
2761 window.on_mouse_event({
2762 move |_: &MouseUpEvent, phase, window, cx| {
2763 if let Some(drag) = &cx.active_drag
2764 && phase == DispatchPhase::Bubble
2765 && hitbox.is_hovered(window)
2766 {
2767 let drag_state_type = drag.value.as_ref().type_id();
2768 for (drop_state_type, listener) in &drop_listeners {
2769 if *drop_state_type == drag_state_type {
2770 let drag = cx
2771 .active_drag
2772 .take()
2773 .expect("checked for type drag state type above");
2774
2775 let mut can_drop = true;
2776 if let Some(predicate) = &can_drop_predicate {
2777 can_drop = predicate(drag.value.as_ref(), window, cx);
2778 }
2779
2780 if can_drop {
2781 listener(drag.value.as_ref(), window, cx);
2782 window.refresh();
2783 cx.stop_propagation();
2784 }
2785 }
2786 }
2787 }
2788 }
2789 });
2790 }
2791
2792 if let Some(element_state) = element_state {
2793 if !click_listeners.is_empty()
2794 || !aux_click_listeners.is_empty()
2795 || drag_listener.is_some()
2796 {
2797 let pending_mouse_down = element_state
2798 .pending_mouse_down
2799 .get_or_insert_with(Default::default)
2800 .clone();
2801
2802 let pending_keyboard_down = element_state
2803 .pending_keyboard_down
2804 .get_or_insert_with(Default::default)
2805 .clone();
2806
2807 let clicked_state = element_state
2808 .clicked_state
2809 .get_or_insert_with(Default::default)
2810 .clone();
2811
2812 window.on_mouse_event({
2813 let pending_mouse_down = pending_mouse_down.clone();
2814 let hitbox = hitbox.clone();
2815 let has_aux_click_listeners = !aux_click_listeners.is_empty();
2816 move |event: &MouseDownEvent, phase, window, _cx| {
2817 if phase == DispatchPhase::Bubble
2818 && (event.button == MouseButton::Left || has_aux_click_listeners)
2819 && hitbox.is_hovered(window)
2820 {
2821 *pending_mouse_down.borrow_mut() = Some(event.clone());
2822 window.refresh();
2823 }
2824 }
2825 });
2826
2827 window.on_mouse_event({
2828 let pending_mouse_down = pending_mouse_down.clone();
2829 let hitbox = hitbox.clone();
2830 move |event: &MouseMoveEvent, phase, window, cx| {
2831 if phase == DispatchPhase::Capture {
2832 return;
2833 }
2834
2835 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2836 if let Some(mouse_down) = pending_mouse_down.clone()
2837 && !cx.has_active_drag()
2838 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2839 && let Some(listener) = drag_listener.take()
2840 && mouse_down.button == MouseButton::Left
2841 {
2842 *clicked_state.borrow_mut() = ElementClickedState::default();
2843 let cursor_offset = event.position - hitbox.origin;
2844 let drag = (listener.render)(
2845 listener.value.as_ref(),
2846 cursor_offset,
2847 window,
2848 cx,
2849 );
2850 let external_payload_source =
2851 listener.external_payload.map(|external_payload| {
2852 let value = listener.value.clone();
2853 Box::new(move |window: &mut Window, cx: &mut App| {
2854 external_payload(value.as_ref(), window, cx)
2855 })
2856 as ExternalDragPayloadSource
2857 });
2858 cx.active_drag = Some(AnyDrag {
2859 view: drag,
2860 value: listener.value,
2861 cursor_offset,
2862 cursor_style: drag_cursor_style,
2863 external_payload_source,
2864 });
2865 pending_mouse_down.take();
2866 window.refresh();
2867 cx.stop_propagation();
2868 }
2869 }
2870 });
2871
2872 if is_focused {
2873 window.on_key_event({
2883 let pending_keyboard_down = pending_keyboard_down.clone();
2884 move |event: &KeyDownEvent, phase, window, _cx| {
2885 if phase.bubble() && !window.default_prevented() {
2886 let stroke = &event.keystroke;
2887 let is_activation_key = (stroke.key.eq("enter")
2888 || stroke.key.eq("space"))
2889 && !stroke.modifiers.modified();
2890 *pending_keyboard_down.borrow_mut() =
2891 is_activation_key.then_some(window.focus_generation);
2892 }
2893 }
2894 });
2895
2896 window.on_key_event({
2898 let click_listeners = click_listeners.clone();
2899 let hitbox = hitbox.clone();
2900 move |event: &KeyUpEvent, phase, window, cx| {
2901 if phase.bubble() && !window.default_prevented() {
2902 let stroke = &event.keystroke;
2903 let keyboard_button = if stroke.key.eq("enter") {
2904 Some(KeyboardButton::Enter)
2905 } else if stroke.key.eq("space") {
2906 Some(KeyboardButton::Space)
2907 } else {
2908 None
2909 };
2910
2911 if let Some(button) = keyboard_button
2912 && !stroke.modifiers.modified()
2913 {
2914 let pending =
2915 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
2916 if pending != Some(window.focus_generation) {
2917 return;
2918 }
2919
2920 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2921 button,
2922 bounds: hitbox.bounds,
2923 });
2924
2925 for listener in &click_listeners {
2926 listener(&click_event, window, cx);
2927 }
2928 } else {
2929 *pending_keyboard_down.borrow_mut() = None;
2933 }
2934 }
2935 }
2936 });
2937 }
2938
2939 window.on_mouse_event({
2940 let mut captured_mouse_down = None;
2941 let hitbox = hitbox.clone();
2942 move |event: &MouseUpEvent, phase, window, cx| match phase {
2943 DispatchPhase::Capture => {
2947 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2948 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2949 captured_mouse_down = pending_mouse_down.take();
2950 window.refresh();
2951 } else if pending_mouse_down.is_some() {
2952 pending_mouse_down.take();
2958 window.refresh();
2959 }
2960 }
2961 DispatchPhase::Bubble => {
2963 if let Some(mouse_down) = captured_mouse_down.take() {
2964 let btn = mouse_down.button;
2965
2966 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2967 down: mouse_down,
2968 up: event.clone(),
2969 });
2970
2971 match btn {
2972 MouseButton::Left => {
2973 for listener in &click_listeners {
2974 listener(&mouse_click, window, cx);
2975 }
2976 }
2977 _ => {
2978 for listener in &aux_click_listeners {
2979 listener(&mouse_click, window, cx);
2980 }
2981 }
2982 }
2983 }
2984 }
2985 }
2986 });
2987 }
2988
2989 if let Some(hover_listener) = self.hover_listener.take() {
2990 let was_hovered = element_state
2991 .hover_listener_state
2992 .get_or_insert_with(Default::default)
2993 .clone();
2994 let has_mouse_down = element_state
2995 .pending_mouse_down
2996 .get_or_insert_with(Default::default)
2997 .clone();
2998 let hover_listener = Rc::new(hover_listener);
2999 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3000 let mut was_hovered = was_hovered.borrow_mut();
3001 if is_hovered != *was_hovered {
3002 *was_hovered = is_hovered;
3003 drop(was_hovered);
3004 hover_listener(&is_hovered, window, cx);
3005 }
3006 };
3007
3008 window.on_mouse_event({
3009 let update_hover = update_hover.clone();
3010 let hitbox = hitbox.clone();
3011 move |_: &MouseMoveEvent, phase, window, cx| {
3012 if phase == DispatchPhase::Bubble {
3013 let is_hovered = has_mouse_down.borrow().is_none()
3014 && !cx.has_active_drag()
3015 && hitbox.is_hovered(window);
3016 update_hover(is_hovered, window, cx);
3017 }
3018 }
3019 });
3020
3021 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3024 if phase == DispatchPhase::Bubble {
3025 update_hover(false, window, cx);
3026 }
3027 });
3028 }
3029
3030 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3031 let active_tooltip = element_state
3032 .active_tooltip
3033 .get_or_insert_with(Default::default)
3034 .clone();
3035 let pending_mouse_down = element_state
3036 .pending_mouse_down
3037 .get_or_insert_with(Default::default)
3038 .clone();
3039
3040 let tooltip_is_hoverable = tooltip_builder.hoverable;
3041 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3042 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3043 });
3044 let check_is_hovered_during_prepaint = Rc::new({
3046 let pending_mouse_down = pending_mouse_down.clone();
3047 let source_bounds = hitbox.bounds;
3048 move |window: &Window| {
3049 !window.last_input_was_keyboard()
3050 && pending_mouse_down.borrow().is_none()
3051 && source_bounds.contains(&window.mouse_position())
3052 }
3053 });
3054 let check_is_hovered = Rc::new({
3055 let hitbox = hitbox.clone();
3056 move |window: &Window| {
3057 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3058 }
3059 });
3060 register_tooltip_mouse_handlers(
3061 &active_tooltip,
3062 self.tooltip_id,
3063 build_tooltip,
3064 check_is_hovered,
3065 check_is_hovered_during_prepaint,
3066 self.tooltip_show_delay,
3067 window,
3068 );
3069 }
3070
3071 let active_state = element_state
3074 .clicked_state
3075 .get_or_insert_with(Default::default)
3076 .clone();
3077
3078 {
3079 let active_state = active_state.clone();
3080 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3081 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3082 *active_state.borrow_mut() = ElementClickedState::default();
3083 window.refresh();
3084 }
3085 });
3086 }
3087
3088 {
3089 let active_group_hitbox = self
3090 .group_active_style
3091 .as_ref()
3092 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3093 let hitbox = hitbox.clone();
3094 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3095 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3096 let group_hovered = active_group_hitbox
3097 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3098 let element_hovered = hitbox.is_hovered(window);
3099 if group_hovered || element_hovered {
3100 *active_state.borrow_mut() = ElementClickedState {
3101 group: group_hovered,
3102 element: element_hovered,
3103 };
3104 window.refresh();
3105 }
3106 }
3107 });
3108 }
3109 }
3110 }
3111
3112 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3113 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3114 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3115 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3116 let action_listeners = mem::take(&mut self.action_listeners);
3117 if let Some(context) = self.key_context.clone() {
3118 window.set_key_context(context);
3119 }
3120
3121 for listener in key_down_listeners {
3122 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3123 listener(event, phase, window, cx);
3124 })
3125 }
3126
3127 for listener in key_up_listeners {
3128 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3129 listener(event, phase, window, cx);
3130 })
3131 }
3132
3133 for listener in modifiers_changed_listeners {
3134 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3135 listener(event, window, cx);
3136 })
3137 }
3138
3139 for (action_type, listener) in action_listeners {
3140 window.on_action(action_type, listener)
3141 }
3142 }
3143
3144 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3145 let group_hitbox = self
3146 .group_hover_style
3147 .as_ref()
3148 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3149
3150 if let Some(group_hitbox) = group_hitbox {
3151 let was_hovered = group_hitbox.is_hovered(window);
3152 let current_view = window.current_view();
3153 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3154 let hovered = group_hitbox.is_hovered(window);
3155 if phase == DispatchPhase::Capture && hovered != was_hovered {
3156 cx.notify(current_view);
3157 }
3158 });
3159 }
3160 }
3161
3162 fn paint_scroll_listener(
3163 &self,
3164 hitbox: &Hitbox,
3165 style: &Style,
3166 window: &mut Window,
3167 _cx: &mut App,
3168 ) {
3169 if let Some(scroll_offset) = self.scroll_offset.clone() {
3170 let ongoing_scroll = self.ongoing_scroll.clone();
3171 let overflow = style.overflow;
3172 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3173 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3174 let line_height = window.line_height();
3175 let hitbox = hitbox.clone();
3176 let current_view = window.current_view();
3177 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
3178 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3179 let mut scroll_offset = scroll_offset.borrow_mut();
3180 let old_scroll_offset = *scroll_offset;
3181 let mut delta = event.delta.pixel_delta(line_height);
3182
3183 if restrict_scroll_to_axis
3184 && event.delta.precise()
3185 && let Some(ongoing_scroll) = &ongoing_scroll
3186 {
3187 ongoing_scroll
3188 .borrow_mut()
3189 .filter(&mut delta, event.touch_phase);
3190 }
3191
3192 let mut delta_x = match overflow.x {
3193 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3194 Overflow::Scroll
3195 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3196 {
3197 delta.y
3198 }
3199 _ => Pixels::ZERO,
3200 };
3201 let mut delta_y = match overflow.y {
3202 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3203 Overflow::Scroll
3204 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3205 {
3206 delta.x
3207 }
3208 _ => Pixels::ZERO,
3209 };
3210 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3211 if delta_x.abs() > delta_y.abs() {
3212 delta_y = Pixels::ZERO;
3213 } else {
3214 delta_x = Pixels::ZERO;
3215 }
3216 }
3217 scroll_offset.y += delta_y;
3218 scroll_offset.x += delta_x;
3219 if *scroll_offset != old_scroll_offset {
3220 cx.notify(current_view);
3221 }
3222 }
3223 });
3224 }
3225 }
3226
3227 pub fn compute_style(
3229 &self,
3230 global_id: Option<&GlobalElementId>,
3231 hitbox: Option<&Hitbox>,
3232 window: &mut Window,
3233 cx: &mut App,
3234 ) -> Style {
3235 window.with_optional_element_state(global_id, |element_state, window| {
3236 let mut element_state =
3237 element_state.map(|element_state| element_state.unwrap_or_default());
3238 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3239 (style, element_state)
3240 })
3241 }
3242
3243 fn compute_style_internal(
3245 &self,
3246 hitbox: Option<&Hitbox>,
3247 element_state: Option<&mut InteractiveElementState>,
3248 window: &mut Window,
3249 cx: &mut App,
3250 ) -> Style {
3251 let mut style = Style::default();
3252 style.refine(&self.base_style);
3253
3254 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3255 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3256 && focus_handle.within_focused(window, cx)
3257 {
3258 style.refine(in_focus_style);
3259 }
3260
3261 if let Some(focus_style) = self.focus_style.as_ref()
3262 && focus_handle.is_focused(window)
3263 {
3264 style.refine(focus_style);
3265 }
3266
3267 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3268 && focus_handle.is_focused(window)
3269 && window.last_input_was_keyboard()
3270 {
3271 style.refine(focus_visible_style);
3272 }
3273 }
3274
3275 if !cx.has_active_drag() {
3276 if let Some(group_hover) = self.group_hover_style.as_ref() {
3277 let is_group_hovered =
3278 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3279 group_hitbox_id.is_hovered(window)
3280 } else if let Some(element_state) = element_state.as_ref() {
3281 element_state
3282 .hover_state
3283 .as_ref()
3284 .map(|state| state.borrow().group)
3285 .unwrap_or(false)
3286 } else {
3287 false
3288 };
3289
3290 if is_group_hovered {
3291 style.refine(&group_hover.style);
3292 }
3293 }
3294
3295 if let Some(hover_style) = self.hover_style.as_ref() {
3296 let is_hovered = if let Some(hitbox) = hitbox {
3297 hitbox.is_hovered(window)
3298 } else if let Some(element_state) = element_state.as_ref() {
3299 element_state
3300 .hover_state
3301 .as_ref()
3302 .map(|state| state.borrow().element)
3303 .unwrap_or(false)
3304 } else {
3305 false
3306 };
3307
3308 if is_hovered {
3309 style.refine(hover_style);
3310 }
3311 }
3312 }
3313
3314 if let Some(hitbox) = hitbox {
3315 if let Some(drag) = cx.active_drag.take() {
3316 let mut can_drop = true;
3317 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3318 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3319 }
3320
3321 if can_drop {
3322 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3323 if let Some(group_hitbox_id) =
3324 GroupHitboxes::get(&group_drag_style.group, cx)
3325 && *state_type == drag.value.as_ref().type_id()
3326 && group_hitbox_id.is_hovered(window)
3327 {
3328 style.refine(&group_drag_style.style);
3329 }
3330 }
3331
3332 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3333 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3334 {
3335 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3336 }
3337 }
3338 }
3339
3340 style.mouse_cursor = drag.cursor_style;
3341 cx.active_drag = Some(drag);
3342 }
3343 }
3344
3345 if let Some(element_state) = element_state {
3346 let clicked_state = element_state
3347 .clicked_state
3348 .get_or_insert_with(Default::default)
3349 .borrow();
3350 if clicked_state.group
3351 && let Some(group) = self.group_active_style.as_ref()
3352 {
3353 style.refine(&group.style)
3354 }
3355
3356 if let Some(active_style) = self.active_style.as_ref()
3357 && clicked_state.element
3358 {
3359 style.refine(active_style)
3360 }
3361 }
3362
3363 style
3364 }
3365
3366 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3367 if let Some(label) = &self.aria.label {
3368 node.set_label(label.to_string());
3369 }
3370 if let Some(description) = &self.aria.description {
3371 node.set_description(description.to_string());
3372 }
3373 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3374 node.set_keyboard_shortcut(keyshortcuts.to_string());
3375 }
3376 if let Some(selected) = self.aria.selected {
3377 node.set_selected(selected);
3378 }
3379 if let Some(expanded) = self.aria.expanded {
3380 node.set_expanded(expanded);
3381 }
3382 if let Some(toggled) = self.aria.toggled {
3383 node.set_toggled(toggled);
3384 }
3385 if let Some(value) = self.aria.numeric_value {
3386 node.set_numeric_value(value);
3387 }
3388 if let Some(value) = self.aria.min_numeric_value {
3389 node.set_min_numeric_value(value);
3390 }
3391 if let Some(value) = self.aria.max_numeric_value {
3392 node.set_max_numeric_value(value);
3393 }
3394 if let Some(step) = self.aria.numeric_value_step {
3395 node.set_numeric_value_step(step);
3396 }
3397 if let Some(value) = &self.aria.value {
3398 node.set_value(value.to_string());
3399 }
3400 if let Some(placeholder) = &self.aria.placeholder {
3401 node.set_placeholder(placeholder.to_string());
3402 }
3403 if let Some(orientation) = self.aria.orientation {
3404 node.set_orientation(orientation);
3405 }
3406 if let Some(level) = self.aria.level {
3407 node.set_level(level);
3408 }
3409 if let Some(position) = self.aria.position_in_set {
3410 node.set_position_in_set(position);
3411 }
3412 if let Some(size) = self.aria.size_of_set {
3413 node.set_size_of_set(size);
3414 }
3415 if let Some(index) = self.aria.row_index {
3416 node.set_row_index(index);
3417 }
3418 if let Some(index) = self.aria.column_index {
3419 node.set_column_index(index);
3420 }
3421 if let Some(count) = self.aria.row_count {
3422 node.set_row_count(count);
3423 }
3424 if let Some(count) = self.aria.column_count {
3425 node.set_column_count(count);
3426 }
3427 if !self.click_listeners.is_empty() {
3428 node.add_action(accesskit::Action::Click);
3429 }
3430 if self.tracked_focus_handle.is_some() || self.focusable {
3431 node.add_action(accesskit::Action::Focus);
3432 }
3433 for (action, _) in &self.a11y_action_listeners {
3434 node.add_action(*action);
3435 }
3436 }
3437}
3438
3439#[derive(Default)]
3442pub struct InteractiveElementState {
3443 pub(crate) focus_handle: Option<FocusHandle>,
3444 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3445 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3446 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3447 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3448 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3456 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3457 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3458 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3459}
3460
3461#[derive(Copy, Clone, Default, Eq, PartialEq)]
3463pub struct ElementClickedState {
3464 pub group: bool,
3466
3467 pub element: bool,
3469}
3470
3471impl ElementClickedState {
3472 fn is_clicked(&self) -> bool {
3473 self.group || self.element
3474 }
3475}
3476
3477#[derive(Copy, Clone, Default, Eq, PartialEq)]
3479pub struct ElementHoverState {
3480 pub group: bool,
3482
3483 pub element: bool,
3485}
3486
3487pub(crate) enum ActiveTooltip {
3488 WaitingForShow { _task: Task<()> },
3490 Visible {
3492 tooltip: AnyTooltip,
3493 is_hoverable: bool,
3494 },
3495 WaitingForHide {
3498 tooltip: AnyTooltip,
3499 _task: Task<()>,
3500 },
3501}
3502
3503pub(crate) fn clear_active_tooltip(
3504 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3505 window: &mut Window,
3506) {
3507 match active_tooltip.borrow_mut().take() {
3508 None => {}
3509 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3510 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3511 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3512 }
3513}
3514
3515pub(crate) fn clear_active_tooltip_if_not_hoverable(
3516 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3517 window: &mut Window,
3518) {
3519 let should_clear = match active_tooltip.borrow().as_ref() {
3520 None => false,
3521 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3522 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3523 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3524 };
3525 if should_clear {
3526 active_tooltip.borrow_mut().take();
3527 window.refresh();
3528 }
3529}
3530
3531pub(crate) fn set_tooltip_on_window(
3532 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3533 window: &mut Window,
3534) -> Option<TooltipId> {
3535 let tooltip = match active_tooltip.borrow().as_ref() {
3536 None => return None,
3537 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3538 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3539 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3540 };
3541 Some(window.set_tooltip(tooltip))
3542}
3543
3544pub(crate) fn register_tooltip_mouse_handlers(
3545 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3546 tooltip_id: Option<TooltipId>,
3547 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3548 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3549 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3550 show_delay: Option<Duration>,
3551 window: &mut Window,
3552) {
3553 let current_view = window.current_view();
3554 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3555
3556 window.on_mouse_event({
3557 let active_tooltip = active_tooltip.clone();
3558 let build_tooltip = build_tooltip.clone();
3559 let check_is_hovered = check_is_hovered.clone();
3560 move |_: &MouseMoveEvent, phase, window, cx| {
3561 handle_tooltip_mouse_move(
3562 &active_tooltip,
3563 &build_tooltip,
3564 &check_is_hovered,
3565 &check_is_hovered_during_prepaint,
3566 tooltip_id,
3567 current_view,
3568 phase,
3569 show_delay,
3570 window,
3571 cx,
3572 )
3573 }
3574 });
3575
3576 window.on_mouse_event({
3577 let active_tooltip = active_tooltip.clone();
3578 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3579 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3580 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3581 }
3582 }
3583 });
3584
3585 window.on_mouse_event({
3586 let active_tooltip = active_tooltip.clone();
3587 move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
3588 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3589 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3590 }
3591 }
3592 });
3593}
3594
3595fn handle_tooltip_mouse_move(
3607 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3608 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3609 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3610 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3611 tooltip_id: Option<TooltipId>,
3612 current_view: EntityId,
3613 phase: DispatchPhase,
3614 show_delay: Duration,
3615 window: &mut Window,
3616 cx: &mut App,
3617) {
3618 enum Action {
3621 None,
3622 CancelShow,
3623 ScheduleShow,
3624 CheckVisible,
3625 }
3626
3627 let action = match active_tooltip.borrow().as_ref() {
3628 None => {
3629 let is_hovered = check_is_hovered(window);
3630 if is_hovered && phase.bubble() {
3631 Action::ScheduleShow
3632 } else {
3633 Action::None
3634 }
3635 }
3636 Some(ActiveTooltip::WaitingForShow { .. }) => {
3637 let is_hovered = check_is_hovered(window);
3638 if is_hovered {
3639 Action::None
3640 } else {
3641 Action::CancelShow
3642 }
3643 }
3644 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3645 if phase.capture()
3646 && !check_is_hovered(window)
3647 && (!*is_hoverable
3648 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3649 {
3650 Action::CheckVisible
3651 } else {
3652 Action::None
3653 }
3654 }
3655 Some(ActiveTooltip::WaitingForHide { .. }) => {
3656 if phase.capture()
3657 && (check_is_hovered(window)
3658 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3659 {
3660 Action::CheckVisible
3661 } else {
3662 Action::None
3663 }
3664 }
3665 };
3666
3667 match action {
3668 Action::None => {}
3669 Action::CancelShow => {
3670 active_tooltip.borrow_mut().take();
3672 }
3673 Action::ScheduleShow => {
3674 let delayed_show_task = window.spawn(cx, {
3675 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3676 let build_tooltip = build_tooltip.clone();
3677 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3678 async move |cx| {
3679 cx.background_executor().timer(show_delay).await;
3680 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3681 return;
3682 };
3683 cx.update(|window, cx| {
3684 let new_tooltip =
3685 build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3686 let weak_active_tooltip = Rc::downgrade(&active_tooltip);
3687 ActiveTooltip::Visible {
3688 tooltip: AnyTooltip {
3689 view,
3690 mouse_position: window.mouse_position(),
3691 check_visible_and_update: Rc::new(
3692 move |tooltip_bounds, window, cx| {
3693 let Some(active_tooltip) =
3694 weak_active_tooltip.upgrade()
3695 else {
3696 return false;
3697 };
3698 handle_tooltip_check_visible_and_update(
3699 &active_tooltip,
3700 tooltip_is_hoverable,
3701 &check_is_hovered_during_prepaint,
3702 tooltip_bounds,
3703 window,
3704 cx,
3705 )
3706 },
3707 ),
3708 },
3709 is_hoverable: tooltip_is_hoverable,
3710 }
3711 });
3712 *active_tooltip.borrow_mut() = new_tooltip;
3713 window.refresh();
3714 })
3715 .ok();
3716 }
3717 });
3718 active_tooltip
3719 .borrow_mut()
3720 .replace(ActiveTooltip::WaitingForShow {
3721 _task: delayed_show_task,
3722 });
3723 }
3724 Action::CheckVisible => cx.notify(current_view),
3725 }
3726}
3727
3728fn handle_tooltip_check_visible_and_update(
3732 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3733 tooltip_is_hoverable: bool,
3734 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3735 tooltip_bounds: Bounds<Pixels>,
3736 window: &mut Window,
3737 cx: &mut App,
3738) -> bool {
3739 enum Action {
3742 None,
3743 Hide,
3744 ScheduleHide(AnyTooltip),
3745 CancelHide(AnyTooltip),
3746 }
3747
3748 let is_hovered = check_is_hovered(window)
3749 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
3750 let action = match active_tooltip.borrow().as_ref() {
3751 Some(ActiveTooltip::Visible { tooltip, .. }) => {
3752 if is_hovered {
3753 Action::None
3754 } else {
3755 if tooltip_is_hoverable {
3756 Action::ScheduleHide(tooltip.clone())
3757 } else {
3758 Action::Hide
3759 }
3760 }
3761 }
3762 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
3763 if is_hovered {
3764 Action::CancelHide(tooltip.clone())
3765 } else {
3766 Action::None
3767 }
3768 }
3769 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
3770 };
3771
3772 match action {
3773 Action::None => {}
3774 Action::Hide => clear_active_tooltip(active_tooltip, window),
3775 Action::ScheduleHide(tooltip) => {
3776 let delayed_hide_task = window.spawn(cx, {
3777 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3778 async move |cx| {
3779 cx.background_executor()
3780 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
3781 .await;
3782 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3783 return;
3784 };
3785 if active_tooltip.borrow_mut().take().is_some() {
3786 cx.update(|window, _cx| window.refresh()).ok();
3787 }
3788 }
3789 });
3790 active_tooltip
3791 .borrow_mut()
3792 .replace(ActiveTooltip::WaitingForHide {
3793 tooltip,
3794 _task: delayed_hide_task,
3795 });
3796 }
3797 Action::CancelHide(tooltip) => {
3798 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
3800 tooltip,
3801 is_hoverable: true,
3802 });
3803 }
3804 }
3805
3806 active_tooltip.borrow().is_some()
3807}
3808
3809#[derive(Default)]
3810pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
3811
3812impl Global for GroupHitboxes {}
3813
3814impl GroupHitboxes {
3815 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
3816 cx.default_global::<Self>()
3817 .0
3818 .get(name)
3819 .and_then(|bounds_stack| bounds_stack.last())
3820 .cloned()
3821 }
3822
3823 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
3824 cx.default_global::<Self>()
3825 .0
3826 .entry(name)
3827 .or_default()
3828 .push(hitbox_id);
3829 }
3830
3831 pub fn pop(name: &SharedString, cx: &mut App) {
3832 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
3833 }
3834}
3835
3836pub struct Stateful<E> {
3838 pub(crate) element: E,
3839}
3840
3841impl<E> Styled for Stateful<E>
3842where
3843 E: Styled,
3844{
3845 fn style(&mut self) -> &mut StyleRefinement {
3846 self.element.style()
3847 }
3848}
3849
3850impl<E> StatefulInteractiveElement for Stateful<E>
3851where
3852 E: Element,
3853 Self: InteractiveElement,
3854{
3855}
3856
3857impl<E> InteractiveElement for Stateful<E>
3858where
3859 E: InteractiveElement,
3860{
3861 fn interactivity(&mut self) -> &mut Interactivity {
3862 self.element.interactivity()
3863 }
3864}
3865
3866impl<E> Element for Stateful<E>
3867where
3868 E: Element,
3869{
3870 type RequestLayoutState = E::RequestLayoutState;
3871 type PrepaintState = E::PrepaintState;
3872
3873 fn id(&self) -> Option<ElementId> {
3874 self.element.id()
3875 }
3876
3877 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3878 self.element.source_location()
3879 }
3880
3881 fn a11y_role(&self) -> Option<accesskit::Role> {
3882 self.element.a11y_role()
3883 }
3884
3885 fn write_a11y_info(&self, node: &mut accesskit::Node) {
3886 self.element.write_a11y_info(node);
3887 }
3888
3889 fn a11y_synthetic_children(
3890 &mut self,
3891 prepaint: &mut Self::PrepaintState,
3892 builder: &mut crate::A11ySubtreeBuilder,
3893 ) {
3894 self.element.a11y_synthetic_children(prepaint, builder);
3895 }
3896
3897 fn request_layout(
3898 &mut self,
3899 id: Option<&GlobalElementId>,
3900 inspector_id: Option<&InspectorElementId>,
3901 window: &mut Window,
3902 cx: &mut App,
3903 ) -> (LayoutId, Self::RequestLayoutState) {
3904 self.element.request_layout(id, inspector_id, window, cx)
3905 }
3906
3907 fn prepaint(
3908 &mut self,
3909 id: Option<&GlobalElementId>,
3910 inspector_id: Option<&InspectorElementId>,
3911 bounds: Bounds<Pixels>,
3912 state: &mut Self::RequestLayoutState,
3913 window: &mut Window,
3914 cx: &mut App,
3915 ) -> E::PrepaintState {
3916 self.element
3917 .prepaint(id, inspector_id, bounds, state, window, cx)
3918 }
3919
3920 fn paint(
3921 &mut self,
3922 id: Option<&GlobalElementId>,
3923 inspector_id: Option<&InspectorElementId>,
3924 bounds: Bounds<Pixels>,
3925 request_layout: &mut Self::RequestLayoutState,
3926 prepaint: &mut Self::PrepaintState,
3927 window: &mut Window,
3928 cx: &mut App,
3929 ) {
3930 self.element.paint(
3931 id,
3932 inspector_id,
3933 bounds,
3934 request_layout,
3935 prepaint,
3936 window,
3937 cx,
3938 );
3939 }
3940}
3941
3942impl<E> IntoElement for Stateful<E>
3943where
3944 E: Element,
3945{
3946 type Element = Self;
3947
3948 fn into_element(self) -> Self::Element {
3949 self
3950 }
3951}
3952
3953impl<E> ParentElement for Stateful<E>
3954where
3955 E: ParentElement,
3956{
3957 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
3958 self.element.extend(elements)
3959 }
3960}
3961
3962#[derive(Clone)]
3965pub struct ScrollAnchor {
3966 handle: ScrollHandle,
3967 last_origin: Rc<RefCell<Point<Pixels>>>,
3968}
3969
3970impl ScrollAnchor {
3971 pub fn for_handle(handle: ScrollHandle) -> Self {
3973 Self {
3974 handle,
3975 last_origin: Default::default(),
3976 }
3977 }
3978 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
3980 let this = self.clone();
3981
3982 window.on_next_frame(move |_, _| {
3983 let viewport_bounds = this.handle.bounds();
3984 let self_bounds = *this.last_origin.borrow();
3985 this.handle.set_offset(viewport_bounds.origin - self_bounds);
3986 });
3987 }
3988}
3989
3990#[derive(Default, Debug)]
3991struct ScrollHandleState {
3992 offset: Rc<RefCell<Point<Pixels>>>,
3993 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
3994 bounds: Bounds<Pixels>,
3995 max_offset: Point<Pixels>,
3996 child_bounds: Vec<Bounds<Pixels>>,
3997 scroll_to_bottom: bool,
3998 overflow: Point<Overflow>,
3999 active_item: Option<ScrollActiveItem>,
4000}
4001
4002#[derive(Default, Debug, Clone, Copy)]
4003struct ScrollActiveItem {
4004 index: usize,
4005 strategy: ScrollStrategy,
4006}
4007
4008#[derive(Default, Debug, Clone, Copy)]
4009enum ScrollStrategy {
4010 #[default]
4011 FirstVisible,
4012 Top,
4013}
4014
4015#[derive(Clone, Debug)]
4019pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4020
4021impl Default for ScrollHandle {
4022 fn default() -> Self {
4023 Self::new()
4024 }
4025}
4026
4027impl ScrollHandle {
4028 pub fn new() -> Self {
4030 Self(Rc::default())
4031 }
4032
4033 pub fn offset(&self) -> Point<Pixels> {
4035 *self.0.borrow().offset.borrow()
4036 }
4037
4038 pub fn max_offset(&self) -> Point<Pixels> {
4040 self.0.borrow().max_offset
4041 }
4042
4043 pub fn top_item(&self) -> usize {
4045 let state = self.0.borrow();
4046 let top = state.bounds.top() - state.offset.borrow().y;
4047
4048 match state.child_bounds.binary_search_by(|bounds| {
4049 if top < bounds.top() {
4050 Ordering::Greater
4051 } else if top > bounds.bottom() {
4052 Ordering::Less
4053 } else {
4054 Ordering::Equal
4055 }
4056 }) {
4057 Ok(ix) => ix,
4058 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4059 }
4060 }
4061
4062 pub fn bottom_item(&self) -> usize {
4064 let state = self.0.borrow();
4065 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4066
4067 match state.child_bounds.binary_search_by(|bounds| {
4068 if bottom < bounds.top() {
4069 Ordering::Greater
4070 } else if bottom > bounds.bottom() {
4071 Ordering::Less
4072 } else {
4073 Ordering::Equal
4074 }
4075 }) {
4076 Ok(ix) => ix,
4077 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4078 }
4079 }
4080
4081 pub fn bounds(&self) -> Bounds<Pixels> {
4083 self.0.borrow().bounds
4084 }
4085
4086 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4088 self.0.borrow().child_bounds.get(ix).cloned()
4089 }
4090
4091 pub fn scroll_to_item(&self, ix: usize) {
4093 let mut state = self.0.borrow_mut();
4094 state.active_item = Some(ScrollActiveItem {
4095 index: ix,
4096 strategy: ScrollStrategy::default(),
4097 });
4098 }
4099
4100 pub fn scroll_to_top_of_item(&self, ix: usize) {
4103 let mut state = self.0.borrow_mut();
4104 state.active_item = Some(ScrollActiveItem {
4105 index: ix,
4106 strategy: ScrollStrategy::Top,
4107 });
4108 }
4109
4110 fn scroll_to_active_item(&self) {
4114 let mut state = self.0.borrow_mut();
4115
4116 let Some(active_item) = state.active_item else {
4117 return;
4118 };
4119
4120 let active_item = match state.child_bounds.get(active_item.index) {
4121 Some(bounds) => {
4122 let mut scroll_offset = state.offset.borrow_mut();
4123
4124 match active_item.strategy {
4125 ScrollStrategy::FirstVisible => {
4126 if state.overflow.y == Overflow::Scroll {
4127 let child_height = bounds.size.height;
4128 let viewport_height = state.bounds.size.height;
4129 if child_height > viewport_height {
4130 scroll_offset.y = state.bounds.top() - bounds.top();
4131 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4132 scroll_offset.y = state.bounds.top() - bounds.top();
4133 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4134 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4135 }
4136 }
4137 }
4138 ScrollStrategy::Top => {
4139 scroll_offset.y = state.bounds.top() - bounds.top();
4140 }
4141 }
4142
4143 if state.overflow.x == Overflow::Scroll {
4144 let child_width = bounds.size.width;
4145 let viewport_width = state.bounds.size.width;
4146 if child_width > viewport_width {
4147 scroll_offset.x = state.bounds.left() - bounds.left();
4148 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4149 scroll_offset.x = state.bounds.left() - bounds.left();
4150 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4151 scroll_offset.x = state.bounds.right() - bounds.right();
4152 }
4153 }
4154 None
4155 }
4156 None => Some(active_item),
4157 };
4158 state.active_item = active_item;
4159 }
4160
4161 pub fn scroll_to_bottom(&self) {
4163 let mut state = self.0.borrow_mut();
4164 state.scroll_to_bottom = true;
4165 }
4166
4167 pub fn set_offset(&self, mut position: Point<Pixels>) {
4171 let state = self.0.borrow();
4172 *state.offset.borrow_mut() = position;
4173 }
4174
4175 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4177 let ix = self.top_item();
4178 let state = self.0.borrow();
4179
4180 if let Some(child_bounds) = state.child_bounds.get(ix) {
4181 (
4182 ix,
4183 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4184 )
4185 } else {
4186 (ix, px(0.))
4187 }
4188 }
4189
4190 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4192 let ix = self.bottom_item();
4193 let state = self.0.borrow();
4194
4195 if let Some(child_bounds) = state.child_bounds.get(ix) {
4196 (
4197 ix,
4198 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4199 )
4200 } else {
4201 (ix, px(0.))
4202 }
4203 }
4204
4205 pub fn children_count(&self) -> usize {
4207 self.0.borrow().child_bounds.len()
4208 }
4209}
4210
4211#[cfg(test)]
4212mod tests {
4213 use super::*;
4214 use crate::{
4215 AnyWindowHandle, AppContext as _, Context, InputEvent, Keystroke, MouseMoveEvent,
4216 TestAppContext, canvas, util::FluentBuilder as _,
4217 };
4218 use std::{cell::Cell, rc::Weak};
4219
4220 struct GroupHoverTestView {
4221 render_count: Rc<Cell<usize>>,
4222 anonymous_paint_count: Rc<Cell<usize>>,
4223 stateful_width: Rc<Cell<Pixels>>,
4224 }
4225
4226 impl Render for GroupHoverTestView {
4227 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4228 self.render_count.set(self.render_count.get() + 1);
4229 let anonymous_paint_count = self.anonymous_paint_count.clone();
4230 let stateful_width = self.stateful_width.clone();
4231 div().size_full().child(
4232 div()
4233 .ml(px(20.))
4234 .mt(px(20.))
4235 .size(px(50.))
4236 .relative()
4237 .group("hover-group")
4238 .child(
4239 div()
4240 .absolute()
4241 .size_full()
4242 .invisible()
4243 .group_hover("hover-group", |style| style.visible())
4244 .child(canvas(
4245 |_, _, _| {},
4246 move |_, _, _, _| {
4247 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4248 },
4249 )),
4250 )
4251 .child(
4252 div()
4253 .id("stateful-group-hover-target")
4254 .absolute()
4255 .top_0()
4256 .left_0()
4257 .size(px(10.))
4258 .group_hover("hover-group", |style| style.size(px(20.)))
4259 .child(canvas(
4260 move |bounds, _, _| stateful_width.set(bounds.size.width),
4261 |_, _, _, _| {},
4262 )),
4263 ),
4264 )
4265 }
4266 }
4267
4268 #[gpui::test]
4269 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4270 let render_count = Rc::new(Cell::new(0));
4271 let anonymous_paint_count = Rc::new(Cell::new(0));
4272 let stateful_width = Rc::new(Cell::new(px(0.)));
4273 let window = cx.add_window({
4274 let render_count = render_count.clone();
4275 let anonymous_paint_count = anonymous_paint_count.clone();
4276 let stateful_width = stateful_width.clone();
4277 move |_, _| GroupHoverTestView {
4278 render_count,
4279 anonymous_paint_count,
4280 stateful_width,
4281 }
4282 });
4283 let window = AnyWindowHandle::from(window);
4284
4285 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4286 .unwrap();
4287 assert_eq!(anonymous_paint_count.get(), 0);
4288 assert_eq!(stateful_width.get(), px(10.));
4289
4290 let move_mouse = |cx: &mut TestAppContext, position| {
4291 cx.update_window(window, |_, window, cx| {
4292 window.simulate_mouse_move(position, cx)
4293 })
4294 .unwrap();
4295 };
4296
4297 let initial_render_count = render_count.get();
4298 move_mouse(cx, point(px(25.), px(25.)));
4299 assert_eq!(render_count.get(), initial_render_count + 1);
4300 assert_eq!(anonymous_paint_count.get(), 1);
4301 assert_eq!(stateful_width.get(), px(20.));
4302
4303 move_mouse(cx, point(px(30.), px(30.)));
4304 assert_eq!(render_count.get(), initial_render_count + 1);
4305 assert_eq!(anonymous_paint_count.get(), 1);
4306 assert_eq!(stateful_width.get(), px(20.));
4307
4308 move_mouse(cx, point(px(5.), px(5.)));
4309 assert_eq!(render_count.get(), initial_render_count + 2);
4310 assert_eq!(anonymous_paint_count.get(), 1);
4311 assert_eq!(stateful_width.get(), px(10.));
4312
4313 move_mouse(cx, point(px(10.), px(10.)));
4314 assert_eq!(render_count.get(), initial_render_count + 2);
4315 assert_eq!(anonymous_paint_count.get(), 1);
4316 assert_eq!(stateful_width.get(), px(10.));
4317 }
4318
4319 struct TestTooltipView;
4320
4321 impl Render for TestTooltipView {
4322 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4323 div().w(px(20.)).h(px(20.)).child("tooltip")
4324 }
4325 }
4326
4327 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4328
4329 struct TooltipCaptureElement {
4330 child: AnyElement,
4331 captured_active_tooltip: CapturedActiveTooltip,
4332 }
4333
4334 impl IntoElement for TooltipCaptureElement {
4335 type Element = Self;
4336
4337 fn into_element(self) -> Self::Element {
4338 self
4339 }
4340 }
4341
4342 impl Element for TooltipCaptureElement {
4343 type RequestLayoutState = ();
4344 type PrepaintState = ();
4345
4346 fn id(&self) -> Option<ElementId> {
4347 None
4348 }
4349
4350 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4351 None
4352 }
4353
4354 fn request_layout(
4355 &mut self,
4356 _id: Option<&GlobalElementId>,
4357 _inspector_id: Option<&InspectorElementId>,
4358 window: &mut Window,
4359 cx: &mut App,
4360 ) -> (LayoutId, Self::RequestLayoutState) {
4361 (self.child.request_layout(window, cx), ())
4362 }
4363
4364 fn prepaint(
4365 &mut self,
4366 _id: Option<&GlobalElementId>,
4367 _inspector_id: Option<&InspectorElementId>,
4368 _bounds: Bounds<Pixels>,
4369 _request_layout: &mut Self::RequestLayoutState,
4370 window: &mut Window,
4371 cx: &mut App,
4372 ) -> Self::PrepaintState {
4373 self.child.prepaint(window, cx);
4374 }
4375
4376 fn paint(
4377 &mut self,
4378 _id: Option<&GlobalElementId>,
4379 _inspector_id: Option<&InspectorElementId>,
4380 _bounds: Bounds<Pixels>,
4381 _request_layout: &mut Self::RequestLayoutState,
4382 _prepaint: &mut Self::PrepaintState,
4383 window: &mut Window,
4384 cx: &mut App,
4385 ) {
4386 self.child.paint(window, cx);
4387 window.with_global_id("target".into(), |global_id, window| {
4388 window.with_element_state::<InteractiveElementState, _>(
4389 global_id,
4390 |state, _window| {
4391 let state = state.unwrap();
4392 *self.captured_active_tooltip.borrow_mut() =
4393 state.active_tooltip.as_ref().map(Rc::downgrade);
4394 ((), state)
4395 },
4396 )
4397 });
4398 }
4399 }
4400
4401 struct TooltipOwner {
4402 captured_active_tooltip: CapturedActiveTooltip,
4403 show_delay_override: Option<Duration>,
4404 }
4405
4406 impl Render for TooltipOwner {
4407 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4408 TooltipCaptureElement {
4409 child: div()
4410 .size_full()
4411 .child(
4412 div()
4413 .id("target")
4414 .w(px(50.))
4415 .h(px(50.))
4416 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4417 .when_some(self.show_delay_override, |this, delay| {
4418 this.tooltip_show_delay(delay)
4419 }),
4420 )
4421 .into_any_element(),
4422 captured_active_tooltip: self.captured_active_tooltip.clone(),
4423 }
4424 }
4425 }
4426
4427 #[test]
4428 fn scroll_handle_aligns_wide_children_to_left_edge() {
4429 let handle = ScrollHandle::new();
4430 {
4431 let mut state = handle.0.borrow_mut();
4432 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4433 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4434 state.overflow.x = Overflow::Scroll;
4435 state.active_item = Some(ScrollActiveItem {
4436 index: 0,
4437 strategy: ScrollStrategy::default(),
4438 });
4439 }
4440
4441 handle.scroll_to_active_item();
4442
4443 assert_eq!(handle.offset().x, px(-25.));
4444 }
4445
4446 #[test]
4447 fn scroll_handle_aligns_tall_children_to_top_edge() {
4448 let handle = ScrollHandle::new();
4449 {
4450 let mut state = handle.0.borrow_mut();
4451 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4452 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4453 state.overflow.y = Overflow::Scroll;
4454 state.active_item = Some(ScrollActiveItem {
4455 index: 0,
4456 strategy: ScrollStrategy::default(),
4457 });
4458 }
4459
4460 handle.scroll_to_active_item();
4461
4462 assert_eq!(handle.offset().y, px(-25.));
4463 }
4464
4465 fn setup_tooltip_owner_test(
4466 show_delay_override: Option<Duration>,
4467 ) -> (
4468 TestAppContext,
4469 crate::AnyWindowHandle,
4470 CapturedActiveTooltip,
4471 ) {
4472 let mut test_app = TestAppContext::single();
4473 let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
4474 let window = test_app.add_window({
4475 let captured_active_tooltip = captured_active_tooltip.clone();
4476 move |_, _| TooltipOwner {
4477 captured_active_tooltip,
4478 show_delay_override,
4479 }
4480 });
4481 let any_window = window.into();
4482
4483 test_app
4484 .update_window(any_window, |_, window, cx| {
4485 window.draw(cx).clear(cx);
4486 })
4487 .unwrap();
4488
4489 test_app
4490 .update_window(any_window, |_, window, cx| {
4491 window.dispatch_event(
4492 MouseMoveEvent {
4493 position: point(px(10.), px(10.)),
4494 modifiers: Default::default(),
4495 pressed_button: None,
4496 }
4497 .to_platform_input(),
4498 cx,
4499 );
4500 })
4501 .unwrap();
4502
4503 test_app
4504 .update_window(any_window, |_, window, cx| {
4505 window.draw(cx).clear(cx);
4506 })
4507 .unwrap();
4508
4509 (test_app, any_window, captured_active_tooltip)
4510 }
4511
4512 #[test]
4513 fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
4514 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4515
4516 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4517 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4518 assert!(matches!(
4519 active_tooltip.borrow().as_ref(),
4520 Some(ActiveTooltip::WaitingForShow { .. })
4521 ));
4522
4523 test_app
4524 .update_window(any_window, |_, window, _| {
4525 window.remove_window();
4526 })
4527 .unwrap();
4528 test_app.run_until_parked();
4529 drop(active_tooltip);
4530
4531 assert!(weak_active_tooltip.upgrade().is_none());
4532 }
4533
4534 #[test]
4535 fn tooltip_respects_custom_show_delay() {
4536 let extra_delay = Duration::from_secs(1);
4537 let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
4538 let (mut test_app, _any_window, captured_active_tooltip) =
4539 setup_tooltip_owner_test(Some(show_delay_override));
4540
4541 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4542 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4543
4544 test_app
4545 .dispatcher
4546 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4547 test_app.run_until_parked();
4548
4549 assert!(matches!(
4550 active_tooltip.borrow().as_ref(),
4551 Some(ActiveTooltip::WaitingForShow { .. })
4552 ));
4553
4554 test_app.dispatcher.advance_clock(extra_delay);
4555 test_app.run_until_parked();
4556
4557 assert!(matches!(
4558 active_tooltip.borrow().as_ref(),
4559 Some(ActiveTooltip::Visible { .. })
4560 ));
4561 }
4562
4563 #[test]
4564 fn tooltip_is_released_when_its_owner_disappears() {
4565 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4566
4567 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4568 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4569
4570 test_app
4571 .dispatcher
4572 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4573 test_app.run_until_parked();
4574
4575 assert!(matches!(
4576 active_tooltip.borrow().as_ref(),
4577 Some(ActiveTooltip::Visible { .. })
4578 ));
4579
4580 test_app
4581 .update_window(any_window, |_, window, _| {
4582 window.remove_window();
4583 })
4584 .unwrap();
4585 test_app.run_until_parked();
4586 drop(active_tooltip);
4587
4588 assert!(weak_active_tooltip.upgrade().is_none());
4589 }
4590
4591 #[test]
4592 fn tooltip_hides_after_mouse_leaves_origin() {
4593 let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4594
4595 let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4596 let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4597
4598 test_app
4599 .dispatcher
4600 .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4601 test_app.run_until_parked();
4602
4603 assert!(matches!(
4604 active_tooltip.borrow().as_ref(),
4605 Some(ActiveTooltip::Visible { .. })
4606 ));
4607
4608 test_app
4609 .update_window(any_window, |_, window, cx| {
4610 window.dispatch_event(
4611 MouseMoveEvent {
4612 position: point(px(75.), px(75.)),
4613 modifiers: Default::default(),
4614 pressed_button: None,
4615 }
4616 .to_platform_input(),
4617 cx,
4618 );
4619 })
4620 .unwrap();
4621
4622 assert!(active_tooltip.borrow().is_none());
4623 }
4624
4625 struct MouseDownOutOwner {
4626 mouse_down_out_count: Rc<RefCell<usize>>,
4627 }
4628
4629 impl Render for MouseDownOutOwner {
4630 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4631 let mouse_down_out_count = self.mouse_down_out_count.clone();
4632 div()
4633 .size_full()
4634 .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
4635 move |_, _, _| {
4636 *mouse_down_out_count.borrow_mut() += 1;
4637 },
4638 ))
4639 }
4640 }
4641
4642 #[test]
4643 fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
4644 let mut test_app = TestAppContext::single();
4645 let mouse_down_out_count = Rc::new(RefCell::new(0));
4646 let window = test_app.add_window({
4647 let mouse_down_out_count = mouse_down_out_count.clone();
4648 move |_, _| MouseDownOutOwner {
4649 mouse_down_out_count,
4650 }
4651 });
4652 let any_window: AnyWindowHandle = window.into();
4653
4654 fn dispatch_mouse_down_outside_target(
4655 test_app: &mut TestAppContext,
4656 any_window: AnyWindowHandle,
4657 ) {
4658 test_app
4659 .update_window(any_window, |_, window, cx| {
4660 window.dispatch_event(
4661 MouseDownEvent {
4662 position: point(px(75.), px(75.)),
4663 button: MouseButton::Left,
4664 modifiers: Default::default(),
4665 click_count: 1,
4666 first_mouse: false,
4667 }
4668 .to_platform_input(),
4669 cx,
4670 );
4671 })
4672 .unwrap();
4673 }
4674
4675 test_app
4676 .update_window(any_window, |_, window, cx| {
4677 window.draw(cx).clear(cx);
4678 })
4679 .unwrap();
4680
4681 dispatch_mouse_down_outside_target(&mut test_app, any_window);
4682 assert_eq!(
4683 *mouse_down_out_count.borrow(),
4684 1,
4685 "mouse down outside the element should fire mouse-down-out listeners"
4686 );
4687
4688 test_app
4689 .update_window(any_window, |_, window, cx| {
4690 cx.set_prompt_builder(crate::fallback_prompt_renderer);
4691 let _receiver =
4692 window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
4693 assert!(window.has_active_prompt());
4694 window.draw(cx).clear(cx);
4695 })
4696 .unwrap();
4697
4698 dispatch_mouse_down_outside_target(&mut test_app, any_window);
4699 assert_eq!(
4700 *mouse_down_out_count.borrow(),
4701 1,
4702 "mouse down over an active prompt should not fire mouse-down-out listeners"
4703 );
4704 }
4705
4706 #[test]
4707 fn test_write_a11y_info_string_and_numeric_properties() {
4708 let mut interactivity = Interactivity::default();
4709 interactivity.aria.label = Some("Buffer Font Size".into());
4710 interactivity.aria.value = Some("15".into());
4711 interactivity.aria.placeholder = Some("Search".into());
4712 interactivity.aria.numeric_value = Some(15.0);
4713 interactivity.aria.min_numeric_value = Some(6.0);
4714 interactivity.aria.max_numeric_value = Some(72.0);
4715 interactivity.aria.numeric_value_step = Some(1.0);
4716
4717 let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
4718 interactivity.write_a11y_info(&mut node);
4719
4720 assert_eq!(node.label(), Some("Buffer Font Size"));
4721 assert_eq!(node.value(), Some("15"));
4722 assert_eq!(node.placeholder(), Some("Search"));
4723 assert_eq!(node.numeric_value(), Some(15.0));
4724 assert_eq!(node.min_numeric_value(), Some(6.0));
4725 assert_eq!(node.max_numeric_value(), Some(72.0));
4726 assert_eq!(node.numeric_value_step(), Some(1.0));
4727 }
4728
4729 struct KeyboardActivationTest {
4732 focus_a: FocusHandle,
4733 focus_b: FocusHandle,
4734 clicks: Rc<RefCell<Vec<&'static str>>>,
4735 }
4736
4737 impl Render for KeyboardActivationTest {
4738 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4739 let clicks_a = self.clicks.clone();
4740 let clicks_b = self.clicks.clone();
4741 div()
4742 .size_full()
4743 .child(
4744 div()
4745 .id("a")
4746 .w(px(50.))
4747 .h(px(50.))
4748 .track_focus(&self.focus_a)
4749 .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
4750 )
4751 .child(
4752 div()
4753 .id("b")
4754 .w(px(50.))
4755 .h(px(50.))
4756 .track_focus(&self.focus_b)
4757 .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
4758 )
4759 }
4760 }
4761
4762 fn setup_keyboard_activation_test() -> (
4763 TestAppContext,
4764 AnyWindowHandle,
4765 Rc<RefCell<Vec<&'static str>>>,
4766 FocusHandle,
4767 FocusHandle,
4768 ) {
4769 let mut cx = TestAppContext::single();
4770 let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
4771 let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
4772 let window = cx.add_window({
4773 let focus_a = focus_a.clone();
4774 let focus_b = focus_b.clone();
4775 let clicks = clicks.clone();
4776 move |_, _| KeyboardActivationTest {
4777 focus_a,
4778 focus_b,
4779 clicks,
4780 }
4781 });
4782 (cx, window.into(), clicks, focus_a, focus_b)
4783 }
4784
4785 fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
4788 cx.update_window(window, |_, window, cx| window.focus(handle, cx))
4789 .unwrap();
4790 cx.run_until_parked();
4791 cx.update_window(window, |_, window, cx| {
4792 window.draw(cx).clear(cx);
4793 })
4794 .unwrap();
4795 }
4796
4797 fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4798 let keystroke = Keystroke::parse(key).unwrap();
4799 cx.update_window(window, |_, window, cx| {
4800 window.dispatch_event(
4801 KeyDownEvent {
4802 keystroke,
4803 is_held: false,
4804 prefer_character_input: false,
4805 }
4806 .to_platform_input(),
4807 cx,
4808 );
4809 })
4810 .unwrap();
4811 }
4812
4813 fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4814 let keystroke = Keystroke::parse(key).unwrap();
4815 cx.update_window(window, |_, window, cx| {
4816 window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
4817 })
4818 .unwrap();
4819 }
4820
4821 #[test]
4823 fn keyboard_activation_fires_click_on_same_element() {
4824 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4825
4826 focus_and_draw(&mut cx, window, &focus_a);
4827 key_down(&mut cx, window, "enter");
4828 key_up(&mut cx, window, "enter");
4829
4830 assert_eq!(*clicks.borrow(), vec!["a"]);
4831 }
4832
4833 #[test]
4838 fn keyboard_activation_does_not_leak_across_focus_change() {
4839 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
4840
4841 focus_and_draw(&mut cx, window, &focus_a);
4843 key_down(&mut cx, window, "enter");
4844
4845 focus_and_draw(&mut cx, window, &focus_b);
4847 key_up(&mut cx, window, "enter");
4848
4849 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4852 }
4853
4854 #[test]
4859 fn keyboard_activation_does_not_leak_when_focus_returns() {
4860 let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
4861
4862 focus_and_draw(&mut cx, window, &focus_a);
4864 key_down(&mut cx, window, "enter");
4865
4866 focus_and_draw(&mut cx, window, &focus_b);
4869 focus_and_draw(&mut cx, window, &focus_a);
4870 key_up(&mut cx, window, "enter");
4871
4872 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4874 }
4875
4876 #[test]
4881 fn keyboard_activation_cleared_by_intervening_key_release() {
4882 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4883
4884 focus_and_draw(&mut cx, window, &focus_a);
4885 key_down(&mut cx, window, "escape");
4886 key_down(&mut cx, window, "space");
4887 key_up(&mut cx, window, "escape");
4888 key_up(&mut cx, window, "space");
4889
4890 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4891 }
4892
4893 #[test]
4897 fn keyboard_activation_does_not_distinguish_space_and_enter() {
4898 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4899
4900 focus_and_draw(&mut cx, window, &focus_a);
4901 key_down(&mut cx, window, "space");
4902 key_up(&mut cx, window, "enter");
4903
4904 assert_eq!(*clicks.borrow(), vec!["a"]);
4905 }
4906
4907 #[test]
4910 fn keyboard_activation_cleared_by_intervening_keydown() {
4911 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4912
4913 focus_and_draw(&mut cx, window, &focus_a);
4914 key_down(&mut cx, window, "enter");
4915 key_down(&mut cx, window, "a");
4916 key_up(&mut cx, window, "enter");
4917
4918 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4919 }
4920
4921 #[test]
4924 fn keyboard_activation_ignores_modified_keys() {
4925 let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4926
4927 focus_and_draw(&mut cx, window, &focus_a);
4928 key_down(&mut cx, window, "cmd-enter");
4929 key_up(&mut cx, window, "cmd-enter");
4930
4931 assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4932 }
4933
4934 struct TabGroupFocus {
4938 group_a: FocusHandle,
4939 item_a: FocusHandle,
4940 group_b: FocusHandle,
4941 item_b: FocusHandle,
4942 }
4943
4944 impl Render for TabGroupFocus {
4945 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4946 fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
4947 div()
4948 .track_focus(container)
4949 .tab_group()
4950 .child(div().track_focus(item))
4951 }
4952 div()
4953 .child(group(&self.group_a, &self.item_a))
4954 .child(group(&self.group_b, &self.item_b))
4955 }
4956 }
4957
4958 #[test]
4962 fn focus_next_from_tab_group_container_enters_that_group() {
4963 let mut cx = TestAppContext::single();
4964 let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
4965 (
4966 cx.focus_handle(),
4967 cx.focus_handle().tab_stop(true),
4968 cx.focus_handle(),
4969 cx.focus_handle().tab_stop(true),
4970 )
4971 });
4972 let window: AnyWindowHandle = cx
4973 .add_window({
4974 let (group_a, item_a, group_b, item_b) =
4975 (group_a, item_a, group_b.clone(), item_b.clone());
4976 move |_, _| TabGroupFocus {
4977 group_a,
4978 item_a,
4979 group_b,
4980 item_b,
4981 }
4982 })
4983 .into();
4984 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4985 .unwrap();
4986
4987 let focused = cx
4989 .update_window(window, |_, window, cx| {
4990 window.focus(&group_b, cx);
4991 window.focus_next(cx);
4992 window.focused(cx).map(|handle| handle.id)
4993 })
4994 .unwrap();
4995
4996 assert_eq!(focused, Some(item_b.id));
4997 }
4998}