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 element_state: Option<Self::ElementState>,
561 cx: &mut ViewContext<V>,
562 ) -> Self::ElementState {
563 let interactive_state =
564 self.interactivity
565 .initialize(element_state.map(|s| s.interactive_state), cx, |cx| {
566 for child in &mut self.children {
567 child.initialize(view_state, cx);
568 }
569 });
570
571 NodeState {
572 interactive_state,
573 child_layout_ids: SmallVec::new(),
574 }
575 }
576
577 fn layout(
578 &mut self,
579 view_state: &mut V,
580 element_state: &mut Self::ElementState,
581 cx: &mut ViewContext<V>,
582 ) -> crate::LayoutId {
583 let mut interactivity = mem::take(&mut self.interactivity);
584 let layout_id =
585 interactivity.layout(&mut element_state.interactive_state, cx, |style, cx| {
586 cx.with_text_style(style.text_style().cloned(), |cx| {
587 element_state.child_layout_ids = self
588 .children
589 .iter_mut()
590 .map(|child| child.layout(view_state, cx))
591 .collect::<SmallVec<_>>();
592 cx.request_layout(&style, element_state.child_layout_ids.iter().copied())
593 })
594 });
595 self.interactivity = interactivity;
596 layout_id
597 }
598
599 fn paint(
600 &mut self,
601 bounds: Bounds<Pixels>,
602 view_state: &mut V,
603 element_state: &mut Self::ElementState,
604 cx: &mut ViewContext<V>,
605 ) {
606 let mut interactivity = mem::take(&mut self.interactivity);
607
608 let mut child_min = point(Pixels::MAX, Pixels::MAX);
609 let mut child_max = Point::default();
610 let content_size = if element_state.child_layout_ids.is_empty() {
611 bounds.size
612 } else {
613 for child_layout_id in &element_state.child_layout_ids {
614 let child_bounds = cx.layout_bounds(*child_layout_id);
615 child_min = child_min.min(&child_bounds.origin);
616 child_max = child_max.max(&child_bounds.lower_right());
617 }
618 (child_max - child_min).into()
619 };
620
621 interactivity.paint(
622 bounds,
623 content_size,
624 &mut element_state.interactive_state,
625 cx,
626 |style, scroll_offset, cx| {
627 if style.visibility == Visibility::Hidden {
628 return;
629 }
630
631 let z_index = style.z_index.unwrap_or(0);
632
633 cx.with_z_index(z_index, |cx| {
634 cx.with_z_index(0, |cx| {
635 style.paint(bounds, cx);
636 });
637 cx.with_z_index(1, |cx| {
638 cx.with_text_style(style.text_style().cloned(), |cx| {
639 cx.with_content_mask(style.overflow_mask(bounds), |cx| {
640 cx.with_element_offset(scroll_offset, |cx| {
641 for child in &mut self.children {
642 child.paint(view_state, cx);
643 }
644 })
645 })
646 })
647 })
648 })
649 },
650 );
651 self.interactivity = interactivity;
652 }
653}
654
655pub struct NodeState {
656 child_layout_ids: SmallVec<[LayoutId; 4]>,
657 interactive_state: InteractiveElementState,
658}
659
660impl AsMut<InteractiveElementState> for InteractiveElementState {
661 fn as_mut(&mut self) -> &mut InteractiveElementState {
662 self
663 }
664}
665
666pub struct Interactivity<V> {
667 hovered: bool,
668 group_hovered: bool,
669 key_context: KeyContext,
670 tracked_focus_handle: Option<FocusHandle>,
671 focusable: bool,
672 scroll_offset: Point<Pixels>,
673 group: Option<SharedString>,
674 base_style: StyleRefinement,
675 focus_style: StyleRefinement,
676 focus_in_style: StyleRefinement,
677 in_focus_style: StyleRefinement,
678 hover_style: StyleRefinement,
679 group_hover_style: Option<GroupStyle>,
680 active_style: StyleRefinement,
681 group_active_style: Option<GroupStyle>,
682 drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
683 group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
684 mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
685 mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
686 mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
687 scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
688 key_down_listeners: SmallVec<[KeyDownListener<V>; 2]>,
689 key_up_listeners: SmallVec<[KeyUpListener<V>; 2]>,
690 action_listeners: SmallVec<[(TypeId, ActionListener<V>); 8]>,
691 drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
692 click_listeners: SmallVec<[ClickListener<V>; 2]>,
693 drag_listener: Option<DragListener<V>>,
694 hover_listener: Option<HoverListener<V>>,
695 tooltip_builder: Option<TooltipBuilder<V>>,
696}
697
698impl<V> Interactivity<V>
699where
700 V: 'static,
701{
702 fn initialize(
703 &mut self,
704 element_state: Option<InteractiveElementState>,
705 cx: &mut ViewContext<V>,
706 f: impl FnOnce(&mut ViewContext<V>),
707 ) -> InteractiveElementState {
708 let mut element_state = element_state.unwrap_or_default();
709 // Ensure we store a focus handle in our element state if we're focusable.
710 // If there's an explicit focus handle we're tracking, use that. Otherwise
711 // create a new handle and store it in the element state, which lives for as
712 // as frames contain an element with this id.
713 if self.focusable {
714 element_state.focus_handle.get_or_insert_with(|| {
715 self.tracked_focus_handle
716 .clone()
717 .unwrap_or_else(|| cx.focus_handle())
718 });
719 }
720 element_state
721 }
722
723 fn layout(
724 &mut self,
725 element_state: &mut InteractiveElementState,
726 cx: &mut ViewContext<V>,
727 f: impl FnOnce(Style, &mut ViewContext<V>) -> LayoutId,
728 ) -> LayoutId {
729 let style = self.compute_style(None, element_state, cx);
730 cx.with_key_dispatch(
731 self.key_context.clone(),
732 self.tracked_focus_handle.clone(),
733 |_, cx| f(style, cx),
734 )
735 }
736
737 fn paint(
738 &mut self,
739 bounds: Bounds<Pixels>,
740 content_size: Size<Pixels>,
741 element_state: &mut InteractiveElementState,
742 cx: &mut ViewContext<V>,
743 f: impl FnOnce(Style, Point<Pixels>, &mut ViewContext<V>),
744 ) {
745 let style = self.compute_style(Some(bounds), element_state, cx);
746
747 if let Some(mouse_cursor) = style.mouse_cursor {
748 let hovered = bounds.contains_point(&cx.mouse_position());
749 if hovered {
750 cx.set_cursor_style(mouse_cursor);
751 }
752 }
753
754 for listener in self.mouse_down_listeners.drain(..) {
755 cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
756 listener(state, event, &bounds, phase, cx);
757 })
758 }
759
760 for listener in self.mouse_up_listeners.drain(..) {
761 cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
762 listener(state, event, &bounds, phase, cx);
763 })
764 }
765
766 for listener in self.mouse_move_listeners.drain(..) {
767 cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
768 listener(state, event, &bounds, phase, cx);
769 })
770 }
771
772 for listener in self.scroll_wheel_listeners.drain(..) {
773 cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
774 listener(state, event, &bounds, phase, cx);
775 })
776 }
777
778 let hover_group_bounds = self
779 .group_hover_style
780 .as_ref()
781 .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
782
783 if let Some(group_bounds) = hover_group_bounds {
784 let hovered = group_bounds.contains_point(&cx.mouse_position());
785 cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
786 if phase == DispatchPhase::Capture {
787 if group_bounds.contains_point(&event.position) != hovered {
788 cx.notify();
789 }
790 }
791 });
792 }
793
794 if self.hover_style.is_some()
795 || (cx.active_drag.is_some() && !self.drag_over_styles.is_empty())
796 {
797 let hovered = bounds.contains_point(&cx.mouse_position());
798 cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
799 if phase == DispatchPhase::Capture {
800 if bounds.contains_point(&event.position) != hovered {
801 cx.notify();
802 }
803 }
804 });
805 }
806
807 if cx.active_drag.is_some() {
808 let drop_listeners = mem::take(&mut self.drop_listeners);
809 cx.on_mouse_event(move |view, event: &MouseUpEvent, phase, cx| {
810 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
811 if let Some(drag_state_type) =
812 cx.active_drag.as_ref().map(|drag| drag.view.entity_type())
813 {
814 for (drop_state_type, listener) in &drop_listeners {
815 if *drop_state_type == drag_state_type {
816 let drag = cx
817 .active_drag
818 .take()
819 .expect("checked for type drag state type above");
820 listener(view, drag.view.clone(), cx);
821 cx.notify();
822 cx.stop_propagation();
823 }
824 }
825 }
826 }
827 });
828 }
829
830 let click_listeners = mem::take(&mut self.click_listeners);
831 let drag_listener = mem::take(&mut self.drag_listener);
832
833 if !click_listeners.is_empty() || drag_listener.is_some() {
834 let pending_mouse_down = element_state.pending_mouse_down.clone();
835 let mouse_down = pending_mouse_down.lock().clone();
836 if let Some(mouse_down) = mouse_down {
837 if let Some(drag_listener) = drag_listener {
838 let active_state = element_state.clicked_state.clone();
839
840 cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
841 if cx.active_drag.is_some() {
842 if phase == DispatchPhase::Capture {
843 cx.notify();
844 }
845 } else if phase == DispatchPhase::Bubble
846 && bounds.contains_point(&event.position)
847 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
848 {
849 *active_state.lock() = ElementClickedState::default();
850 let cursor_offset = event.position - bounds.origin;
851 let drag = drag_listener(view_state, cursor_offset, cx);
852 cx.active_drag = Some(drag);
853 cx.notify();
854 cx.stop_propagation();
855 }
856 });
857 }
858
859 cx.on_mouse_event(move |view_state, event: &MouseUpEvent, phase, cx| {
860 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
861 let mouse_click = ClickEvent {
862 down: mouse_down.clone(),
863 up: event.clone(),
864 };
865 for listener in &click_listeners {
866 listener(view_state, &mouse_click, cx);
867 }
868 }
869 *pending_mouse_down.lock() = None;
870 });
871 } else {
872 cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
873 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
874 *pending_mouse_down.lock() = Some(event.clone());
875 }
876 });
877 }
878 }
879
880 if let Some(hover_listener) = self.hover_listener.take() {
881 let was_hovered = element_state.hover_state.clone();
882 let has_mouse_down = element_state.pending_mouse_down.clone();
883
884 cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
885 if phase != DispatchPhase::Bubble {
886 return;
887 }
888 let is_hovered =
889 bounds.contains_point(&event.position) && has_mouse_down.lock().is_none();
890 let mut was_hovered = was_hovered.lock();
891
892 if is_hovered != was_hovered.clone() {
893 *was_hovered = is_hovered;
894 drop(was_hovered);
895
896 hover_listener(view_state, is_hovered, cx);
897 }
898 });
899 }
900
901 if let Some(tooltip_builder) = self.tooltip_builder.take() {
902 let active_tooltip = element_state.active_tooltip.clone();
903 let pending_mouse_down = element_state.pending_mouse_down.clone();
904
905 cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
906 if phase != DispatchPhase::Bubble {
907 return;
908 }
909
910 let is_hovered =
911 bounds.contains_point(&event.position) && pending_mouse_down.lock().is_none();
912 if !is_hovered {
913 active_tooltip.lock().take();
914 return;
915 }
916
917 if active_tooltip.lock().is_none() {
918 let task = cx.spawn({
919 let active_tooltip = active_tooltip.clone();
920 let tooltip_builder = tooltip_builder.clone();
921
922 move |view, mut cx| async move {
923 cx.background_executor().timer(TOOLTIP_DELAY).await;
924 view.update(&mut cx, move |view_state, cx| {
925 active_tooltip.lock().replace(ActiveTooltip {
926 waiting: None,
927 tooltip: Some(AnyTooltip {
928 view: tooltip_builder(view_state, cx),
929 cursor_offset: cx.mouse_position() + TOOLTIP_OFFSET,
930 }),
931 });
932 cx.notify();
933 })
934 .ok();
935 }
936 });
937 active_tooltip.lock().replace(ActiveTooltip {
938 waiting: Some(task),
939 tooltip: None,
940 });
941 }
942 });
943
944 if let Some(active_tooltip) = element_state.active_tooltip.lock().as_ref() {
945 if active_tooltip.tooltip.is_some() {
946 cx.active_tooltip = active_tooltip.tooltip.clone()
947 }
948 }
949 }
950
951 let active_state = element_state.clicked_state.clone();
952 if !active_state.lock().is_clicked() {
953 cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
954 if phase == DispatchPhase::Capture {
955 *active_state.lock() = ElementClickedState::default();
956 cx.notify();
957 }
958 });
959 } else {
960 let active_group_bounds = self
961 .group_active_style
962 .as_ref()
963 .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
964 cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
965 if phase == DispatchPhase::Bubble {
966 let group = active_group_bounds
967 .map_or(false, |bounds| bounds.contains_point(&down.position));
968 let element = bounds.contains_point(&down.position);
969 if group || element {
970 *active_state.lock() = ElementClickedState { group, element };
971 cx.notify();
972 }
973 }
974 });
975 }
976
977 let overflow = style.overflow;
978 if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
979 let scroll_offset = element_state
980 .scroll_offset
981 .get_or_insert_with(Arc::default)
982 .clone();
983 let line_height = cx.line_height();
984 let scroll_max = (content_size - bounds.size).max(&Size::default());
985
986 cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
987 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
988 let mut scroll_offset = scroll_offset.lock();
989 let old_scroll_offset = *scroll_offset;
990 let delta = event.delta.pixel_delta(line_height);
991
992 if overflow.x == Overflow::Scroll {
993 scroll_offset.x =
994 (scroll_offset.x + delta.x).clamp(-scroll_max.width, px(0.));
995 }
996
997 if overflow.y == Overflow::Scroll {
998 scroll_offset.y =
999 (scroll_offset.y + delta.y).clamp(-scroll_max.height, px(0.));
1000 }
1001
1002 if *scroll_offset != old_scroll_offset {
1003 cx.notify();
1004 cx.stop_propagation();
1005 }
1006 }
1007 });
1008 }
1009
1010 if let Some(group) = self.group.clone() {
1011 GroupBounds::push(group, bounds, cx);
1012 }
1013
1014 cx.with_key_dispatch(
1015 self.key_context.clone(),
1016 self.tracked_focus_handle.clone(),
1017 |_, cx| {
1018 for listener in self.key_down_listeners.drain(..) {
1019 cx.on_key_event(move |state, event: &KeyDownEvent, phase, cx| {
1020 listener(state, event, phase, cx);
1021 })
1022 }
1023
1024 for listener in self.key_up_listeners.drain(..) {
1025 cx.on_key_event(move |state, event: &KeyUpEvent, phase, cx| {
1026 listener(state, event, phase, cx);
1027 })
1028 }
1029
1030 for (action_type, listener) in self.action_listeners.drain(..) {
1031 cx.on_action(action_type, listener)
1032 }
1033
1034 f(style, self.scroll_offset, cx)
1035 },
1036 );
1037
1038 if let Some(group) = self.group.as_ref() {
1039 GroupBounds::pop(group, cx);
1040 }
1041 }
1042
1043 fn compute_style(
1044 &self,
1045 bounds: Option<Bounds<Pixels>>,
1046 element_state: &mut InteractiveElementState,
1047 cx: &mut ViewContext<V>,
1048 ) -> Style {
1049 let mut style = Style::default();
1050 style.refine(&self.base_style);
1051
1052 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1053 if focus_handle.contains_focused(cx) {
1054 style.refine(&self.focus_in_style);
1055 }
1056
1057 if focus_handle.within_focused(cx) {
1058 style.refine(&self.in_focus_style);
1059 }
1060
1061 if focus_handle.is_focused(cx) {
1062 style.refine(&self.focus_style);
1063 }
1064 }
1065
1066 if let Some(bounds) = bounds {
1067 let mouse_position = cx.mouse_position();
1068 if let Some(group_hover) = self.group_hover_style.as_ref() {
1069 if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
1070 if group_bounds.contains_point(&mouse_position) {
1071 style.refine(&group_hover.style);
1072 }
1073 }
1074 }
1075 if bounds.contains_point(&mouse_position) {
1076 style.refine(&self.hover_style);
1077 }
1078
1079 if let Some(drag) = cx.active_drag.take() {
1080 for (state_type, group_drag_style) in &self.group_drag_over_styles {
1081 if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
1082 if *state_type == drag.view.entity_type()
1083 && group_bounds.contains_point(&mouse_position)
1084 {
1085 style.refine(&group_drag_style.style);
1086 }
1087 }
1088 }
1089
1090 for (state_type, drag_over_style) in &self.drag_over_styles {
1091 if *state_type == drag.view.entity_type()
1092 && bounds.contains_point(&mouse_position)
1093 {
1094 style.refine(drag_over_style);
1095 }
1096 }
1097
1098 cx.active_drag = Some(drag);
1099 }
1100 }
1101
1102 let clicked_state = element_state.clicked_state.lock();
1103 if clicked_state.group {
1104 if let Some(group) = self.group_active_style.as_ref() {
1105 style.refine(&group.style)
1106 }
1107 }
1108
1109 if clicked_state.element {
1110 style.refine(&self.active_style)
1111 }
1112
1113 style
1114 }
1115}
1116
1117impl<V: 'static> Default for Interactivity<V> {
1118 fn default() -> Self {
1119 Self {
1120 hovered: false,
1121 group_hovered: false,
1122 key_context: KeyContext::default(),
1123 tracked_focus_handle: None,
1124 scroll_offset: Point::default(),
1125 group: None,
1126 base_style: StyleRefinement::default(),
1127 focus_style: StyleRefinement::default(),
1128 focus_in_style: StyleRefinement::default(),
1129 in_focus_style: StyleRefinement::default(),
1130 hover_style: StyleRefinement::default(),
1131 group_hover_style: None,
1132 active_style: StyleRefinement::default(),
1133 group_active_style: None,
1134 drag_over_styles: SmallVec::new(),
1135 group_drag_over_styles: SmallVec::new(),
1136 mouse_down_listeners: SmallVec::new(),
1137 mouse_up_listeners: SmallVec::new(),
1138 mouse_move_listeners: SmallVec::new(),
1139 scroll_wheel_listeners: SmallVec::new(),
1140 key_down_listeners: SmallVec::new(),
1141 key_up_listeners: SmallVec::new(),
1142 action_listeners: SmallVec::new(),
1143 drop_listeners: SmallVec::new(),
1144 click_listeners: SmallVec::new(),
1145 drag_listener: None,
1146 hover_listener: None,
1147 tooltip_builder: None,
1148 focusable: false,
1149 }
1150 }
1151}
1152
1153#[derive(Default)]
1154pub struct InteractiveElementState {
1155 focus_handle: Option<FocusHandle>,
1156 clicked_state: Arc<Mutex<ElementClickedState>>,
1157 hover_state: Arc<Mutex<bool>>,
1158 pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
1159 scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
1160 active_tooltip: Arc<Mutex<Option<ActiveTooltip>>>,
1161}
1162
1163struct ActiveTooltip {
1164 #[allow(unused)] // used to drop the task
1165 waiting: Option<Task<()>>,
1166 tooltip: Option<AnyTooltip>,
1167}
1168
1169/// Whether or not the element or a group that contains it is clicked by the mouse.
1170#[derive(Copy, Clone, Default, Eq, PartialEq)]
1171struct ElementClickedState {
1172 pub group: bool,
1173 pub element: bool,
1174}
1175
1176impl ElementClickedState {
1177 fn is_clicked(&self) -> bool {
1178 self.group || self.element
1179 }
1180}
1181
1182#[derive(Default)]
1183pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
1184
1185impl GroupBounds {
1186 pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
1187 cx.default_global::<Self>()
1188 .0
1189 .get(name)
1190 .and_then(|bounds_stack| bounds_stack.last())
1191 .cloned()
1192 }
1193
1194 pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
1195 cx.default_global::<Self>()
1196 .0
1197 .entry(name)
1198 .or_default()
1199 .push(bounds);
1200 }
1201
1202 pub fn pop(name: &SharedString, cx: &mut AppContext) {
1203 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
1204 }
1205}
1206
1207pub struct Focusable<V, E> {
1208 focusability: Focusability<V>,
1209 view_type: PhantomData<V>,
1210 element: E,
1211}
1212
1213pub struct Focusability<V> {
1214 focus_handle: Option<FocusHandle>,
1215 focus_listeners: FocusListeners<V>,
1216 focus_style: StyleRefinement,
1217 focus_in_style: StyleRefinement,
1218 in_focus_style: StyleRefinement,
1219}
1220
1221impl<V, E> FocusableComponent<V> for Focusable<V, E> {
1222 fn focusability(&mut self) -> &mut Focusability<V> {
1223 &mut self.focusability
1224 }
1225}
1226
1227impl<V, E> InteractiveComponent<V> for Focusable<V, E>
1228where
1229 V: 'static,
1230 E: InteractiveComponent<V>,
1231{
1232 fn interactivity(&mut self) -> &mut Interactivity<V> {
1233 self.element.interactivity()
1234 }
1235}
1236
1237impl<V: 'static, E: StatefulInteractiveComponent<V, E>> StatefulInteractiveComponent<V, E>
1238 for Focusable<V, E>
1239{
1240}
1241
1242impl<V, E> Element<V> for Focusable<V, E>
1243where
1244 V: 'static,
1245 E: Element<V>,
1246{
1247 type ElementState = E::ElementState;
1248
1249 fn id(&self) -> Option<crate::ElementId> {
1250 self.element.id()
1251 }
1252
1253 fn initialize(
1254 &mut self,
1255 view_state: &mut V,
1256 element_state: Option<Self::ElementState>,
1257 cx: &mut ViewContext<V>,
1258 ) -> Self::ElementState {
1259 todo!()
1260 }
1261
1262 fn layout(
1263 &mut self,
1264 view_state: &mut V,
1265 element_state: &mut Self::ElementState,
1266 cx: &mut ViewContext<V>,
1267 ) -> LayoutId {
1268 todo!()
1269 }
1270
1271 fn paint(
1272 &mut self,
1273 bounds: Bounds<Pixels>,
1274 view_state: &mut V,
1275 element_state: &mut Self::ElementState,
1276 cx: &mut ViewContext<V>,
1277 ) {
1278 todo!()
1279 }
1280}
1281
1282pub struct Stateful<V, E> {
1283 id: SharedString,
1284 view_type: PhantomData<V>,
1285 element: E,
1286}
1287
1288impl<V, E> StatefulInteractiveComponent<V, E> for Stateful<V, E>
1289where
1290 V: 'static,
1291 E: Element<V>,
1292 Self: InteractiveComponent<V>,
1293{
1294}
1295
1296impl<V, E> InteractiveComponent<V> for Stateful<V, E>
1297where
1298 V: 'static,
1299 E: InteractiveComponent<V>,
1300{
1301 fn interactivity(&mut self) -> &mut Interactivity<V> {
1302 self.element.interactivity()
1303 }
1304}
1305
1306impl<V, E: FocusableComponent<V>> FocusableComponent<V> for Stateful<V, E> {
1307 fn focusability(&mut self) -> &mut Focusability<V> {
1308 self.element.focusability()
1309 }
1310}
1311
1312impl<V, E> Element<V> for Stateful<V, E>
1313where
1314 V: 'static,
1315 E: Element<V>,
1316{
1317 type ElementState = InteractiveElementState;
1318
1319 fn id(&self) -> Option<crate::ElementId> {
1320 todo!()
1321 }
1322
1323 fn initialize(
1324 &mut self,
1325 view_state: &mut V,
1326 element_state: Option<Self::ElementState>,
1327 cx: &mut ViewContext<V>,
1328 ) -> Self::ElementState {
1329 todo!()
1330 }
1331
1332 fn layout(
1333 &mut self,
1334 view_state: &mut V,
1335 element_state: &mut Self::ElementState,
1336 cx: &mut ViewContext<V>,
1337 ) -> LayoutId {
1338 todo!()
1339 }
1340
1341 fn paint(
1342 &mut self,
1343 bounds: Bounds<Pixels>,
1344 view_state: &mut V,
1345 element_state: &mut Self::ElementState,
1346 cx: &mut ViewContext<V>,
1347 ) {
1348 todo!()
1349 }
1350}