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