div.rs

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