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