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