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