1use crate::{
2 point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext,
3 BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, ElementId, FocusHandle, IntoElement,
4 IsZero, KeyContext, KeyDownEvent, KeyUpEvent, LayoutId, MouseButton, MouseDownEvent,
5 MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point, Render, ScrollWheelEvent,
6 SharedString, Size, StackingOrder, Style, StyleRefinement, Styled, Task, View, Visibility,
7 WindowContext,
8};
9
10use collections::HashMap;
11use refineable::Refineable;
12use smallvec::SmallVec;
13use std::{
14 any::{Any, TypeId},
15 cell::RefCell,
16 cmp::Ordering,
17 fmt::Debug,
18 marker::PhantomData,
19 mem,
20 rc::Rc,
21 time::Duration,
22};
23use taffy::style::Overflow;
24use util::ResultExt;
25
26const DRAG_THRESHOLD: f64 = 2.;
27const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
28
29pub struct GroupStyle {
30 pub group: SharedString,
31 pub style: Box<StyleRefinement>,
32}
33
34pub struct DragMoveEvent<T> {
35 pub event: MouseMoveEvent,
36 pub bounds: Bounds<Pixels>,
37 drag: PhantomData<T>,
38}
39
40impl<T: 'static> DragMoveEvent<T> {
41 pub fn drag<'b>(&self, cx: &'b AppContext) -> &'b T {
42 cx.active_drag
43 .as_ref()
44 .and_then(|drag| drag.value.downcast_ref::<T>())
45 .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
46 }
47}
48
49impl Interactivity {
50 pub fn on_mouse_down(
51 &mut self,
52 button: MouseButton,
53 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
54 ) {
55 self.mouse_down_listeners
56 .push(Box::new(move |event, bounds, phase, cx| {
57 if phase == DispatchPhase::Bubble
58 && event.button == button
59 && bounds.visibly_contains(&event.position, cx)
60 {
61 (listener)(event, cx)
62 }
63 }));
64 }
65
66 pub fn capture_any_mouse_down(
67 &mut self,
68 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
69 ) {
70 self.mouse_down_listeners
71 .push(Box::new(move |event, bounds, phase, cx| {
72 if phase == DispatchPhase::Capture && bounds.visibly_contains(&event.position, cx) {
73 (listener)(event, cx)
74 }
75 }));
76 }
77
78 pub fn on_any_mouse_down(
79 &mut self,
80 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
81 ) {
82 self.mouse_down_listeners
83 .push(Box::new(move |event, bounds, phase, cx| {
84 if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
85 (listener)(event, cx)
86 }
87 }));
88 }
89
90 pub fn on_mouse_up(
91 &mut self,
92 button: MouseButton,
93 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
94 ) {
95 self.mouse_up_listeners
96 .push(Box::new(move |event, bounds, phase, cx| {
97 if phase == DispatchPhase::Bubble
98 && event.button == button
99 && bounds.visibly_contains(&event.position, cx)
100 {
101 (listener)(event, cx)
102 }
103 }));
104 }
105
106 pub fn capture_any_mouse_up(
107 &mut self,
108 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
109 ) {
110 self.mouse_up_listeners
111 .push(Box::new(move |event, bounds, phase, cx| {
112 if phase == DispatchPhase::Capture && bounds.visibly_contains(&event.position, cx) {
113 (listener)(event, cx)
114 }
115 }));
116 }
117
118 pub fn on_any_mouse_up(
119 &mut self,
120 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
121 ) {
122 self.mouse_up_listeners
123 .push(Box::new(move |event, bounds, phase, cx| {
124 if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
125 (listener)(event, cx)
126 }
127 }));
128 }
129
130 pub fn on_mouse_down_out(
131 &mut self,
132 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
133 ) {
134 self.mouse_down_listeners
135 .push(Box::new(move |event, bounds, phase, cx| {
136 if phase == DispatchPhase::Capture && !bounds.visibly_contains(&event.position, cx)
137 {
138 (listener)(event, cx)
139 }
140 }));
141 }
142
143 pub fn on_mouse_up_out(
144 &mut self,
145 button: MouseButton,
146 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
147 ) {
148 self.mouse_up_listeners
149 .push(Box::new(move |event, bounds, phase, cx| {
150 if phase == DispatchPhase::Capture
151 && event.button == button
152 && !bounds.visibly_contains(&event.position, cx)
153 {
154 (listener)(event, cx);
155 }
156 }));
157 }
158
159 pub fn on_mouse_move(
160 &mut self,
161 listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static,
162 ) {
163 self.mouse_move_listeners
164 .push(Box::new(move |event, bounds, phase, cx| {
165 if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
166 (listener)(event, cx);
167 }
168 }));
169 }
170
171 pub fn on_drag_move<T>(
172 &mut self,
173 listener: impl Fn(&DragMoveEvent<T>, &mut WindowContext) + 'static,
174 ) where
175 T: 'static,
176 {
177 self.mouse_move_listeners
178 .push(Box::new(move |event, bounds, phase, cx| {
179 if phase == DispatchPhase::Capture
180 && cx
181 .active_drag
182 .as_ref()
183 .is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::<T>())
184 {
185 (listener)(
186 &DragMoveEvent {
187 event: event.clone(),
188 bounds: bounds.bounds,
189 drag: PhantomData,
190 },
191 cx,
192 );
193 }
194 }));
195 }
196
197 pub fn on_scroll_wheel(
198 &mut self,
199 listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static,
200 ) {
201 self.scroll_wheel_listeners
202 .push(Box::new(move |event, bounds, phase, cx| {
203 if phase == DispatchPhase::Bubble && bounds.visibly_contains(&event.position, cx) {
204 (listener)(event, cx);
205 }
206 }));
207 }
208
209 pub fn capture_action<A: Action>(
210 &mut self,
211 listener: impl Fn(&A, &mut WindowContext) + 'static,
212 ) {
213 self.action_listeners.push((
214 TypeId::of::<A>(),
215 Box::new(move |action, phase, cx| {
216 let action = action.downcast_ref().unwrap();
217 if phase == DispatchPhase::Capture {
218 (listener)(action, cx)
219 }
220 }),
221 ));
222 }
223
224 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) {
225 self.action_listeners.push((
226 TypeId::of::<A>(),
227 Box::new(move |action, phase, cx| {
228 let action = action.downcast_ref().unwrap();
229 if phase == DispatchPhase::Bubble {
230 (listener)(action, cx)
231 }
232 }),
233 ));
234 }
235
236 pub fn on_boxed_action(
237 &mut self,
238 action: &dyn Action,
239 listener: impl Fn(&Box<dyn Action>, &mut WindowContext) + 'static,
240 ) {
241 let action = action.boxed_clone();
242 self.action_listeners.push((
243 (*action).type_id(),
244 Box::new(move |_, phase, cx| {
245 if phase == DispatchPhase::Bubble {
246 (listener)(&action, cx)
247 }
248 }),
249 ));
250 }
251
252 pub fn on_key_down(&mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static) {
253 self.key_down_listeners
254 .push(Box::new(move |event, phase, cx| {
255 if phase == DispatchPhase::Bubble {
256 (listener)(event, cx)
257 }
258 }));
259 }
260
261 pub fn capture_key_down(
262 &mut self,
263 listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static,
264 ) {
265 self.key_down_listeners
266 .push(Box::new(move |event, phase, cx| {
267 if phase == DispatchPhase::Capture {
268 listener(event, cx)
269 }
270 }));
271 }
272
273 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) {
274 self.key_up_listeners
275 .push(Box::new(move |event, phase, cx| {
276 if phase == DispatchPhase::Bubble {
277 listener(event, cx)
278 }
279 }));
280 }
281
282 pub fn capture_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) {
283 self.key_up_listeners
284 .push(Box::new(move |event, phase, cx| {
285 if phase == DispatchPhase::Capture {
286 listener(event, cx)
287 }
288 }));
289 }
290
291 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut WindowContext) + 'static) {
292 self.drop_listeners.push((
293 TypeId::of::<T>(),
294 Box::new(move |dragged_value, cx| {
295 listener(dragged_value.downcast_ref().unwrap(), cx);
296 }),
297 ));
298 }
299
300 pub fn can_drop(&mut self, predicate: impl Fn(&dyn Any, &mut WindowContext) -> bool + 'static) {
301 self.can_drop_predicate = Some(Box::new(predicate));
302 }
303
304 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static)
305 where
306 Self: Sized,
307 {
308 self.click_listeners
309 .push(Box::new(move |event, cx| listener(event, cx)));
310 }
311
312 pub fn on_drag<T, W>(
313 &mut self,
314 value: T,
315 constructor: impl Fn(&T, &mut WindowContext) -> View<W> + 'static,
316 ) where
317 Self: Sized,
318 T: 'static,
319 W: 'static + Render,
320 {
321 debug_assert!(
322 self.drag_listener.is_none(),
323 "calling on_drag more than once on the same element is not supported"
324 );
325 self.drag_listener = Some((
326 Box::new(value),
327 Box::new(move |value, cx| constructor(value.downcast_ref().unwrap(), cx).into()),
328 ));
329 }
330
331 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut WindowContext) + 'static)
332 where
333 Self: Sized,
334 {
335 debug_assert!(
336 self.hover_listener.is_none(),
337 "calling on_hover more than once on the same element is not supported"
338 );
339 self.hover_listener = Some(Box::new(listener));
340 }
341
342 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static)
343 where
344 Self: Sized,
345 {
346 debug_assert!(
347 self.tooltip_builder.is_none(),
348 "calling tooltip more than once on the same element is not supported"
349 );
350 self.tooltip_builder = Some(Rc::new(build_tooltip));
351 }
352
353 pub fn block_mouse(&mut self) {
354 self.block_mouse = true;
355 }
356}
357
358pub trait InteractiveElement: Sized {
359 fn interactivity(&mut self) -> &mut Interactivity;
360
361 fn group(mut self, group: impl Into<SharedString>) -> Self {
362 self.interactivity().group = Some(group.into());
363 self
364 }
365
366 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
367 self.interactivity().element_id = Some(id.into());
368
369 Stateful { element: self }
370 }
371
372 fn track_focus(mut self, focus_handle: &FocusHandle) -> Focusable<Self> {
373 self.interactivity().focusable = true;
374 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
375 Focusable { element: self }
376 }
377
378 fn key_context<C, E>(mut self, key_context: C) -> Self
379 where
380 C: TryInto<KeyContext, Error = E>,
381 E: Debug,
382 {
383 if let Some(key_context) = key_context.try_into().log_err() {
384 self.interactivity().key_context = Some(key_context);
385 }
386 self
387 }
388
389 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
390 debug_assert!(
391 self.interactivity().hover_style.is_none(),
392 "hover style already set"
393 );
394 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
395 self
396 }
397
398 fn group_hover(
399 mut self,
400 group_name: impl Into<SharedString>,
401 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
402 ) -> Self {
403 self.interactivity().group_hover_style = Some(GroupStyle {
404 group: group_name.into(),
405 style: Box::new(f(StyleRefinement::default())),
406 });
407 self
408 }
409
410 fn on_mouse_down(
411 mut self,
412 button: MouseButton,
413 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
414 ) -> Self {
415 self.interactivity().on_mouse_down(button, listener);
416 self
417 }
418
419 #[cfg(any(test, feature = "test-support"))]
420 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
421 self.interactivity().debug_selector = Some(f());
422 self
423 }
424
425 #[cfg(not(any(test, feature = "test-support")))]
426 #[inline]
427 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
428 self
429 }
430
431 fn capture_any_mouse_down(
432 mut self,
433 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
434 ) -> Self {
435 self.interactivity().capture_any_mouse_down(listener);
436 self
437 }
438
439 fn on_any_mouse_down(
440 mut self,
441 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
442 ) -> Self {
443 self.interactivity().on_any_mouse_down(listener);
444 self
445 }
446
447 fn on_mouse_up(
448 mut self,
449 button: MouseButton,
450 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
451 ) -> Self {
452 self.interactivity().on_mouse_up(button, listener);
453 self
454 }
455
456 fn capture_any_mouse_up(
457 mut self,
458 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
459 ) -> Self {
460 self.interactivity().capture_any_mouse_up(listener);
461 self
462 }
463
464 fn on_mouse_down_out(
465 mut self,
466 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
467 ) -> Self {
468 self.interactivity().on_mouse_down_out(listener);
469 self
470 }
471
472 fn on_mouse_up_out(
473 mut self,
474 button: MouseButton,
475 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
476 ) -> Self {
477 self.interactivity().on_mouse_up_out(button, listener);
478 self
479 }
480
481 fn on_mouse_move(
482 mut self,
483 listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static,
484 ) -> Self {
485 self.interactivity().on_mouse_move(listener);
486 self
487 }
488
489 fn on_drag_move<T: 'static>(
490 mut self,
491 listener: impl Fn(&DragMoveEvent<T>, &mut WindowContext) + 'static,
492 ) -> Self
493 where
494 T: 'static,
495 {
496 self.interactivity().on_drag_move(listener);
497 self
498 }
499
500 fn on_scroll_wheel(
501 mut self,
502 listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static,
503 ) -> Self {
504 self.interactivity().on_scroll_wheel(listener);
505 self
506 }
507
508 /// Capture the given action, before normal action dispatch can fire
509 fn capture_action<A: Action>(
510 mut self,
511 listener: impl Fn(&A, &mut WindowContext) + 'static,
512 ) -> Self {
513 self.interactivity().capture_action(listener);
514 self
515 }
516
517 /// Add a listener for the given action, fires during the bubble event phase
518 fn on_action<A: Action>(mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) -> Self {
519 self.interactivity().on_action(listener);
520 self
521 }
522
523 fn on_boxed_action(
524 mut self,
525 action: &dyn Action,
526 listener: impl Fn(&Box<dyn Action>, &mut WindowContext) + 'static,
527 ) -> Self {
528 self.interactivity().on_boxed_action(action, listener);
529 self
530 }
531
532 fn on_key_down(
533 mut self,
534 listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static,
535 ) -> Self {
536 self.interactivity().on_key_down(listener);
537 self
538 }
539
540 fn capture_key_down(
541 mut self,
542 listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static,
543 ) -> Self {
544 self.interactivity().capture_key_down(listener);
545 self
546 }
547
548 fn on_key_up(mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) -> Self {
549 self.interactivity().on_key_up(listener);
550 self
551 }
552
553 fn capture_key_up(
554 mut self,
555 listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static,
556 ) -> Self {
557 self.interactivity().capture_key_up(listener);
558 self
559 }
560
561 fn drag_over<S: 'static>(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
562 self.interactivity()
563 .drag_over_styles
564 .push((TypeId::of::<S>(), f(StyleRefinement::default())));
565 self
566 }
567
568 fn group_drag_over<S: 'static>(
569 mut self,
570 group_name: impl Into<SharedString>,
571 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
572 ) -> Self {
573 self.interactivity().group_drag_over_styles.push((
574 TypeId::of::<S>(),
575 GroupStyle {
576 group: group_name.into(),
577 style: Box::new(f(StyleRefinement::default())),
578 },
579 ));
580 self
581 }
582
583 fn on_drop<T: 'static>(mut self, listener: impl Fn(&T, &mut WindowContext) + 'static) -> Self {
584 self.interactivity().on_drop(listener);
585 self
586 }
587
588 fn can_drop(
589 mut self,
590 predicate: impl Fn(&dyn Any, &mut WindowContext) -> bool + 'static,
591 ) -> Self {
592 self.interactivity().can_drop(predicate);
593 self
594 }
595
596 fn block_mouse(mut self) -> Self {
597 self.interactivity().block_mouse();
598 self
599 }
600}
601
602pub trait StatefulInteractiveElement: InteractiveElement {
603 fn focusable(mut self) -> Focusable<Self> {
604 self.interactivity().focusable = true;
605 Focusable { element: self }
606 }
607
608 fn overflow_scroll(mut self) -> Self {
609 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
610 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
611 self
612 }
613
614 fn overflow_x_scroll(mut self) -> Self {
615 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
616 self
617 }
618
619 fn overflow_y_scroll(mut self) -> Self {
620 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
621 self
622 }
623
624 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
625 self.interactivity().scroll_handle = Some(scroll_handle.clone());
626 self
627 }
628
629 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
630 where
631 Self: Sized,
632 {
633 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
634 self
635 }
636
637 fn group_active(
638 mut self,
639 group_name: impl Into<SharedString>,
640 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
641 ) -> Self
642 where
643 Self: Sized,
644 {
645 self.interactivity().group_active_style = Some(GroupStyle {
646 group: group_name.into(),
647 style: Box::new(f(StyleRefinement::default())),
648 });
649 self
650 }
651
652 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static) -> Self
653 where
654 Self: Sized,
655 {
656 self.interactivity().on_click(listener);
657 self
658 }
659
660 fn on_drag<T, W>(
661 mut self,
662 value: T,
663 constructor: impl Fn(&T, &mut WindowContext) -> View<W> + 'static,
664 ) -> Self
665 where
666 Self: Sized,
667 T: 'static,
668 W: 'static + Render,
669 {
670 self.interactivity().on_drag(value, constructor);
671 self
672 }
673
674 fn on_hover(mut self, listener: impl Fn(&bool, &mut WindowContext) + 'static) -> Self
675 where
676 Self: Sized,
677 {
678 self.interactivity().on_hover(listener);
679 self
680 }
681
682 fn tooltip(mut self, build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self
683 where
684 Self: Sized,
685 {
686 self.interactivity().tooltip(build_tooltip);
687 self
688 }
689}
690
691pub trait FocusableElement: InteractiveElement {
692 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
693 where
694 Self: Sized,
695 {
696 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
697 self
698 }
699
700 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
701 where
702 Self: Sized,
703 {
704 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
705 self
706 }
707}
708
709pub type MouseDownListener =
710 Box<dyn Fn(&MouseDownEvent, &InteractiveBounds, DispatchPhase, &mut WindowContext) + 'static>;
711pub type MouseUpListener =
712 Box<dyn Fn(&MouseUpEvent, &InteractiveBounds, DispatchPhase, &mut WindowContext) + 'static>;
713
714pub type MouseMoveListener =
715 Box<dyn Fn(&MouseMoveEvent, &InteractiveBounds, DispatchPhase, &mut WindowContext) + 'static>;
716
717pub type ScrollWheelListener =
718 Box<dyn Fn(&ScrollWheelEvent, &InteractiveBounds, DispatchPhase, &mut WindowContext) + 'static>;
719
720pub type ClickListener = Box<dyn Fn(&ClickEvent, &mut WindowContext) + 'static>;
721
722pub type DragListener = Box<dyn Fn(&dyn Any, &mut WindowContext) -> AnyView + 'static>;
723
724type DropListener = Box<dyn Fn(&dyn Any, &mut WindowContext) + 'static>;
725
726type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut WindowContext) -> bool + 'static>;
727
728pub type TooltipBuilder = Rc<dyn Fn(&mut WindowContext) -> AnyView + 'static>;
729
730pub type KeyDownListener = Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut WindowContext) + 'static>;
731
732pub type KeyUpListener = Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut WindowContext) + 'static>;
733
734pub type DragEventListener = Box<dyn Fn(&MouseMoveEvent, &mut WindowContext) + 'static>;
735
736pub type ActionListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
737
738#[track_caller]
739pub fn div() -> Div {
740 #[cfg(debug_assertions)]
741 let interactivity = {
742 let mut interactivity = Interactivity::default();
743 interactivity.location = Some(*core::panic::Location::caller());
744 interactivity
745 };
746
747 #[cfg(not(debug_assertions))]
748 let interactivity = Interactivity::default();
749
750 Div {
751 interactivity,
752 children: SmallVec::default(),
753 }
754}
755
756pub struct Div {
757 interactivity: Interactivity,
758 children: SmallVec<[AnyElement; 2]>,
759}
760
761impl Styled for Div {
762 fn style(&mut self) -> &mut StyleRefinement {
763 &mut self.interactivity.base_style
764 }
765}
766
767impl InteractiveElement for Div {
768 fn interactivity(&mut self) -> &mut Interactivity {
769 &mut self.interactivity
770 }
771}
772
773impl ParentElement for Div {
774 fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
775 &mut self.children
776 }
777}
778
779impl Element for Div {
780 type State = DivState;
781
782 fn request_layout(
783 &mut self,
784 element_state: Option<Self::State>,
785 cx: &mut WindowContext,
786 ) -> (LayoutId, Self::State) {
787 let mut child_layout_ids = SmallVec::new();
788 let (layout_id, interactive_state) = self.interactivity.layout(
789 element_state.map(|s| s.interactive_state),
790 cx,
791 |style, cx| {
792 cx.with_text_style(style.text_style().cloned(), |cx| {
793 child_layout_ids = self
794 .children
795 .iter_mut()
796 .map(|child| child.request_layout(cx))
797 .collect::<SmallVec<_>>();
798 cx.request_layout(&style, child_layout_ids.iter().copied())
799 })
800 },
801 );
802 (
803 layout_id,
804 DivState {
805 interactive_state,
806 child_layout_ids,
807 },
808 )
809 }
810
811 fn paint(
812 &mut self,
813 bounds: Bounds<Pixels>,
814 element_state: &mut Self::State,
815 cx: &mut WindowContext,
816 ) {
817 let mut child_min = point(Pixels::MAX, Pixels::MAX);
818 let mut child_max = Point::default();
819 let content_size = if element_state.child_layout_ids.is_empty() {
820 bounds.size
821 } else if let Some(scroll_handle) = self.interactivity.scroll_handle.as_ref() {
822 let mut state = scroll_handle.0.borrow_mut();
823 state.child_bounds = Vec::with_capacity(element_state.child_layout_ids.len());
824 state.bounds = bounds;
825 let requested = state.requested_scroll_top.take();
826
827 for (ix, child_layout_id) in element_state.child_layout_ids.iter().enumerate() {
828 let child_bounds = cx.layout_bounds(*child_layout_id);
829 child_min = child_min.min(&child_bounds.origin);
830 child_max = child_max.max(&child_bounds.lower_right());
831 state.child_bounds.push(child_bounds);
832
833 if let Some(requested) = requested.as_ref() {
834 if requested.0 == ix {
835 *state.offset.borrow_mut() =
836 bounds.origin - (child_bounds.origin - point(px(0.), requested.1));
837 }
838 }
839 }
840 (child_max - child_min).into()
841 } else {
842 for child_layout_id in &element_state.child_layout_ids {
843 let child_bounds = cx.layout_bounds(*child_layout_id);
844 child_min = child_min.min(&child_bounds.origin);
845 child_max = child_max.max(&child_bounds.lower_right());
846 }
847 (child_max - child_min).into()
848 };
849
850 self.interactivity.paint(
851 bounds,
852 content_size,
853 &mut element_state.interactive_state,
854 cx,
855 |_style, scroll_offset, cx| {
856 cx.with_element_offset(scroll_offset, |cx| {
857 for child in &mut self.children {
858 child.paint(cx);
859 }
860 })
861 },
862 );
863 }
864}
865
866impl IntoElement for Div {
867 type Element = Self;
868
869 fn element_id(&self) -> Option<ElementId> {
870 self.interactivity.element_id.clone()
871 }
872
873 fn into_element(self) -> Self::Element {
874 self
875 }
876}
877
878pub struct DivState {
879 child_layout_ids: SmallVec<[LayoutId; 2]>,
880 interactive_state: InteractiveElementState,
881}
882
883impl DivState {
884 pub fn is_active(&self) -> bool {
885 self.interactive_state
886 .pending_mouse_down
887 .as_ref()
888 .map_or(false, |pending| pending.borrow().is_some())
889 }
890}
891
892#[derive(Default)]
893pub struct Interactivity {
894 pub element_id: Option<ElementId>,
895 pub key_context: Option<KeyContext>,
896 pub focusable: bool,
897 pub tracked_focus_handle: Option<FocusHandle>,
898 pub scroll_handle: Option<ScrollHandle>,
899 pub group: Option<SharedString>,
900 pub base_style: Box<StyleRefinement>,
901 pub focus_style: Option<Box<StyleRefinement>>,
902 pub in_focus_style: Option<Box<StyleRefinement>>,
903 pub hover_style: Option<Box<StyleRefinement>>,
904 pub group_hover_style: Option<GroupStyle>,
905 pub active_style: Option<Box<StyleRefinement>>,
906 pub group_active_style: Option<GroupStyle>,
907 pub drag_over_styles: Vec<(TypeId, StyleRefinement)>,
908 pub group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
909 pub mouse_down_listeners: Vec<MouseDownListener>,
910 pub mouse_up_listeners: Vec<MouseUpListener>,
911 pub mouse_move_listeners: Vec<MouseMoveListener>,
912 pub scroll_wheel_listeners: Vec<ScrollWheelListener>,
913 pub key_down_listeners: Vec<KeyDownListener>,
914 pub key_up_listeners: Vec<KeyUpListener>,
915 pub action_listeners: Vec<(TypeId, ActionListener)>,
916 pub drop_listeners: Vec<(TypeId, DropListener)>,
917 pub can_drop_predicate: Option<CanDropPredicate>,
918 pub click_listeners: Vec<ClickListener>,
919 pub drag_listener: Option<(Box<dyn Any>, DragListener)>,
920 pub hover_listener: Option<Box<dyn Fn(&bool, &mut WindowContext)>>,
921 pub tooltip_builder: Option<TooltipBuilder>,
922 pub block_mouse: bool,
923
924 #[cfg(debug_assertions)]
925 pub location: Option<core::panic::Location<'static>>,
926
927 #[cfg(any(test, feature = "test-support"))]
928 pub debug_selector: Option<String>,
929}
930
931#[derive(Clone, Debug)]
932pub struct InteractiveBounds {
933 pub bounds: Bounds<Pixels>,
934 pub stacking_order: StackingOrder,
935}
936
937impl InteractiveBounds {
938 pub fn visibly_contains(&self, point: &Point<Pixels>, cx: &WindowContext) -> bool {
939 self.bounds.contains(point) && cx.was_top_layer(point, &self.stacking_order)
940 }
941
942 pub fn drag_target_contains(&self, point: &Point<Pixels>, cx: &WindowContext) -> bool {
943 self.bounds.contains(point)
944 && cx.was_top_layer_under_active_drag(point, &self.stacking_order)
945 }
946}
947
948impl Interactivity {
949 pub fn layout(
950 &mut self,
951 element_state: Option<InteractiveElementState>,
952 cx: &mut WindowContext,
953 f: impl FnOnce(Style, &mut WindowContext) -> LayoutId,
954 ) -> (LayoutId, InteractiveElementState) {
955 let mut element_state = element_state.unwrap_or_default();
956
957 if cx.has_active_drag() {
958 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
959 *pending_mouse_down.borrow_mut() = None;
960 }
961 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
962 *clicked_state.borrow_mut() = ElementClickedState::default();
963 }
964 }
965
966 // Ensure we store a focus handle in our element state if we're focusable.
967 // If there's an explicit focus handle we're tracking, use that. Otherwise
968 // create a new handle and store it in the element state, which lives for as
969 // as frames contain an element with this id.
970 if self.focusable {
971 element_state.focus_handle.get_or_insert_with(|| {
972 self.tracked_focus_handle
973 .clone()
974 .unwrap_or_else(|| cx.focus_handle())
975 });
976 }
977
978 if let Some(scroll_handle) = self.scroll_handle.as_ref() {
979 element_state.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
980 }
981
982 let style = self.compute_style(None, &mut element_state, cx);
983 let layout_id = f(style, cx);
984 (layout_id, element_state)
985 }
986
987 pub fn paint(
988 &mut self,
989 bounds: Bounds<Pixels>,
990 content_size: Size<Pixels>,
991 element_state: &mut InteractiveElementState,
992 cx: &mut WindowContext,
993 f: impl FnOnce(&Style, Point<Pixels>, &mut WindowContext),
994 ) {
995 let style = self.compute_style(Some(bounds), element_state, cx);
996 let z_index = style.z_index.unwrap_or(0);
997
998 #[cfg(any(feature = "test-support", test))]
999 if let Some(debug_selector) = &self.debug_selector {
1000 cx.window
1001 .next_frame
1002 .debug_bounds
1003 .insert(debug_selector.clone(), bounds);
1004 }
1005
1006 let paint_hover_group_handler = |cx: &mut WindowContext| {
1007 let hover_group_bounds = self
1008 .group_hover_style
1009 .as_ref()
1010 .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
1011
1012 if let Some(group_bounds) = hover_group_bounds {
1013 let hovered = group_bounds.contains(&cx.mouse_position());
1014 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1015 if phase == DispatchPhase::Capture
1016 && group_bounds.contains(&event.position) != hovered
1017 {
1018 cx.refresh();
1019 }
1020 });
1021 }
1022 };
1023
1024 if style.visibility == Visibility::Hidden {
1025 cx.with_z_index(z_index, |cx| paint_hover_group_handler(cx));
1026 return;
1027 }
1028
1029 cx.with_z_index(z_index, |cx| {
1030 style.paint(bounds, cx, |cx| {
1031 cx.with_text_style(style.text_style().cloned(), |cx| {
1032 cx.with_content_mask(style.overflow_mask(bounds, cx.rem_size()), |cx| {
1033 #[cfg(debug_assertions)]
1034 if self.element_id.is_some()
1035 && (style.debug
1036 || style.debug_below
1037 || cx.has_global::<crate::DebugBelow>())
1038 && bounds.contains(&cx.mouse_position())
1039 {
1040 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
1041 let element_id = format!("{:?}", self.element_id.as_ref().unwrap());
1042 let str_len = element_id.len();
1043
1044 let render_debug_text = |cx: &mut WindowContext| {
1045 if let Some(text) = cx
1046 .text_system()
1047 .shape_text(
1048 element_id.into(),
1049 FONT_SIZE,
1050 &[cx.text_style().to_run(str_len)],
1051 None,
1052 )
1053 .ok()
1054 .and_then(|mut text| text.pop())
1055 {
1056 text.paint(bounds.origin, FONT_SIZE, cx).ok();
1057
1058 let text_bounds = crate::Bounds {
1059 origin: bounds.origin,
1060 size: text.size(FONT_SIZE),
1061 };
1062 if self.location.is_some()
1063 && text_bounds.contains(&cx.mouse_position())
1064 && cx.modifiers().command
1065 {
1066 let command_held = cx.modifiers().command;
1067 cx.on_key_event({
1068 move |e: &crate::ModifiersChangedEvent, _phase, cx| {
1069 if e.modifiers.command != command_held
1070 && text_bounds.contains(&cx.mouse_position())
1071 {
1072 cx.refresh();
1073 }
1074 }
1075 });
1076
1077 let hovered = bounds.contains(&cx.mouse_position());
1078 cx.on_mouse_event(
1079 move |event: &MouseMoveEvent, phase, cx| {
1080 if phase == DispatchPhase::Capture
1081 && bounds.contains(&event.position) != hovered
1082 {
1083 cx.refresh();
1084 }
1085 },
1086 );
1087
1088 cx.on_mouse_event({
1089 let location = self.location.unwrap();
1090 move |e: &crate::MouseDownEvent, phase, cx| {
1091 if text_bounds.contains(&e.position)
1092 && phase.capture()
1093 {
1094 cx.stop_propagation();
1095 let Ok(dir) = std::env::current_dir() else {
1096 return;
1097 };
1098
1099 eprintln!(
1100 "This element was created at:\n{}:{}:{}",
1101 dir.join(location.file()).to_string_lossy(),
1102 location.line(),
1103 location.column()
1104 );
1105 }
1106 }
1107 });
1108 cx.paint_quad(crate::outline(
1109 crate::Bounds {
1110 origin: bounds.origin
1111 + crate::point(
1112 crate::px(0.),
1113 FONT_SIZE - px(2.),
1114 ),
1115 size: crate::Size {
1116 width: text_bounds.size.width,
1117 height: crate::px(1.),
1118 },
1119 },
1120 crate::red(),
1121 ))
1122 }
1123 }
1124 };
1125
1126 cx.with_z_index(1, |cx| {
1127 cx.with_text_style(
1128 Some(crate::TextStyleRefinement {
1129 color: Some(crate::red()),
1130 line_height: Some(FONT_SIZE.into()),
1131 background_color: Some(crate::white()),
1132 ..Default::default()
1133 }),
1134 render_debug_text,
1135 )
1136 });
1137 }
1138
1139 let interactive_bounds = InteractiveBounds {
1140 bounds: bounds.intersect(&cx.content_mask().bounds),
1141 stacking_order: cx.stacking_order().clone(),
1142 };
1143
1144 if self.block_mouse
1145 || style.background.as_ref().is_some_and(|fill| {
1146 fill.color().is_some_and(|color| !color.is_transparent())
1147 })
1148 {
1149 cx.add_opaque_layer(interactive_bounds.bounds);
1150 }
1151
1152 if !cx.has_active_drag() {
1153 if let Some(mouse_cursor) = style.mouse_cursor {
1154 let mouse_position = &cx.mouse_position();
1155 let hovered =
1156 interactive_bounds.visibly_contains(mouse_position, cx);
1157 if hovered {
1158 cx.set_cursor_style(mouse_cursor);
1159 }
1160 }
1161 }
1162
1163 // If this element can be focused, register a mouse down listener
1164 // that will automatically transfer focus when hitting the element.
1165 // This behavior can be suppressed by using `cx.prevent_default()`.
1166 if let Some(focus_handle) = element_state.focus_handle.clone() {
1167 cx.on_mouse_event({
1168 let interactive_bounds = interactive_bounds.clone();
1169 move |event: &MouseDownEvent, phase, cx| {
1170 if phase == DispatchPhase::Bubble
1171 && !cx.default_prevented()
1172 && interactive_bounds.visibly_contains(&event.position, cx)
1173 {
1174 cx.focus(&focus_handle);
1175 // If there is a parent that is also focusable, prevent it
1176 // from transferring focus because we already did so.
1177 cx.prevent_default();
1178 }
1179 }
1180 });
1181 }
1182
1183 for listener in self.mouse_down_listeners.drain(..) {
1184 let interactive_bounds = interactive_bounds.clone();
1185 cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
1186 listener(event, &interactive_bounds, phase, cx);
1187 })
1188 }
1189
1190 for listener in self.mouse_up_listeners.drain(..) {
1191 let interactive_bounds = interactive_bounds.clone();
1192 cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
1193 listener(event, &interactive_bounds, phase, cx);
1194 })
1195 }
1196
1197 for listener in self.mouse_move_listeners.drain(..) {
1198 let interactive_bounds = interactive_bounds.clone();
1199 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1200 listener(event, &interactive_bounds, phase, cx);
1201 })
1202 }
1203
1204 for listener in self.scroll_wheel_listeners.drain(..) {
1205 let interactive_bounds = interactive_bounds.clone();
1206 cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1207 listener(event, &interactive_bounds, phase, cx);
1208 })
1209 }
1210
1211 paint_hover_group_handler(cx);
1212
1213 if self.hover_style.is_some()
1214 || self.base_style.mouse_cursor.is_some()
1215 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
1216 {
1217 let bounds = bounds.intersect(&cx.content_mask().bounds);
1218 let hovered = bounds.contains(&cx.mouse_position());
1219 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1220 if phase == DispatchPhase::Capture
1221 && bounds.contains(&event.position) != hovered
1222 {
1223 cx.refresh();
1224 }
1225 });
1226 }
1227
1228 let mut drag_listener = mem::take(&mut self.drag_listener);
1229 let drop_listeners = mem::take(&mut self.drop_listeners);
1230 let click_listeners = mem::take(&mut self.click_listeners);
1231 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
1232
1233 if !drop_listeners.is_empty() {
1234 cx.on_mouse_event({
1235 let interactive_bounds = interactive_bounds.clone();
1236 move |event: &MouseUpEvent, phase, cx| {
1237 if let Some(drag) = &cx.active_drag {
1238 if phase == DispatchPhase::Bubble
1239 && interactive_bounds
1240 .drag_target_contains(&event.position, cx)
1241 {
1242 let drag_state_type = drag.value.as_ref().type_id();
1243 for (drop_state_type, listener) in &drop_listeners {
1244 if *drop_state_type == drag_state_type {
1245 let drag = cx.active_drag.take().expect(
1246 "checked for type drag state type above",
1247 );
1248
1249 let mut can_drop = true;
1250 if let Some(predicate) = &can_drop_predicate {
1251 can_drop =
1252 predicate(drag.value.as_ref(), cx);
1253 }
1254
1255 if can_drop {
1256 listener(drag.value.as_ref(), cx);
1257 cx.refresh();
1258 cx.stop_propagation();
1259 }
1260 }
1261 }
1262 }
1263 }
1264 }
1265 });
1266 }
1267
1268 if !click_listeners.is_empty() || drag_listener.is_some() {
1269 let pending_mouse_down = element_state
1270 .pending_mouse_down
1271 .get_or_insert_with(Default::default)
1272 .clone();
1273
1274 let clicked_state = element_state
1275 .clicked_state
1276 .get_or_insert_with(Default::default)
1277 .clone();
1278
1279 cx.on_mouse_event({
1280 let interactive_bounds = interactive_bounds.clone();
1281 let pending_mouse_down = pending_mouse_down.clone();
1282 move |event: &MouseDownEvent, phase, cx| {
1283 if phase == DispatchPhase::Bubble
1284 && event.button == MouseButton::Left
1285 && interactive_bounds.visibly_contains(&event.position, cx)
1286 {
1287 *pending_mouse_down.borrow_mut() = Some(event.clone());
1288 cx.refresh();
1289 }
1290 }
1291 });
1292
1293 cx.on_mouse_event({
1294 let pending_mouse_down = pending_mouse_down.clone();
1295 move |event: &MouseMoveEvent, phase, cx| {
1296 if phase == DispatchPhase::Capture {
1297 return;
1298 }
1299
1300 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
1301 if let Some(mouse_down) = pending_mouse_down.clone() {
1302 if !cx.has_active_drag()
1303 && (event.position - mouse_down.position).magnitude()
1304 > DRAG_THRESHOLD
1305 {
1306 if let Some((drag_value, drag_listener)) =
1307 drag_listener.take()
1308 {
1309 *clicked_state.borrow_mut() =
1310 ElementClickedState::default();
1311 let cursor_offset = event.position - bounds.origin;
1312 let drag = (drag_listener)(drag_value.as_ref(), cx);
1313 cx.active_drag = Some(AnyDrag {
1314 view: drag,
1315 value: drag_value,
1316 cursor_offset,
1317 });
1318 pending_mouse_down.take();
1319 cx.refresh();
1320 cx.stop_propagation();
1321 }
1322 }
1323 }
1324 }
1325 });
1326
1327 cx.on_mouse_event({
1328 let interactive_bounds = interactive_bounds.clone();
1329 let mut captured_mouse_down = None;
1330 move |event: &MouseUpEvent, phase, cx| match phase {
1331 // Clear the pending mouse down during the capture phase,
1332 // so that it happens even if another event handler stops
1333 // propagation.
1334 DispatchPhase::Capture => {
1335 let mut pending_mouse_down =
1336 pending_mouse_down.borrow_mut();
1337 if pending_mouse_down.is_some() {
1338 captured_mouse_down = pending_mouse_down.take();
1339 cx.refresh();
1340 }
1341 }
1342 // Fire click handlers during the bubble phase.
1343 DispatchPhase::Bubble => {
1344 if let Some(mouse_down) = captured_mouse_down.take() {
1345 if interactive_bounds
1346 .visibly_contains(&event.position, cx)
1347 {
1348 let mouse_click = ClickEvent {
1349 down: mouse_down,
1350 up: event.clone(),
1351 };
1352 for listener in &click_listeners {
1353 listener(&mouse_click, cx);
1354 }
1355 }
1356 }
1357 }
1358 }
1359 });
1360 }
1361
1362 if let Some(hover_listener) = self.hover_listener.take() {
1363 let was_hovered = element_state
1364 .hover_state
1365 .get_or_insert_with(Default::default)
1366 .clone();
1367 let has_mouse_down = element_state
1368 .pending_mouse_down
1369 .get_or_insert_with(Default::default)
1370 .clone();
1371 let interactive_bounds = interactive_bounds.clone();
1372
1373 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1374 if phase != DispatchPhase::Bubble {
1375 return;
1376 }
1377 let is_hovered = interactive_bounds
1378 .visibly_contains(&event.position, cx)
1379 && has_mouse_down.borrow().is_none()
1380 && !cx.has_active_drag();
1381 let mut was_hovered = was_hovered.borrow_mut();
1382
1383 if is_hovered != *was_hovered {
1384 *was_hovered = is_hovered;
1385 drop(was_hovered);
1386
1387 hover_listener(&is_hovered, cx);
1388 }
1389 });
1390 }
1391
1392 if let Some(tooltip_builder) = self.tooltip_builder.take() {
1393 let active_tooltip = element_state
1394 .active_tooltip
1395 .get_or_insert_with(Default::default)
1396 .clone();
1397 let pending_mouse_down = element_state
1398 .pending_mouse_down
1399 .get_or_insert_with(Default::default)
1400 .clone();
1401 let interactive_bounds = interactive_bounds.clone();
1402
1403 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1404 let is_hovered = interactive_bounds
1405 .visibly_contains(&event.position, cx)
1406 && pending_mouse_down.borrow().is_none();
1407 if !is_hovered {
1408 active_tooltip.borrow_mut().take();
1409 return;
1410 }
1411
1412 if phase != DispatchPhase::Bubble {
1413 return;
1414 }
1415
1416 if active_tooltip.borrow().is_none() {
1417 let task = cx.spawn({
1418 let active_tooltip = active_tooltip.clone();
1419 let tooltip_builder = tooltip_builder.clone();
1420
1421 move |mut cx| async move {
1422 cx.background_executor().timer(TOOLTIP_DELAY).await;
1423 cx.update(|_, cx| {
1424 active_tooltip.borrow_mut().replace(
1425 ActiveTooltip {
1426 tooltip: Some(AnyTooltip {
1427 view: tooltip_builder(cx),
1428 cursor_offset: cx.mouse_position(),
1429 }),
1430 _task: None,
1431 },
1432 );
1433 cx.refresh();
1434 })
1435 .ok();
1436 }
1437 });
1438 active_tooltip.borrow_mut().replace(ActiveTooltip {
1439 tooltip: None,
1440 _task: Some(task),
1441 });
1442 }
1443 });
1444
1445 let active_tooltip = element_state
1446 .active_tooltip
1447 .get_or_insert_with(Default::default)
1448 .clone();
1449 cx.on_mouse_event(move |_: &MouseDownEvent, _, _| {
1450 active_tooltip.borrow_mut().take();
1451 });
1452
1453 if let Some(active_tooltip) = element_state
1454 .active_tooltip
1455 .get_or_insert_with(Default::default)
1456 .borrow()
1457 .as_ref()
1458 {
1459 if let Some(tooltip) = active_tooltip.tooltip.clone() {
1460 cx.set_tooltip(tooltip);
1461 }
1462 }
1463 }
1464
1465 let active_state = element_state
1466 .clicked_state
1467 .get_or_insert_with(Default::default)
1468 .clone();
1469 if active_state.borrow().is_clicked() {
1470 cx.on_mouse_event(move |_: &MouseUpEvent, phase, cx| {
1471 if phase == DispatchPhase::Capture {
1472 *active_state.borrow_mut() = ElementClickedState::default();
1473 cx.refresh();
1474 }
1475 });
1476 } else {
1477 let active_group_bounds = self
1478 .group_active_style
1479 .as_ref()
1480 .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
1481 let interactive_bounds = interactive_bounds.clone();
1482 cx.on_mouse_event(move |down: &MouseDownEvent, phase, cx| {
1483 if phase == DispatchPhase::Bubble && !cx.default_prevented() {
1484 let group = active_group_bounds
1485 .map_or(false, |bounds| bounds.contains(&down.position));
1486 let element =
1487 interactive_bounds.visibly_contains(&down.position, cx);
1488 if group || element {
1489 *active_state.borrow_mut() =
1490 ElementClickedState { group, element };
1491 cx.refresh();
1492 }
1493 }
1494 });
1495 }
1496
1497 let overflow = style.overflow;
1498 if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
1499 if let Some(scroll_handle) = &self.scroll_handle {
1500 scroll_handle.0.borrow_mut().overflow = overflow;
1501 }
1502
1503 let scroll_offset = element_state
1504 .scroll_offset
1505 .get_or_insert_with(Rc::default)
1506 .clone();
1507 let line_height = cx.line_height();
1508 let scroll_max = (content_size - bounds.size).max(&Size::default());
1509 // Clamp scroll offset in case scroll max is smaller now (e.g., if children
1510 // were removed or the bounds became larger).
1511 {
1512 let mut scroll_offset = scroll_offset.borrow_mut();
1513 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.width, px(0.));
1514 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.height, px(0.));
1515 }
1516
1517 let interactive_bounds = interactive_bounds.clone();
1518 cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1519 if phase == DispatchPhase::Bubble
1520 && interactive_bounds.visibly_contains(&event.position, cx)
1521 {
1522 let mut scroll_offset = scroll_offset.borrow_mut();
1523 let old_scroll_offset = *scroll_offset;
1524 let delta = event.delta.pixel_delta(line_height);
1525
1526 if overflow.x == Overflow::Scroll {
1527 let mut delta_x = Pixels::ZERO;
1528 if !delta.x.is_zero() {
1529 delta_x = delta.x;
1530 } else if overflow.y != Overflow::Scroll {
1531 delta_x = delta.y;
1532 }
1533
1534 scroll_offset.x = (scroll_offset.x + delta_x)
1535 .clamp(-scroll_max.width, px(0.));
1536 }
1537
1538 if overflow.y == Overflow::Scroll {
1539 let mut delta_y = Pixels::ZERO;
1540 if !delta.y.is_zero() {
1541 delta_y = delta.y;
1542 } else if overflow.x != Overflow::Scroll {
1543 delta_y = delta.x;
1544 }
1545
1546 scroll_offset.y = (scroll_offset.y + delta_y)
1547 .clamp(-scroll_max.height, px(0.));
1548 }
1549
1550 if *scroll_offset != old_scroll_offset {
1551 cx.refresh();
1552 cx.stop_propagation();
1553 }
1554 }
1555 });
1556 }
1557
1558 if let Some(group) = self.group.clone() {
1559 GroupBounds::push(group, bounds, cx);
1560 }
1561
1562 let scroll_offset = element_state
1563 .scroll_offset
1564 .as_ref()
1565 .map(|scroll_offset| *scroll_offset.borrow());
1566
1567 let key_down_listeners = mem::take(&mut self.key_down_listeners);
1568 let key_up_listeners = mem::take(&mut self.key_up_listeners);
1569 let action_listeners = mem::take(&mut self.action_listeners);
1570 cx.with_key_dispatch(
1571 self.key_context.clone(),
1572 element_state.focus_handle.clone(),
1573 |_, cx| {
1574 for listener in key_down_listeners {
1575 cx.on_key_event(move |event: &KeyDownEvent, phase, cx| {
1576 listener(event, phase, cx);
1577 })
1578 }
1579
1580 for listener in key_up_listeners {
1581 cx.on_key_event(move |event: &KeyUpEvent, phase, cx| {
1582 listener(event, phase, cx);
1583 })
1584 }
1585
1586 for (action_type, listener) in action_listeners {
1587 cx.on_action(action_type, listener)
1588 }
1589
1590 f(&style, scroll_offset.unwrap_or_default(), cx)
1591 },
1592 );
1593
1594 if let Some(group) = self.group.as_ref() {
1595 GroupBounds::pop(group, cx);
1596 }
1597 });
1598 });
1599 });
1600 });
1601 }
1602
1603 pub fn compute_style(
1604 &self,
1605 bounds: Option<Bounds<Pixels>>,
1606 element_state: &mut InteractiveElementState,
1607 cx: &mut WindowContext,
1608 ) -> Style {
1609 let mut style = Style::default();
1610 style.refine(&self.base_style);
1611
1612 cx.with_z_index(style.z_index.unwrap_or(0), |cx| {
1613 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1614 if let Some(in_focus_style) = self.in_focus_style.as_ref() {
1615 if focus_handle.within_focused(cx) {
1616 style.refine(in_focus_style);
1617 }
1618 }
1619
1620 if let Some(focus_style) = self.focus_style.as_ref() {
1621 if focus_handle.is_focused(cx) {
1622 style.refine(focus_style);
1623 }
1624 }
1625 }
1626
1627 if let Some(bounds) = bounds {
1628 let mouse_position = cx.mouse_position();
1629 if !cx.has_active_drag() {
1630 if let Some(group_hover) = self.group_hover_style.as_ref() {
1631 if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
1632 if group_bounds.contains(&mouse_position)
1633 && cx.was_top_layer(&mouse_position, cx.stacking_order())
1634 {
1635 style.refine(&group_hover.style);
1636 }
1637 }
1638 }
1639
1640 if let Some(hover_style) = self.hover_style.as_ref() {
1641 if bounds
1642 .intersect(&cx.content_mask().bounds)
1643 .contains(&mouse_position)
1644 && cx.was_top_layer(&mouse_position, cx.stacking_order())
1645 {
1646 style.refine(hover_style);
1647 }
1648 }
1649 }
1650
1651 if let Some(drag) = cx.active_drag.take() {
1652 let mut can_drop = true;
1653 if let Some(can_drop_predicate) = &self.can_drop_predicate {
1654 can_drop = can_drop_predicate(drag.value.as_ref(), cx);
1655 }
1656
1657 if can_drop {
1658 for (state_type, group_drag_style) in &self.group_drag_over_styles {
1659 if let Some(group_bounds) =
1660 GroupBounds::get(&group_drag_style.group, cx)
1661 {
1662 if *state_type == drag.value.as_ref().type_id()
1663 && group_bounds.contains(&mouse_position)
1664 {
1665 style.refine(&group_drag_style.style);
1666 }
1667 }
1668 }
1669
1670 for (state_type, drag_over_style) in &self.drag_over_styles {
1671 if *state_type == drag.value.as_ref().type_id()
1672 && bounds
1673 .intersect(&cx.content_mask().bounds)
1674 .contains(&mouse_position)
1675 && cx.was_top_layer_under_active_drag(
1676 &mouse_position,
1677 cx.stacking_order(),
1678 )
1679 {
1680 style.refine(drag_over_style);
1681 }
1682 }
1683 }
1684
1685 cx.active_drag = Some(drag);
1686 }
1687 }
1688
1689 let clicked_state = element_state
1690 .clicked_state
1691 .get_or_insert_with(Default::default)
1692 .borrow();
1693 if clicked_state.group {
1694 if let Some(group) = self.group_active_style.as_ref() {
1695 style.refine(&group.style)
1696 }
1697 }
1698
1699 if let Some(active_style) = self.active_style.as_ref() {
1700 if clicked_state.element {
1701 style.refine(active_style)
1702 }
1703 }
1704 });
1705
1706 style
1707 }
1708}
1709
1710#[derive(Default)]
1711pub struct InteractiveElementState {
1712 pub focus_handle: Option<FocusHandle>,
1713 pub clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
1714 pub hover_state: Option<Rc<RefCell<bool>>>,
1715 pub pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
1716 pub scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
1717 pub active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
1718}
1719
1720pub struct ActiveTooltip {
1721 tooltip: Option<AnyTooltip>,
1722 _task: Option<Task<()>>,
1723}
1724
1725/// Whether or not the element or a group that contains it is clicked by the mouse.
1726#[derive(Copy, Clone, Default, Eq, PartialEq)]
1727pub struct ElementClickedState {
1728 pub group: bool,
1729 pub element: bool,
1730}
1731
1732impl ElementClickedState {
1733 fn is_clicked(&self) -> bool {
1734 self.group || self.element
1735 }
1736}
1737
1738#[derive(Default)]
1739pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
1740
1741impl GroupBounds {
1742 pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
1743 cx.default_global::<Self>()
1744 .0
1745 .get(name)
1746 .and_then(|bounds_stack| bounds_stack.last())
1747 .cloned()
1748 }
1749
1750 pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
1751 cx.default_global::<Self>()
1752 .0
1753 .entry(name)
1754 .or_default()
1755 .push(bounds);
1756 }
1757
1758 pub fn pop(name: &SharedString, cx: &mut AppContext) {
1759 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
1760 }
1761}
1762
1763pub struct Focusable<E> {
1764 pub element: E,
1765}
1766
1767impl<E: InteractiveElement> FocusableElement for Focusable<E> {}
1768
1769impl<E> InteractiveElement for Focusable<E>
1770where
1771 E: InteractiveElement,
1772{
1773 fn interactivity(&mut self) -> &mut Interactivity {
1774 self.element.interactivity()
1775 }
1776}
1777
1778impl<E: StatefulInteractiveElement> StatefulInteractiveElement for Focusable<E> {}
1779
1780impl<E> Styled for Focusable<E>
1781where
1782 E: Styled,
1783{
1784 fn style(&mut self) -> &mut StyleRefinement {
1785 self.element.style()
1786 }
1787}
1788
1789impl<E> Element for Focusable<E>
1790where
1791 E: Element,
1792{
1793 type State = E::State;
1794
1795 fn request_layout(
1796 &mut self,
1797 state: Option<Self::State>,
1798 cx: &mut WindowContext,
1799 ) -> (LayoutId, Self::State) {
1800 self.element.request_layout(state, cx)
1801 }
1802
1803 fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut WindowContext) {
1804 self.element.paint(bounds, state, cx)
1805 }
1806}
1807
1808impl<E> IntoElement for Focusable<E>
1809where
1810 E: IntoElement,
1811{
1812 type Element = E::Element;
1813
1814 fn element_id(&self) -> Option<ElementId> {
1815 self.element.element_id()
1816 }
1817
1818 fn into_element(self) -> Self::Element {
1819 self.element.into_element()
1820 }
1821}
1822
1823impl<E> ParentElement for Focusable<E>
1824where
1825 E: ParentElement,
1826{
1827 fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
1828 self.element.children_mut()
1829 }
1830}
1831
1832pub struct Stateful<E> {
1833 element: E,
1834}
1835
1836impl<E> Styled for Stateful<E>
1837where
1838 E: Styled,
1839{
1840 fn style(&mut self) -> &mut StyleRefinement {
1841 self.element.style()
1842 }
1843}
1844
1845impl<E> StatefulInteractiveElement for Stateful<E>
1846where
1847 E: Element,
1848 Self: InteractiveElement,
1849{
1850}
1851
1852impl<E> InteractiveElement for Stateful<E>
1853where
1854 E: InteractiveElement,
1855{
1856 fn interactivity(&mut self) -> &mut Interactivity {
1857 self.element.interactivity()
1858 }
1859}
1860
1861impl<E: FocusableElement> FocusableElement for Stateful<E> {}
1862
1863impl<E> Element for Stateful<E>
1864where
1865 E: Element,
1866{
1867 type State = E::State;
1868
1869 fn request_layout(
1870 &mut self,
1871 state: Option<Self::State>,
1872 cx: &mut WindowContext,
1873 ) -> (LayoutId, Self::State) {
1874 self.element.request_layout(state, cx)
1875 }
1876
1877 fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut WindowContext) {
1878 self.element.paint(bounds, state, cx)
1879 }
1880}
1881
1882impl<E> IntoElement for Stateful<E>
1883where
1884 E: Element,
1885{
1886 type Element = Self;
1887
1888 fn element_id(&self) -> Option<ElementId> {
1889 self.element.element_id()
1890 }
1891
1892 fn into_element(self) -> Self::Element {
1893 self
1894 }
1895}
1896
1897impl<E> ParentElement for Stateful<E>
1898where
1899 E: ParentElement,
1900{
1901 fn children_mut(&mut self) -> &mut SmallVec<[AnyElement; 2]> {
1902 self.element.children_mut()
1903 }
1904}
1905
1906#[derive(Default)]
1907struct ScrollHandleState {
1908 // not great to have the nested rc's...
1909 offset: Rc<RefCell<Point<Pixels>>>,
1910 bounds: Bounds<Pixels>,
1911 child_bounds: Vec<Bounds<Pixels>>,
1912 requested_scroll_top: Option<(usize, Pixels)>,
1913 overflow: Point<Overflow>,
1914}
1915
1916#[derive(Clone)]
1917pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
1918
1919impl Default for ScrollHandle {
1920 fn default() -> Self {
1921 Self::new()
1922 }
1923}
1924
1925impl ScrollHandle {
1926 pub fn new() -> Self {
1927 Self(Rc::default())
1928 }
1929
1930 pub fn offset(&self) -> Point<Pixels> {
1931 *self.0.borrow().offset.borrow()
1932 }
1933
1934 pub fn top_item(&self) -> usize {
1935 let state = self.0.borrow();
1936 let top = state.bounds.top() - state.offset.borrow().y;
1937
1938 match state.child_bounds.binary_search_by(|bounds| {
1939 if top < bounds.top() {
1940 Ordering::Greater
1941 } else if top > bounds.bottom() {
1942 Ordering::Less
1943 } else {
1944 Ordering::Equal
1945 }
1946 }) {
1947 Ok(ix) => ix,
1948 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
1949 }
1950 }
1951
1952 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
1953 self.0.borrow().child_bounds.get(ix).cloned()
1954 }
1955
1956 /// scroll_to_item scrolls the minimal amount to ensure that the item is
1957 /// fully visible
1958 pub fn scroll_to_item(&self, ix: usize) {
1959 let state = self.0.borrow();
1960
1961 let Some(bounds) = state.child_bounds.get(ix) else {
1962 return;
1963 };
1964
1965 let mut scroll_offset = state.offset.borrow_mut();
1966
1967 if state.overflow.y == Overflow::Scroll {
1968 if bounds.top() + scroll_offset.y < state.bounds.top() {
1969 scroll_offset.y = state.bounds.top() - bounds.top();
1970 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
1971 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
1972 }
1973 }
1974
1975 if state.overflow.x == Overflow::Scroll {
1976 if bounds.left() + scroll_offset.x < state.bounds.left() {
1977 scroll_offset.x = state.bounds.left() - bounds.left();
1978 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
1979 scroll_offset.x = state.bounds.right() - bounds.right();
1980 }
1981 }
1982 }
1983
1984 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
1985 let ix = self.top_item();
1986 let state = self.0.borrow();
1987
1988 if let Some(child_bounds) = state.child_bounds.get(ix) {
1989 (
1990 ix,
1991 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
1992 )
1993 } else {
1994 (ix, px(0.))
1995 }
1996 }
1997
1998 pub fn set_logical_scroll_top(&self, ix: usize, px: Pixels) {
1999 self.0.borrow_mut().requested_scroll_top = Some((ix, px));
2000 }
2001}