1use crate::{
2 point, px, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, BorrowAppContext,
3 BorrowWindow, Bounds, ClickEvent, DispatchPhase, Element, FocusHandle, KeyContext,
4 KeyDownEvent, KeyUpEvent, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
5 Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style, StyleRefinement, Styled,
6 Task, View, ViewContext, Visibility,
7};
8use collections::HashMap;
9use parking_lot::Mutex;
10use refineable::Refineable;
11use smallvec::SmallVec;
12use std::{
13 any::{Any, TypeId},
14 marker::PhantomData,
15 mem,
16 sync::Arc,
17 time::Duration,
18};
19use taffy::style::Overflow;
20
21const DRAG_THRESHOLD: f64 = 2.;
22const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
23const TOOLTIP_OFFSET: Point<Pixels> = Point::new(px(10.0), px(8.0));
24
25pub struct GroupStyle {
26 pub group: SharedString,
27 pub style: StyleRefinement,
28}
29
30pub trait InteractiveComponent<V: 'static>: Sized + Element<V> {
31 fn interactivity(&mut self) -> &mut Interactivity<V>;
32
33 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
34 where
35 Self: Sized,
36 {
37 self.interactivity().hover_style = f(StyleRefinement::default());
38 self
39 }
40
41 fn group_hover(
42 mut self,
43 group_name: impl Into<SharedString>,
44 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
45 ) -> Self
46 where
47 Self: Sized,
48 {
49 self.interactivity().group_hover_style = Some(GroupStyle {
50 group: group_name.into(),
51 style: f(StyleRefinement::default()),
52 });
53 self
54 }
55
56 fn on_mouse_down(
57 mut self,
58 button: MouseButton,
59 handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
60 ) -> Self
61 where
62 Self: Sized,
63 {
64 self.interactivity().mouse_down_listeners.push(Box::new(
65 move |view, event, bounds, phase, cx| {
66 if phase == DispatchPhase::Bubble
67 && event.button == button
68 && bounds.contains_point(&event.position)
69 {
70 handler(view, event, cx)
71 }
72 },
73 ));
74 self
75 }
76
77 fn on_mouse_up(
78 mut self,
79 button: MouseButton,
80 handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
81 ) -> Self
82 where
83 Self: Sized,
84 {
85 self.interactivity().mouse_up_listeners.push(Box::new(
86 move |view, event, bounds, phase, cx| {
87 if phase == DispatchPhase::Bubble
88 && event.button == button
89 && bounds.contains_point(&event.position)
90 {
91 handler(view, event, cx)
92 }
93 },
94 ));
95 self
96 }
97
98 fn on_mouse_down_out(
99 mut self,
100 handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
101 ) -> Self
102 where
103 Self: Sized,
104 {
105 self.interactivity().mouse_down_listeners.push(Box::new(
106 move |view, event, bounds, phase, cx| {
107 if phase == DispatchPhase::Capture && !bounds.contains_point(&event.position) {
108 handler(view, event, cx)
109 }
110 },
111 ));
112 self
113 }
114
115 fn on_mouse_up_out(
116 mut self,
117 button: MouseButton,
118 handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
119 ) -> Self
120 where
121 Self: Sized,
122 {
123 self.interactivity().mouse_up_listeners.push(Box::new(
124 move |view, event, bounds, phase, cx| {
125 if phase == DispatchPhase::Capture
126 && event.button == button
127 && !bounds.contains_point(&event.position)
128 {
129 handler(view, event, cx);
130 }
131 },
132 ));
133 self
134 }
135
136 fn on_mouse_move(
137 mut self,
138 handler: impl Fn(&mut V, &MouseMoveEvent, &mut ViewContext<V>) + 'static,
139 ) -> Self
140 where
141 Self: Sized,
142 {
143 self.interactivity().mouse_move_listeners.push(Box::new(
144 move |view, event, bounds, phase, cx| {
145 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
146 handler(view, event, cx);
147 }
148 },
149 ));
150 self
151 }
152
153 fn on_scroll_wheel(
154 mut self,
155 handler: impl Fn(&mut V, &ScrollWheelEvent, &mut ViewContext<V>) + 'static,
156 ) -> Self
157 where
158 Self: Sized,
159 {
160 self.interactivity().scroll_wheel_listeners.push(Box::new(
161 move |view, event, bounds, phase, cx| {
162 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
163 handler(view, event, cx);
164 }
165 },
166 ));
167 self
168 }
169
170 /// Capture the given action, fires during the capture phase
171 fn capture_action<A: Action>(
172 mut self,
173 listener: impl Fn(&mut V, &A, &mut ViewContext<V>) + 'static,
174 ) -> Self
175 where
176 Self: Sized,
177 {
178 self.interactivity().action_listeners.push((
179 TypeId::of::<A>(),
180 Box::new(move |view, action, phase, cx| {
181 let action = action.downcast_ref().unwrap();
182 if phase == DispatchPhase::Capture {
183 listener(view, action, cx)
184 }
185 }),
186 ));
187 self
188 }
189
190 /// Add a listener for the given action, fires during the bubble event phase
191 fn on_action<A: Action>(
192 mut self,
193 listener: impl Fn(&mut V, &A, &mut ViewContext<V>) + 'static,
194 ) -> Self
195 where
196 Self: Sized,
197 {
198 self.interactivity().action_listeners.push((
199 TypeId::of::<A>(),
200 Box::new(move |view, action, phase, cx| {
201 let action = action.downcast_ref().unwrap();
202 if phase == DispatchPhase::Bubble {
203 listener(view, action, cx)
204 }
205 }),
206 ));
207 self
208 }
209
210 fn on_key_down(
211 mut self,
212 listener: impl Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
213 ) -> Self
214 where
215 Self: Sized,
216 {
217 self.interactivity()
218 .key_down_listeners
219 .push(Box::new(move |view, event, phase, cx| {
220 listener(view, event, phase, cx)
221 }));
222 self
223 }
224
225 fn on_key_up(
226 mut self,
227 listener: impl Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
228 ) -> Self
229 where
230 Self: Sized,
231 {
232 self.interactivity()
233 .key_up_listeners
234 .push(Box::new(move |view, event, phase, cx| {
235 listener(view, event, phase, cx)
236 }));
237 self
238 }
239
240 fn drag_over<S: 'static>(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
241 where
242 Self: Sized,
243 {
244 self.interactivity()
245 .drag_over_styles
246 .push((TypeId::of::<S>(), f(StyleRefinement::default())));
247 self
248 }
249
250 fn group_drag_over<S: 'static>(
251 mut self,
252 group_name: impl Into<SharedString>,
253 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
254 ) -> Self
255 where
256 Self: Sized,
257 {
258 self.interactivity().group_drag_over_styles.push((
259 TypeId::of::<S>(),
260 GroupStyle {
261 group: group_name.into(),
262 style: f(StyleRefinement::default()),
263 },
264 ));
265 self
266 }
267
268 fn on_drop<W: 'static>(
269 mut self,
270 listener: impl Fn(&mut V, View<W>, &mut ViewContext<V>) + 'static,
271 ) -> Self
272 where
273 Self: Sized,
274 {
275 self.interactivity().drop_listeners.push((
276 TypeId::of::<W>(),
277 Box::new(move |view, dragged_view, cx| {
278 listener(view, dragged_view.downcast().unwrap(), cx);
279 }),
280 ));
281 self
282 }
283}
284
285pub trait StatefulInteractiveComponent<V: 'static, E: Element<V>>: InteractiveComponent<V> {
286 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
287 where
288 Self: Sized,
289 {
290 self.interactivity().active_style = f(StyleRefinement::default());
291 self
292 }
293
294 fn group_active(
295 mut self,
296 group_name: impl Into<SharedString>,
297 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
298 ) -> Self
299 where
300 Self: Sized,
301 {
302 self.interactivity().group_active_style = Some(GroupStyle {
303 group: group_name.into(),
304 style: f(StyleRefinement::default()),
305 });
306 self
307 }
308
309 fn on_click(
310 mut self,
311 listener: impl Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static,
312 ) -> Self
313 where
314 Self: Sized,
315 {
316 self.interactivity()
317 .click_listeners
318 .push(Box::new(move |view, event, cx| listener(view, event, cx)));
319 self
320 }
321
322 fn on_drag<W>(
323 mut self,
324 listener: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
325 ) -> Self
326 where
327 Self: Sized,
328 W: 'static + Render,
329 {
330 debug_assert!(
331 self.interactivity().drag_listener.is_none(),
332 "calling on_drag more than once on the same element is not supported"
333 );
334 self.interactivity().drag_listener =
335 Some(Box::new(move |view_state, cursor_offset, cx| AnyDrag {
336 view: listener(view_state, cx).into(),
337 cursor_offset,
338 }));
339 self
340 }
341
342 fn on_hover(mut self, listener: impl 'static + Fn(&mut V, bool, &mut ViewContext<V>)) -> Self
343 where
344 Self: Sized,
345 {
346 debug_assert!(
347 self.interactivity().hover_listener.is_none(),
348 "calling on_hover more than once on the same element is not supported"
349 );
350 self.interactivity().hover_listener = Some(Box::new(listener));
351 self
352 }
353
354 fn tooltip<W>(
355 mut self,
356 build_tooltip: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
357 ) -> Self
358 where
359 Self: Sized,
360 W: 'static + Render,
361 {
362 debug_assert!(
363 self.interactivity().tooltip_builder.is_none(),
364 "calling tooltip more than once on the same element is not supported"
365 );
366 self.interactivity().tooltip_builder = Some(Arc::new(move |view_state, cx| {
367 build_tooltip(view_state, cx).into()
368 }));
369
370 self
371 }
372}
373
374pub trait FocusableComponent<V> {
375 fn focusability(&mut self) -> &mut Focusability<V>;
376
377 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
378 where
379 Self: Sized,
380 {
381 self.focusability().focus_style = f(StyleRefinement::default());
382 self
383 }
384
385 fn focus_in(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
386 where
387 Self: Sized,
388 {
389 self.focusability().focus_in_style = f(StyleRefinement::default());
390 self
391 }
392
393 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
394 where
395 Self: Sized,
396 {
397 self.focusability().in_focus_style = f(StyleRefinement::default());
398 self
399 }
400
401 fn on_focus(
402 mut self,
403 listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
404 ) -> Self
405 where
406 Self: Sized,
407 {
408 self.focusability()
409 .focus_listeners
410 .push(Box::new(move |view, focus_handle, event, cx| {
411 if event.focused.as_ref() == Some(focus_handle) {
412 listener(view, event, cx)
413 }
414 }));
415 self
416 }
417
418 fn on_blur(
419 mut self,
420 listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
421 ) -> Self
422 where
423 Self: Sized,
424 {
425 self.focusability()
426 .focus_listeners
427 .push(Box::new(move |view, focus_handle, event, cx| {
428 if event.blurred.as_ref() == Some(focus_handle) {
429 listener(view, event, cx)
430 }
431 }));
432 self
433 }
434
435 fn on_focus_in(
436 mut self,
437 listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
438 ) -> Self
439 where
440 Self: Sized,
441 {
442 self.focusability()
443 .focus_listeners
444 .push(Box::new(move |view, focus_handle, event, cx| {
445 let descendant_blurred = event
446 .blurred
447 .as_ref()
448 .map_or(false, |blurred| focus_handle.contains(blurred, cx));
449 let descendant_focused = event
450 .focused
451 .as_ref()
452 .map_or(false, |focused| focus_handle.contains(focused, cx));
453
454 if !descendant_blurred && descendant_focused {
455 listener(view, event, cx)
456 }
457 }));
458 self
459 }
460
461 fn on_focus_out(
462 mut self,
463 listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
464 ) -> Self
465 where
466 Self: Sized,
467 {
468 self.focusability()
469 .focus_listeners
470 .push(Box::new(move |view, focus_handle, event, cx| {
471 let descendant_blurred = event
472 .blurred
473 .as_ref()
474 .map_or(false, |blurred| focus_handle.contains(blurred, cx));
475 let descendant_focused = event
476 .focused
477 .as_ref()
478 .map_or(false, |focused| focus_handle.contains(focused, cx));
479 if descendant_blurred && !descendant_focused {
480 listener(view, event, cx)
481 }
482 }));
483 self
484 }
485}
486
487pub type FocusListeners<V> = SmallVec<[FocusListener<V>; 2]>;
488
489pub type FocusListener<V> =
490 Box<dyn Fn(&mut V, &FocusHandle, &FocusEvent, &mut ViewContext<V>) + 'static>;
491
492pub type MouseDownListener<V> = Box<
493 dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
494>;
495pub type MouseUpListener<V> = Box<
496 dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
497>;
498
499pub type MouseMoveListener<V> = Box<
500 dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
501>;
502
503pub type ScrollWheelListener<V> = Box<
504 dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
505 + 'static,
506>;
507
508pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static>;
509
510pub type DragListener<V> =
511 Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + 'static>;
512
513type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static;
514
515pub type HoverListener<V> = Box<dyn Fn(&mut V, bool, &mut ViewContext<V>) + 'static>;
516
517pub type TooltipBuilder<V> = Arc<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>;
518
519pub type KeyDownListener<V> =
520 Box<dyn Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + 'static>;
521
522pub type KeyUpListener<V> =
523 Box<dyn Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>) + 'static>;
524
525pub type ActionListener<V> =
526 Box<dyn Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static>;
527
528pub struct FocusEvent {
529 pub blurred: Option<FocusHandle>,
530 pub focused: Option<FocusHandle>,
531}
532
533pub struct Node<V> {
534 interactivity: Interactivity<V>,
535 children: Vec<AnyElement<V>>,
536}
537
538impl<V> Styled for Node<V> {
539 fn style(&mut self) -> &mut StyleRefinement {
540 &mut self.interactivity.base_style
541 }
542}
543
544impl<V: 'static> InteractiveComponent<V> for Node<V> {
545 fn interactivity(&mut self) -> &mut Interactivity<V> {
546 &mut self.interactivity
547 }
548}
549
550impl<V: 'static> Element<V> for Node<V> {
551 type ElementState = NodeState;
552
553 fn id(&self) -> Option<crate::ElementId> {
554 None
555 }
556
557 fn initialize(
558 &mut self,
559 view_state: &mut V,
560 previous_element_state: Option<Self::ElementState>,
561 cx: &mut ViewContext<V>,
562 ) -> Self::ElementState {
563 for child in &mut self.children {
564 child.initialize(view_state, cx);
565 }
566 NodeState {
567 child_layout_ids: SmallVec::new(),
568 interactive_state: previous_element_state
569 .map(|s| s.interactive_state)
570 .unwrap_or_default(),
571 }
572 }
573
574 fn layout(
575 &mut self,
576 view_state: &mut V,
577 element_state: &mut Self::ElementState,
578 cx: &mut ViewContext<V>,
579 ) -> crate::LayoutId {
580 let mut interactivity = mem::take(&mut self.interactivity);
581 let layout_id =
582 interactivity.layout(&mut element_state.interactive_state, cx, |style, cx| {
583 cx.with_text_style(style.text_style().cloned(), |cx| {
584 element_state.child_layout_ids = self
585 .children
586 .iter_mut()
587 .map(|child| child.layout(view_state, cx))
588 .collect::<SmallVec<_>>();
589 cx.request_layout(&style, element_state.child_layout_ids.iter().copied())
590 })
591 });
592 self.interactivity = interactivity;
593 layout_id
594 }
595
596 fn paint(
597 &mut self,
598 bounds: Bounds<Pixels>,
599 view_state: &mut V,
600 element_state: &mut Self::ElementState,
601 cx: &mut ViewContext<V>,
602 ) {
603 let mut interactivity = mem::take(&mut self.interactivity);
604
605 let mut child_min = point(Pixels::MAX, Pixels::MAX);
606 let mut child_max = Point::default();
607 let content_size = if element_state.child_layout_ids.is_empty() {
608 bounds.size
609 } else {
610 for child_layout_id in &element_state.child_layout_ids {
611 let child_bounds = cx.layout_bounds(*child_layout_id);
612 child_min = child_min.min(&child_bounds.origin);
613 child_max = child_max.max(&child_bounds.lower_right());
614 }
615 (child_max - child_min).into()
616 };
617
618 interactivity.paint(
619 bounds,
620 content_size,
621 &mut element_state.interactive_state,
622 cx,
623 |style, scroll_offset, cx| {
624 if style.visibility == Visibility::Hidden {
625 return;
626 }
627
628 let z_index = style.z_index.unwrap_or(0);
629
630 cx.with_z_index(z_index, |cx| {
631 cx.with_z_index(0, |cx| {
632 style.paint(bounds, cx);
633 });
634 cx.with_z_index(1, |cx| {
635 cx.with_text_style(style.text_style().cloned(), |cx| {
636 cx.with_content_mask(style.overflow_mask(bounds), |cx| {
637 cx.with_element_offset(scroll_offset, |cx| {
638 for child in &mut self.children {
639 child.paint(view_state, cx);
640 }
641 })
642 })
643 })
644 })
645 })
646 },
647 );
648 self.interactivity = interactivity;
649 }
650}
651
652pub struct NodeState {
653 child_layout_ids: SmallVec<[LayoutId; 4]>,
654 interactive_state: InteractiveElementState,
655}
656
657impl AsMut<InteractiveElementState> for InteractiveElementState {
658 fn as_mut(&mut self) -> &mut InteractiveElementState {
659 self
660 }
661}
662
663pub struct Interactivity<V> {
664 hovered: bool,
665 group_hovered: bool,
666 key_context: KeyContext,
667 focus_handle: Option<FocusHandle>,
668 focusable: bool,
669 scroll_offset: Point<Pixels>,
670 group: Option<SharedString>,
671 base_style: StyleRefinement,
672 focus_style: StyleRefinement,
673 focus_in_style: StyleRefinement,
674 in_focus_style: StyleRefinement,
675 hover_style: StyleRefinement,
676 group_hover_style: Option<GroupStyle>,
677 active_style: StyleRefinement,
678 group_active_style: Option<GroupStyle>,
679 drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
680 group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
681 mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
682 mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
683 mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
684 scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
685 key_down_listeners: SmallVec<[KeyDownListener<V>; 2]>,
686 key_up_listeners: SmallVec<[KeyUpListener<V>; 2]>,
687 action_listeners: SmallVec<[(TypeId, ActionListener<V>); 8]>,
688 drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
689 click_listeners: SmallVec<[ClickListener<V>; 2]>,
690 drag_listener: Option<DragListener<V>>,
691 hover_listener: Option<HoverListener<V>>,
692 tooltip_builder: Option<TooltipBuilder<V>>,
693}
694
695#[derive(Default)]
696pub struct InteractiveElementState {
697 focus_handle: Option<FocusHandle>,
698 clicked_state: Arc<Mutex<ElementClickedState>>,
699 hover_state: Arc<Mutex<bool>>,
700 pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
701 scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
702 active_tooltip: Arc<Mutex<Option<ActiveTooltip>>>,
703}
704
705struct ActiveTooltip {
706 #[allow(unused)] // used to drop the task
707 waiting: Option<Task<()>>,
708 tooltip: Option<AnyTooltip>,
709}
710
711/// Whether or not the element or a group that contains it is clicked by the mouse.
712#[derive(Copy, Clone, Default, Eq, PartialEq)]
713struct ElementClickedState {
714 pub group: bool,
715 pub element: bool,
716}
717
718impl ElementClickedState {
719 fn is_clicked(&self) -> bool {
720 self.group || self.element
721 }
722}
723
724impl<V> Interactivity<V>
725where
726 V: 'static,
727{
728 fn compute_style(
729 &self,
730 bounds: Option<Bounds<Pixels>>,
731 element_state: &mut InteractiveElementState,
732 cx: &mut ViewContext<V>,
733 ) -> Style {
734 let mut style = Style::default();
735 style.refine(&self.base_style);
736
737 if let Some(focus_handle) = self.focus_handle.as_ref() {
738 if focus_handle.contains_focused(cx) {
739 style.refine(&self.focus_in_style);
740 }
741
742 if focus_handle.within_focused(cx) {
743 style.refine(&self.in_focus_style);
744 }
745
746 if focus_handle.is_focused(cx) {
747 style.refine(&self.focus_style);
748 }
749 }
750
751 if let Some(bounds) = bounds {
752 let mouse_position = cx.mouse_position();
753 if let Some(group_hover) = self.group_hover_style.as_ref() {
754 if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
755 if group_bounds.contains_point(&mouse_position) {
756 style.refine(&group_hover.style);
757 }
758 }
759 }
760 if bounds.contains_point(&mouse_position) {
761 style.refine(&self.hover_style);
762 }
763
764 if let Some(drag) = cx.active_drag.take() {
765 for (state_type, group_drag_style) in &self.group_drag_over_styles {
766 if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
767 if *state_type == drag.view.entity_type()
768 && group_bounds.contains_point(&mouse_position)
769 {
770 style.refine(&group_drag_style.style);
771 }
772 }
773 }
774
775 for (state_type, drag_over_style) in &self.drag_over_styles {
776 if *state_type == drag.view.entity_type()
777 && bounds.contains_point(&mouse_position)
778 {
779 style.refine(drag_over_style);
780 }
781 }
782
783 cx.active_drag = Some(drag);
784 }
785 }
786
787 let clicked_state = element_state.clicked_state.lock();
788 if clicked_state.group {
789 if let Some(group) = self.group_active_style.as_ref() {
790 style.refine(&group.style)
791 }
792 }
793
794 if clicked_state.element {
795 style.refine(&self.active_style)
796 }
797
798 style
799 }
800
801 fn layout(
802 &mut self,
803 element_state: &mut InteractiveElementState,
804 cx: &mut ViewContext<V>,
805 f: impl FnOnce(Style, &mut ViewContext<V>) -> LayoutId,
806 ) -> LayoutId {
807 let style = self.compute_style(None, element_state, cx);
808 cx.with_key_dispatch(
809 self.key_context.clone(),
810 self.focus_handle.clone(),
811 |_, cx| f(style, cx),
812 )
813 }
814
815 fn paint(
816 &mut self,
817 bounds: Bounds<Pixels>,
818 content_size: Size<Pixels>,
819 element_state: &mut InteractiveElementState,
820 cx: &mut ViewContext<V>,
821 f: impl FnOnce(Style, Point<Pixels>, &mut ViewContext<V>),
822 ) {
823 let style = self.compute_style(Some(bounds), element_state, cx);
824
825 if let Some(mouse_cursor) = style.mouse_cursor {
826 let hovered = bounds.contains_point(&cx.mouse_position());
827 if hovered {
828 cx.set_cursor_style(mouse_cursor);
829 }
830 }
831
832 for listener in self.mouse_down_listeners.drain(..) {
833 cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
834 listener(state, event, &bounds, phase, cx);
835 })
836 }
837
838 for listener in self.mouse_up_listeners.drain(..) {
839 cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
840 listener(state, event, &bounds, phase, cx);
841 })
842 }
843
844 for listener in self.mouse_move_listeners.drain(..) {
845 cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
846 listener(state, event, &bounds, phase, cx);
847 })
848 }
849
850 for listener in self.scroll_wheel_listeners.drain(..) {
851 cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
852 listener(state, event, &bounds, phase, cx);
853 })
854 }
855
856 let hover_group_bounds = self
857 .group_hover_style
858 .as_ref()
859 .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
860
861 if let Some(group_bounds) = hover_group_bounds {
862 let hovered = group_bounds.contains_point(&cx.mouse_position());
863 cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
864 if phase == DispatchPhase::Capture {
865 if group_bounds.contains_point(&event.position) != hovered {
866 cx.notify();
867 }
868 }
869 });
870 }
871
872 if self.hover_style.is_some()
873 || (cx.active_drag.is_some() && !self.drag_over_styles.is_empty())
874 {
875 let hovered = bounds.contains_point(&cx.mouse_position());
876 cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
877 if phase == DispatchPhase::Capture {
878 if bounds.contains_point(&event.position) != hovered {
879 cx.notify();
880 }
881 }
882 });
883 }
884
885 if cx.active_drag.is_some() {
886 let drop_listeners = mem::take(&mut self.drop_listeners);
887 cx.on_mouse_event(move |view, event: &MouseUpEvent, phase, cx| {
888 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
889 if let Some(drag_state_type) =
890 cx.active_drag.as_ref().map(|drag| drag.view.entity_type())
891 {
892 for (drop_state_type, listener) in &drop_listeners {
893 if *drop_state_type == drag_state_type {
894 let drag = cx
895 .active_drag
896 .take()
897 .expect("checked for type drag state type above");
898 listener(view, drag.view.clone(), cx);
899 cx.notify();
900 cx.stop_propagation();
901 }
902 }
903 }
904 }
905 });
906 }
907
908 let click_listeners = mem::take(&mut self.click_listeners);
909 let drag_listener = mem::take(&mut self.drag_listener);
910
911 if !click_listeners.is_empty() || drag_listener.is_some() {
912 let pending_mouse_down = element_state.pending_mouse_down.clone();
913 let mouse_down = pending_mouse_down.lock().clone();
914 if let Some(mouse_down) = mouse_down {
915 if let Some(drag_listener) = drag_listener {
916 let active_state = element_state.clicked_state.clone();
917
918 cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
919 if cx.active_drag.is_some() {
920 if phase == DispatchPhase::Capture {
921 cx.notify();
922 }
923 } else if phase == DispatchPhase::Bubble
924 && bounds.contains_point(&event.position)
925 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
926 {
927 *active_state.lock() = ElementClickedState::default();
928 let cursor_offset = event.position - bounds.origin;
929 let drag = drag_listener(view_state, cursor_offset, cx);
930 cx.active_drag = Some(drag);
931 cx.notify();
932 cx.stop_propagation();
933 }
934 });
935 }
936
937 cx.on_mouse_event(move |view_state, event: &MouseUpEvent, phase, cx| {
938 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
939 let mouse_click = ClickEvent {
940 down: mouse_down.clone(),
941 up: event.clone(),
942 };
943 for listener in &click_listeners {
944 listener(view_state, &mouse_click, cx);
945 }
946 }
947 *pending_mouse_down.lock() = None;
948 });
949 } else {
950 cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
951 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
952 *pending_mouse_down.lock() = Some(event.clone());
953 }
954 });
955 }
956 }
957
958 if let Some(hover_listener) = self.hover_listener.take() {
959 let was_hovered = element_state.hover_state.clone();
960 let has_mouse_down = element_state.pending_mouse_down.clone();
961
962 cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
963 if phase != DispatchPhase::Bubble {
964 return;
965 }
966 let is_hovered =
967 bounds.contains_point(&event.position) && has_mouse_down.lock().is_none();
968 let mut was_hovered = was_hovered.lock();
969
970 if is_hovered != was_hovered.clone() {
971 *was_hovered = is_hovered;
972 drop(was_hovered);
973
974 hover_listener(view_state, is_hovered, cx);
975 }
976 });
977 }
978
979 if let Some(tooltip_builder) = self.tooltip_builder.take() {
980 let active_tooltip = element_state.active_tooltip.clone();
981 let pending_mouse_down = element_state.pending_mouse_down.clone();
982
983 cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
984 if phase != DispatchPhase::Bubble {
985 return;
986 }
987
988 let is_hovered =
989 bounds.contains_point(&event.position) && pending_mouse_down.lock().is_none();
990 if !is_hovered {
991 active_tooltip.lock().take();
992 return;
993 }
994
995 if active_tooltip.lock().is_none() {
996 let task = cx.spawn({
997 let active_tooltip = active_tooltip.clone();
998 let tooltip_builder = tooltip_builder.clone();
999
1000 move |view, mut cx| async move {
1001 cx.background_executor().timer(TOOLTIP_DELAY).await;
1002 view.update(&mut cx, move |view_state, cx| {
1003 active_tooltip.lock().replace(ActiveTooltip {
1004 waiting: None,
1005 tooltip: Some(AnyTooltip {
1006 view: tooltip_builder(view_state, cx),
1007 cursor_offset: cx.mouse_position() + TOOLTIP_OFFSET,
1008 }),
1009 });
1010 cx.notify();
1011 })
1012 .ok();
1013 }
1014 });
1015 active_tooltip.lock().replace(ActiveTooltip {
1016 waiting: Some(task),
1017 tooltip: None,
1018 });
1019 }
1020 });
1021
1022 if let Some(active_tooltip) = element_state.active_tooltip.lock().as_ref() {
1023 if active_tooltip.tooltip.is_some() {
1024 cx.active_tooltip = active_tooltip.tooltip.clone()
1025 }
1026 }
1027 }
1028
1029 let active_state = element_state.clicked_state.clone();
1030 if !active_state.lock().is_clicked() {
1031 cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
1032 if phase == DispatchPhase::Capture {
1033 *active_state.lock() = ElementClickedState::default();
1034 cx.notify();
1035 }
1036 });
1037 } else {
1038 let active_group_bounds = self
1039 .group_active_style
1040 .as_ref()
1041 .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
1042 cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
1043 if phase == DispatchPhase::Bubble {
1044 let group = active_group_bounds
1045 .map_or(false, |bounds| bounds.contains_point(&down.position));
1046 let element = bounds.contains_point(&down.position);
1047 if group || element {
1048 *active_state.lock() = ElementClickedState { group, element };
1049 cx.notify();
1050 }
1051 }
1052 });
1053 }
1054
1055 let overflow = style.overflow;
1056 if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
1057 let scroll_offset = element_state
1058 .scroll_offset
1059 .get_or_insert_with(Arc::default)
1060 .clone();
1061 let line_height = cx.line_height();
1062 let scroll_max = (content_size - bounds.size).max(&Size::default());
1063
1064 cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
1065 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
1066 let mut scroll_offset = scroll_offset.lock();
1067 let old_scroll_offset = *scroll_offset;
1068 let delta = event.delta.pixel_delta(line_height);
1069
1070 if overflow.x == Overflow::Scroll {
1071 scroll_offset.x =
1072 (scroll_offset.x + delta.x).clamp(-scroll_max.width, px(0.));
1073 }
1074
1075 if overflow.y == Overflow::Scroll {
1076 scroll_offset.y =
1077 (scroll_offset.y + delta.y).clamp(-scroll_max.height, px(0.));
1078 }
1079
1080 if *scroll_offset != old_scroll_offset {
1081 cx.notify();
1082 cx.stop_propagation();
1083 }
1084 }
1085 });
1086 }
1087
1088 if let Some(group) = self.group.clone() {
1089 GroupBounds::push(group, bounds, cx);
1090 }
1091
1092 cx.with_key_dispatch(
1093 self.key_context.clone(),
1094 self.focus_handle.clone(),
1095 |_, cx| f(style, self.scroll_offset, cx),
1096 );
1097
1098 if let Some(group) = self.group.as_ref() {
1099 GroupBounds::pop(group, cx);
1100 }
1101 }
1102}
1103
1104impl<V: 'static> Default for Interactivity<V> {
1105 fn default() -> Self {
1106 Self {
1107 hovered: false,
1108 group_hovered: false,
1109 key_context: KeyContext::default(),
1110 focus_handle: None,
1111 scroll_offset: Point::default(),
1112 group: None,
1113 base_style: StyleRefinement::default(),
1114 focus_style: StyleRefinement::default(),
1115 focus_in_style: StyleRefinement::default(),
1116 in_focus_style: StyleRefinement::default(),
1117 hover_style: StyleRefinement::default(),
1118 group_hover_style: None,
1119 active_style: StyleRefinement::default(),
1120 group_active_style: None,
1121 drag_over_styles: SmallVec::new(),
1122 group_drag_over_styles: SmallVec::new(),
1123 mouse_down_listeners: SmallVec::new(),
1124 mouse_up_listeners: SmallVec::new(),
1125 mouse_move_listeners: SmallVec::new(),
1126 scroll_wheel_listeners: SmallVec::new(),
1127 key_down_listeners: SmallVec::new(),
1128 key_up_listeners: SmallVec::new(),
1129 action_listeners: SmallVec::new(),
1130 drop_listeners: SmallVec::new(),
1131 click_listeners: SmallVec::new(),
1132 drag_listener: None,
1133 hover_listener: None,
1134 tooltip_builder: None,
1135 focusable: todo!(),
1136 }
1137 }
1138}
1139
1140#[derive(Default)]
1141pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
1142
1143impl GroupBounds {
1144 pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
1145 cx.default_global::<Self>()
1146 .0
1147 .get(name)
1148 .and_then(|bounds_stack| bounds_stack.last())
1149 .cloned()
1150 }
1151
1152 pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
1153 cx.default_global::<Self>()
1154 .0
1155 .entry(name)
1156 .or_default()
1157 .push(bounds);
1158 }
1159
1160 pub fn pop(name: &SharedString, cx: &mut AppContext) {
1161 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
1162 }
1163}
1164
1165pub struct Focusable<V, E> {
1166 focusability: Focusability<V>,
1167 view_type: PhantomData<V>,
1168 element: E,
1169}
1170
1171pub struct Focusability<V> {
1172 focus_handle: Option<FocusHandle>,
1173 focus_listeners: FocusListeners<V>,
1174 focus_style: StyleRefinement,
1175 focus_in_style: StyleRefinement,
1176 in_focus_style: StyleRefinement,
1177}
1178
1179impl<V, E> FocusableComponent<V> for Focusable<V, E> {
1180 fn focusability(&mut self) -> &mut Focusability<V> {
1181 &mut self.focusability
1182 }
1183}
1184
1185impl<V, E> InteractiveComponent<V> for Focusable<V, E>
1186where
1187 V: 'static,
1188 E: InteractiveComponent<V>,
1189{
1190 fn interactivity(&mut self) -> &mut Interactivity<V> {
1191 self.element.interactivity()
1192 }
1193}
1194
1195impl<V: 'static, E: StatefulInteractiveComponent<V, E>> StatefulInteractiveComponent<V, E>
1196 for Focusable<V, E>
1197{
1198}
1199
1200impl<V, E> Element<V> for Focusable<V, E>
1201where
1202 V: 'static,
1203 E: Element<V>,
1204{
1205 type ElementState = E::ElementState;
1206
1207 fn id(&self) -> Option<crate::ElementId> {
1208 self.element.id()
1209 }
1210
1211 fn initialize(
1212 &mut self,
1213 view_state: &mut V,
1214 element_state: Option<Self::ElementState>,
1215 cx: &mut ViewContext<V>,
1216 ) -> Self::ElementState {
1217 todo!()
1218 }
1219
1220 fn layout(
1221 &mut self,
1222 view_state: &mut V,
1223 element_state: &mut Self::ElementState,
1224 cx: &mut ViewContext<V>,
1225 ) -> LayoutId {
1226 todo!()
1227 }
1228
1229 fn paint(
1230 &mut self,
1231 bounds: Bounds<Pixels>,
1232 view_state: &mut V,
1233 element_state: &mut Self::ElementState,
1234 cx: &mut ViewContext<V>,
1235 ) {
1236 todo!()
1237 }
1238}
1239
1240pub struct Stateful<V, E> {
1241 id: SharedString,
1242 view_type: PhantomData<V>,
1243 element: E,
1244}
1245
1246impl<V, E> StatefulInteractiveComponent<V, E> for Stateful<V, E>
1247where
1248 V: 'static,
1249 E: Element<V>,
1250 Self: InteractiveComponent<V>,
1251{
1252}
1253
1254impl<V, E> InteractiveComponent<V> for Stateful<V, E>
1255where
1256 V: 'static,
1257 E: InteractiveComponent<V>,
1258{
1259 fn interactivity(&mut self) -> &mut Interactivity<V> {
1260 self.element.interactivity()
1261 }
1262}
1263
1264impl<V, E: FocusableComponent<V>> FocusableComponent<V> for Stateful<V, E> {
1265 fn focusability(&mut self) -> &mut Focusability<V> {
1266 self.element.focusability()
1267 }
1268}
1269
1270impl<V, E> Element<V> for Stateful<V, E>
1271where
1272 V: 'static,
1273 E: Element<V>,
1274{
1275 type ElementState = InteractiveElementState;
1276
1277 fn id(&self) -> Option<crate::ElementId> {
1278 todo!()
1279 }
1280
1281 fn initialize(
1282 &mut self,
1283 view_state: &mut V,
1284 element_state: Option<Self::ElementState>,
1285 cx: &mut ViewContext<V>,
1286 ) -> Self::ElementState {
1287 todo!()
1288 }
1289
1290 fn layout(
1291 &mut self,
1292 view_state: &mut V,
1293 element_state: &mut Self::ElementState,
1294 cx: &mut ViewContext<V>,
1295 ) -> LayoutId {
1296 todo!()
1297 }
1298
1299 fn paint(
1300 &mut self,
1301 bounds: Bounds<Pixels>,
1302 view_state: &mut V,
1303 element_state: &mut Self::ElementState,
1304 cx: &mut ViewContext<V>,
1305 ) {
1306 todo!()
1307 }
1308}