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