div.rs

   1//! Div is the central, reusable element that most GPUI trees will be built from.
   2//! It functions as a container for other elements, and provides a number of
   3//! useful features for laying out and styling its children as well as binding
   4//! mouse events and action handlers. It is meant to be similar to the HTML `<div>`
   5//! element, but for GPUI.
   6//!
   7//! # Build your own div
   8//!
   9//! GPUI does not directly provide APIs for stateful, multi step events like `click`
  10//! and `drag`. We want GPUI users to be able to build their own abstractions for
  11//! their own needs. However, as a UI framework, we're also obliged to provide some
  12//! building blocks to make the process of building your own elements easier.
  13//! For this we have the [`Interactivity`] and the [`StyleRefinement`] structs, as well
  14//! as several associated traits. Together, these provide the full suite of Dom-like events
  15//! and Tailwind-like styling that you can use to build your own custom elements. Div is
  16//! constructed by combining these two systems into an all-in-one element.
  17
  18use crate::{
  19    AbsoluteLength, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent,
  20    DispatchPhase, Element, ElementId, Entity, FocusHandle, Global, GlobalElementId, Hitbox,
  21    HitboxBehavior, HitboxId, InspectorElementId, IntoElement, IsZero, KeyContext, KeyDownEvent,
  22    KeyUpEvent, KeyboardButton, KeyboardClickEvent, LayoutId, ModifiersChangedEvent, MouseButton,
  23    MouseClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Overflow, ParentElement, Pixels,
  24    Point, Render, ScrollWheelEvent, SharedString, Size, Style, StyleRefinement, Styled, Task,
  25    TooltipId, Visibility, Window, WindowControlArea, point, px, size,
  26};
  27use collections::HashMap;
  28use refineable::Refineable;
  29use smallvec::SmallVec;
  30use stacksafe::{StackSafe, stacksafe};
  31use std::{
  32    any::{Any, TypeId},
  33    cell::RefCell,
  34    cmp::Ordering,
  35    fmt::Debug,
  36    marker::PhantomData,
  37    mem,
  38    rc::Rc,
  39    sync::Arc,
  40    time::Duration,
  41};
  42use util::ResultExt;
  43
  44use super::ImageCacheProvider;
  45
  46const DRAG_THRESHOLD: f64 = 2.;
  47const TOOLTIP_SHOW_DELAY: Duration = Duration::from_millis(500);
  48const HOVERABLE_TOOLTIP_HIDE_DELAY: Duration = Duration::from_millis(500);
  49
  50/// The styling information for a given group.
  51pub struct GroupStyle {
  52    /// The identifier for this group.
  53    pub group: SharedString,
  54
  55    /// The specific style refinement that this group would apply
  56    /// to its children.
  57    pub style: Box<StyleRefinement>,
  58}
  59
  60/// An event for when a drag is moving over this element, with the given state type.
  61pub struct DragMoveEvent<T> {
  62    /// The mouse move event that triggered this drag move event.
  63    pub event: MouseMoveEvent,
  64
  65    /// The bounds of this element.
  66    pub bounds: Bounds<Pixels>,
  67    drag: PhantomData<T>,
  68    dragged_item: Arc<dyn Any>,
  69}
  70
  71impl<T: 'static> DragMoveEvent<T> {
  72    /// Returns the drag state for this event.
  73    pub fn drag<'b>(&self, cx: &'b App) -> &'b T {
  74        cx.active_drag
  75            .as_ref()
  76            .and_then(|drag| drag.value.downcast_ref::<T>())
  77            .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
  78    }
  79
  80    /// An item that is about to be dropped.
  81    pub fn dragged_item(&self) -> &dyn Any {
  82        self.dragged_item.as_ref()
  83    }
  84}
  85
  86impl Interactivity {
  87    /// Create an `Interactivity`, capturing the caller location in debug mode.
  88    #[cfg(any(feature = "inspector", debug_assertions))]
  89    #[track_caller]
  90    pub fn new() -> Interactivity {
  91        Interactivity {
  92            source_location: Some(core::panic::Location::caller()),
  93            ..Default::default()
  94        }
  95    }
  96
  97    /// Create an `Interactivity`, capturing the caller location in debug mode.
  98    #[cfg(not(any(feature = "inspector", debug_assertions)))]
  99    pub fn new() -> Interactivity {
 100        Interactivity::default()
 101    }
 102
 103    /// Gets the source location of construction. Returns `None` when not in debug mode.
 104    pub fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
 105        #[cfg(any(feature = "inspector", debug_assertions))]
 106        {
 107            self.source_location
 108        }
 109
 110        #[cfg(not(any(feature = "inspector", debug_assertions)))]
 111        {
 112            None
 113        }
 114    }
 115
 116    /// Bind the given callback to the mouse down event for the given mouse button, during the bubble phase
 117    /// The imperative API equivalent of [`InteractiveElement::on_mouse_down`]
 118    ///
 119    /// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
 120    pub fn on_mouse_down(
 121        &mut self,
 122        button: MouseButton,
 123        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
 124    ) {
 125        self.mouse_down_listeners
 126            .push(Box::new(move |event, phase, hitbox, window, cx| {
 127                if phase == DispatchPhase::Bubble
 128                    && event.button == button
 129                    && hitbox.is_hovered(window)
 130                {
 131                    (listener)(event, window, cx)
 132                }
 133            }));
 134    }
 135
 136    /// Bind the given callback to the mouse down event for any button, during the capture phase
 137    /// The imperative API equivalent of [`InteractiveElement::capture_any_mouse_down`]
 138    ///
 139    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 140    pub fn capture_any_mouse_down(
 141        &mut self,
 142        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
 143    ) {
 144        self.mouse_down_listeners
 145            .push(Box::new(move |event, phase, hitbox, window, cx| {
 146                if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
 147                    (listener)(event, window, cx)
 148                }
 149            }));
 150    }
 151
 152    /// Bind the given callback to the mouse down event for any button, during the bubble phase
 153    /// the imperative API equivalent to [`InteractiveElement::on_any_mouse_down`]
 154    ///
 155    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 156    pub fn on_any_mouse_down(
 157        &mut self,
 158        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
 159    ) {
 160        self.mouse_down_listeners
 161            .push(Box::new(move |event, phase, hitbox, window, cx| {
 162                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
 163                    (listener)(event, window, cx)
 164                }
 165            }));
 166    }
 167
 168    /// Bind the given callback to the mouse up event for the given button, during the bubble phase
 169    /// the imperative API equivalent to [`InteractiveElement::on_mouse_up`]
 170    ///
 171    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 172    pub fn on_mouse_up(
 173        &mut self,
 174        button: MouseButton,
 175        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
 176    ) {
 177        self.mouse_up_listeners
 178            .push(Box::new(move |event, phase, hitbox, window, cx| {
 179                if phase == DispatchPhase::Bubble
 180                    && event.button == button
 181                    && hitbox.is_hovered(window)
 182                {
 183                    (listener)(event, window, cx)
 184                }
 185            }));
 186    }
 187
 188    /// Bind the given callback to the mouse up event for any button, during the capture phase
 189    /// the imperative API equivalent to [`InteractiveElement::capture_any_mouse_up`]
 190    ///
 191    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 192    pub fn capture_any_mouse_up(
 193        &mut self,
 194        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
 195    ) {
 196        self.mouse_up_listeners
 197            .push(Box::new(move |event, phase, hitbox, window, cx| {
 198                if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
 199                    (listener)(event, window, cx)
 200                }
 201            }));
 202    }
 203
 204    /// Bind the given callback to the mouse up event for any button, during the bubble phase
 205    /// the imperative API equivalent to [`Interactivity::on_any_mouse_up`]
 206    ///
 207    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 208    pub fn on_any_mouse_up(
 209        &mut self,
 210        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
 211    ) {
 212        self.mouse_up_listeners
 213            .push(Box::new(move |event, phase, hitbox, window, cx| {
 214                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
 215                    (listener)(event, window, cx)
 216                }
 217            }));
 218    }
 219
 220    /// Bind the given callback to the mouse down event, on any button, during the capture phase,
 221    /// when the mouse is outside of the bounds of this element.
 222    /// The imperative API equivalent to [`InteractiveElement::on_mouse_down_out`]
 223    ///
 224    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 225    pub fn on_mouse_down_out(
 226        &mut self,
 227        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
 228    ) {
 229        self.mouse_down_listeners
 230            .push(Box::new(move |event, phase, hitbox, window, cx| {
 231                if phase == DispatchPhase::Capture && !hitbox.contains(&window.mouse_position()) {
 232                    (listener)(event, window, cx)
 233                }
 234            }));
 235    }
 236
 237    /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
 238    /// when the mouse is outside of the bounds of this element.
 239    /// The imperative API equivalent to [`InteractiveElement::on_mouse_up_out`]
 240    ///
 241    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 242    pub fn on_mouse_up_out(
 243        &mut self,
 244        button: MouseButton,
 245        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
 246    ) {
 247        self.mouse_up_listeners
 248            .push(Box::new(move |event, phase, hitbox, window, cx| {
 249                if phase == DispatchPhase::Capture
 250                    && event.button == button
 251                    && !hitbox.is_hovered(window)
 252                {
 253                    (listener)(event, window, cx);
 254                }
 255            }));
 256    }
 257
 258    /// Bind the given callback to the mouse move event, during the bubble phase
 259    /// The imperative API equivalent to [`InteractiveElement::on_mouse_move`]
 260    ///
 261    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 262    pub fn on_mouse_move(
 263        &mut self,
 264        listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
 265    ) {
 266        self.mouse_move_listeners
 267            .push(Box::new(move |event, phase, hitbox, window, cx| {
 268                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
 269                    (listener)(event, window, cx);
 270                }
 271            }));
 272    }
 273
 274    /// Bind the given callback to the mouse drag event of the given type. Note that this
 275    /// will be called for all move events, inside or outside of this element, as long as the
 276    /// drag was started with this element under the mouse. Useful for implementing draggable
 277    /// UIs that don't conform to a drag and drop style interaction, like resizing.
 278    /// The imperative API equivalent to [`InteractiveElement::on_drag_move`]
 279    ///
 280    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 281    pub fn on_drag_move<T>(
 282        &mut self,
 283        listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
 284    ) where
 285        T: 'static,
 286    {
 287        self.mouse_move_listeners
 288            .push(Box::new(move |event, phase, hitbox, window, cx| {
 289                if phase == DispatchPhase::Capture
 290                    && let Some(drag) = &cx.active_drag
 291                    && drag.value.as_ref().type_id() == TypeId::of::<T>()
 292                {
 293                    (listener)(
 294                        &DragMoveEvent {
 295                            event: event.clone(),
 296                            bounds: hitbox.bounds,
 297                            drag: PhantomData,
 298                            dragged_item: Arc::clone(&drag.value),
 299                        },
 300                        window,
 301                        cx,
 302                    );
 303                }
 304            }));
 305    }
 306
 307    /// Bind the given callback to scroll wheel events during the bubble phase
 308    /// The imperative API equivalent to [`InteractiveElement::on_scroll_wheel`]
 309    ///
 310    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 311    pub fn on_scroll_wheel(
 312        &mut self,
 313        listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
 314    ) {
 315        self.scroll_wheel_listeners
 316            .push(Box::new(move |event, phase, hitbox, window, cx| {
 317                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
 318                    (listener)(event, window, cx);
 319                }
 320            }));
 321    }
 322
 323    /// Bind the given callback to an action dispatch during the capture phase
 324    /// The imperative API equivalent to [`InteractiveElement::capture_action`]
 325    ///
 326    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 327    pub fn capture_action<A: Action>(
 328        &mut self,
 329        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
 330    ) {
 331        self.action_listeners.push((
 332            TypeId::of::<A>(),
 333            Box::new(move |action, phase, window, cx| {
 334                let action = action.downcast_ref().unwrap();
 335                if phase == DispatchPhase::Capture {
 336                    (listener)(action, window, cx)
 337                } else {
 338                    cx.propagate();
 339                }
 340            }),
 341        ));
 342    }
 343
 344    /// Bind the given callback to an action dispatch during the bubble phase
 345    /// The imperative API equivalent to [`InteractiveElement::on_action`]
 346    ///
 347    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 348    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
 349        self.action_listeners.push((
 350            TypeId::of::<A>(),
 351            Box::new(move |action, phase, window, cx| {
 352                let action = action.downcast_ref().unwrap();
 353                if phase == DispatchPhase::Bubble {
 354                    (listener)(action, window, cx)
 355                }
 356            }),
 357        ));
 358    }
 359
 360    /// Bind the given callback to an action dispatch, based on a dynamic action parameter
 361    /// instead of a type parameter. Useful for component libraries that want to expose
 362    /// action bindings to their users.
 363    /// The imperative API equivalent to [`InteractiveElement::on_boxed_action`]
 364    ///
 365    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 366    pub fn on_boxed_action(
 367        &mut self,
 368        action: &dyn Action,
 369        listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
 370    ) {
 371        let action = action.boxed_clone();
 372        self.action_listeners.push((
 373            (*action).type_id(),
 374            Box::new(move |_, phase, window, cx| {
 375                if phase == DispatchPhase::Bubble {
 376                    (listener)(&*action, window, cx)
 377                }
 378            }),
 379        ));
 380    }
 381
 382    /// Bind the given callback to key down events during the bubble phase
 383    /// The imperative API equivalent to [`InteractiveElement::on_key_down`]
 384    ///
 385    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 386    pub fn on_key_down(
 387        &mut self,
 388        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
 389    ) {
 390        self.key_down_listeners
 391            .push(Box::new(move |event, phase, window, cx| {
 392                if phase == DispatchPhase::Bubble {
 393                    (listener)(event, window, cx)
 394                }
 395            }));
 396    }
 397
 398    /// Bind the given callback to key down events during the capture phase
 399    /// The imperative API equivalent to [`InteractiveElement::capture_key_down`]
 400    ///
 401    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 402    pub fn capture_key_down(
 403        &mut self,
 404        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
 405    ) {
 406        self.key_down_listeners
 407            .push(Box::new(move |event, phase, window, cx| {
 408                if phase == DispatchPhase::Capture {
 409                    listener(event, window, cx)
 410                }
 411            }));
 412    }
 413
 414    /// Bind the given callback to key up events during the bubble phase
 415    /// The imperative API equivalent to [`InteractiveElement::on_key_up`]
 416    ///
 417    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 418    pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
 419        self.key_up_listeners
 420            .push(Box::new(move |event, phase, window, cx| {
 421                if phase == DispatchPhase::Bubble {
 422                    listener(event, window, cx)
 423                }
 424            }));
 425    }
 426
 427    /// Bind the given callback to key up events during the capture phase
 428    /// The imperative API equivalent to [`InteractiveElement::on_key_up`]
 429    ///
 430    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 431    pub fn capture_key_up(
 432        &mut self,
 433        listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
 434    ) {
 435        self.key_up_listeners
 436            .push(Box::new(move |event, phase, window, cx| {
 437                if phase == DispatchPhase::Capture {
 438                    listener(event, window, cx)
 439                }
 440            }));
 441    }
 442
 443    /// Bind the given callback to modifiers changing events.
 444    /// The imperative API equivalent to [`InteractiveElement::on_modifiers_changed`]
 445    ///
 446    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 447    pub fn on_modifiers_changed(
 448        &mut self,
 449        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
 450    ) {
 451        self.modifiers_changed_listeners
 452            .push(Box::new(move |event, window, cx| {
 453                listener(event, window, cx)
 454            }));
 455    }
 456
 457    /// Bind the given callback to drop events of the given type, whether or not the drag started on this element
 458    /// The imperative API equivalent to [`InteractiveElement::on_drop`]
 459    ///
 460    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 461    pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
 462        self.drop_listeners.push((
 463            TypeId::of::<T>(),
 464            Box::new(move |dragged_value, window, cx| {
 465                listener(dragged_value.downcast_ref().unwrap(), window, cx);
 466            }),
 467        ));
 468    }
 469
 470    /// Use the given predicate to determine whether or not a drop event should be dispatched to this element
 471    /// The imperative API equivalent to [`InteractiveElement::can_drop`]
 472    pub fn can_drop(
 473        &mut self,
 474        predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
 475    ) {
 476        self.can_drop_predicate = Some(Box::new(predicate));
 477    }
 478
 479    /// Bind the given callback to click events of this element
 480    /// The imperative API equivalent to [`StatefulInteractiveElement::on_click`]
 481    ///
 482    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 483    pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
 484    where
 485        Self: Sized,
 486    {
 487        self.click_listeners.push(Rc::new(move |event, window, cx| {
 488            listener(event, window, cx)
 489        }));
 490    }
 491
 492    /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
 493    /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
 494    /// the [`Self::on_drag_move`] API
 495    /// The imperative API equivalent to [`StatefulInteractiveElement::on_drag`]
 496    ///
 497    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 498    pub fn on_drag<T, W>(
 499        &mut self,
 500        value: T,
 501        constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
 502    ) where
 503        Self: Sized,
 504        T: 'static,
 505        W: 'static + Render,
 506    {
 507        debug_assert!(
 508            self.drag_listener.is_none(),
 509            "calling on_drag more than once on the same element is not supported"
 510        );
 511        self.drag_listener = Some((
 512            Arc::new(value),
 513            Box::new(move |value, offset, window, cx| {
 514                constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
 515            }),
 516        ));
 517    }
 518
 519    /// Bind the given callback on the hover start and end events of this element. Note that the boolean
 520    /// passed to the callback is true when the hover starts and false when it ends.
 521    /// The imperative API equivalent to [`StatefulInteractiveElement::on_hover`]
 522    ///
 523    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 524    pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
 525    where
 526        Self: Sized,
 527    {
 528        debug_assert!(
 529            self.hover_listener.is_none(),
 530            "calling on_hover more than once on the same element is not supported"
 531        );
 532        self.hover_listener = Some(Box::new(listener));
 533    }
 534
 535    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
 536    /// The imperative API equivalent to [`StatefulInteractiveElement::tooltip`]
 537    pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
 538    where
 539        Self: Sized,
 540    {
 541        debug_assert!(
 542            self.tooltip_builder.is_none(),
 543            "calling tooltip more than once on the same element is not supported"
 544        );
 545        self.tooltip_builder = Some(TooltipBuilder {
 546            build: Rc::new(build_tooltip),
 547            hoverable: false,
 548        });
 549    }
 550
 551    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
 552    /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
 553    /// the tooltip. The imperative API equivalent to [`StatefulInteractiveElement::hoverable_tooltip`]
 554    pub fn hoverable_tooltip(
 555        &mut self,
 556        build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
 557    ) where
 558        Self: Sized,
 559    {
 560        debug_assert!(
 561            self.tooltip_builder.is_none(),
 562            "calling tooltip more than once on the same element is not supported"
 563        );
 564        self.tooltip_builder = Some(TooltipBuilder {
 565            build: Rc::new(build_tooltip),
 566            hoverable: true,
 567        });
 568    }
 569
 570    /// Block the mouse from all interactions with elements behind this element's hitbox. Typically
 571    /// `block_mouse_except_scroll` should be preferred.
 572    ///
 573    /// The imperative API equivalent to [`InteractiveElement::occlude`]
 574    pub fn occlude_mouse(&mut self) {
 575        self.hitbox_behavior = HitboxBehavior::BlockMouse;
 576    }
 577
 578    /// Set the bounds of this element as a window control area for the platform window.
 579    /// The imperative API equivalent to [`InteractiveElement::window_control_area`]
 580    pub fn window_control_area(&mut self, area: WindowControlArea) {
 581        self.window_control = Some(area);
 582    }
 583
 584    /// Block non-scroll mouse interactions with elements behind this element's hitbox. See
 585    /// [`Hitbox::is_hovered`] for details.
 586    ///
 587    /// The imperative API equivalent to [`InteractiveElement::block_mouse_except_scroll`]
 588    pub fn block_mouse_except_scroll(&mut self) {
 589        self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
 590    }
 591}
 592
 593/// A trait for elements that want to use the standard GPUI event handlers that don't
 594/// require any state.
 595pub trait InteractiveElement: Sized {
 596    /// Retrieve the interactivity state associated with this element
 597    fn interactivity(&mut self) -> &mut Interactivity;
 598
 599    /// Assign this element to a group of elements that can be styled together
 600    fn group(mut self, group: impl Into<SharedString>) -> Self {
 601        self.interactivity().group = Some(group.into());
 602        self
 603    }
 604
 605    /// Assign this element an ID, so that it can be used with interactivity
 606    fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
 607        self.interactivity().element_id = Some(id.into());
 608
 609        Stateful { element: self }
 610    }
 611
 612    /// Track the focus state of the given focus handle on this element.
 613    /// If the focus handle is focused by the application, this element will
 614    /// apply its focused styles.
 615    fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
 616        self.interactivity().focusable = true;
 617        self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
 618        self
 619    }
 620
 621    /// Designate this element as a tab stop, equivalent to `tab_index(0)`.
 622    /// This should be the primary mechanism for tab navigation within the application.
 623    fn tab_stop(mut self) -> Self {
 624        self.tab_index(0)
 625    }
 626
 627    /// Set index of the tab stop order. This should only be used in conjunction with `tab_group`
 628    /// in order to not interfere with the tab index of other elements.
 629    fn tab_index(mut self, index: isize) -> Self {
 630        self.interactivity().focusable = true;
 631        self.interactivity().tab_index = Some(index);
 632        self
 633    }
 634
 635    /// Designate this div as a "tab group". Tab groups have their own location in the tab-index order,
 636    /// but for children of the tab group, the tab index is reset to 0. This can be useful for swapping
 637    /// the order of tab stops within the group, without having to renumber all the tab stops in the whole
 638    /// application.
 639    fn tab_group(mut self) -> Self {
 640        self.interactivity().tab_group = true;
 641        if self.interactivity().tab_index.is_none() {
 642            self.interactivity().tab_index = Some(0);
 643        }
 644        self
 645    }
 646
 647    /// Set the keymap context for this element. This will be used to determine
 648    /// which action to dispatch from the keymap.
 649    fn key_context<C, E>(mut self, key_context: C) -> Self
 650    where
 651        C: TryInto<KeyContext, Error = E>,
 652        E: Debug,
 653    {
 654        if let Some(key_context) = key_context.try_into().log_err() {
 655            self.interactivity().key_context = Some(key_context);
 656        }
 657        self
 658    }
 659
 660    /// Apply the given style to this element when the mouse hovers over it
 661    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
 662        debug_assert!(
 663            self.interactivity().hover_style.is_none(),
 664            "hover style already set"
 665        );
 666        self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
 667        self
 668    }
 669
 670    /// Apply the given style to this element when the mouse hovers over a group member
 671    fn group_hover(
 672        mut self,
 673        group_name: impl Into<SharedString>,
 674        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 675    ) -> Self {
 676        self.interactivity().group_hover_style = Some(GroupStyle {
 677            group: group_name.into(),
 678            style: Box::new(f(StyleRefinement::default())),
 679        });
 680        self
 681    }
 682
 683    /// Bind the given callback to the mouse down event for the given mouse button,
 684    /// the fluent API equivalent to [`Interactivity::on_mouse_down`]
 685    ///
 686    /// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
 687    fn on_mouse_down(
 688        mut self,
 689        button: MouseButton,
 690        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
 691    ) -> Self {
 692        self.interactivity().on_mouse_down(button, listener);
 693        self
 694    }
 695
 696    #[cfg(any(test, feature = "test-support"))]
 697    /// Set a key that can be used to look up this element's bounds
 698    /// in the [`crate::VisualTestContext::debug_bounds`] map
 699    /// This is a noop in release builds
 700    fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
 701        self.interactivity().debug_selector = Some(f());
 702        self
 703    }
 704
 705    #[cfg(not(any(test, feature = "test-support")))]
 706    /// Set a key that can be used to look up this element's bounds
 707    /// in the [`crate::VisualTestContext::debug_bounds`] map
 708    /// This is a noop in release builds
 709    #[inline]
 710    fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
 711        self
 712    }
 713
 714    /// Bind the given callback to the mouse down event for any button, during the capture phase
 715    /// the fluent API equivalent to [`Interactivity::capture_any_mouse_down`]
 716    ///
 717    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 718    fn capture_any_mouse_down(
 719        mut self,
 720        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
 721    ) -> Self {
 722        self.interactivity().capture_any_mouse_down(listener);
 723        self
 724    }
 725
 726    /// Bind the given callback to the mouse down event for any button, during the capture phase
 727    /// the fluent API equivalent to [`Interactivity::on_any_mouse_down`]
 728    ///
 729    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 730    fn on_any_mouse_down(
 731        mut self,
 732        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
 733    ) -> Self {
 734        self.interactivity().on_any_mouse_down(listener);
 735        self
 736    }
 737
 738    /// Bind the given callback to the mouse up event for the given button, during the bubble phase
 739    /// the fluent API equivalent to [`Interactivity::on_mouse_up`]
 740    ///
 741    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 742    fn on_mouse_up(
 743        mut self,
 744        button: MouseButton,
 745        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
 746    ) -> Self {
 747        self.interactivity().on_mouse_up(button, listener);
 748        self
 749    }
 750
 751    /// Bind the given callback to the mouse up event for any button, during the capture phase
 752    /// the fluent API equivalent to [`Interactivity::capture_any_mouse_up`]
 753    ///
 754    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 755    fn capture_any_mouse_up(
 756        mut self,
 757        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
 758    ) -> Self {
 759        self.interactivity().capture_any_mouse_up(listener);
 760        self
 761    }
 762
 763    /// Bind the given callback to the mouse down event, on any button, during the capture phase,
 764    /// when the mouse is outside of the bounds of this element.
 765    /// The fluent API equivalent to [`Interactivity::on_mouse_down_out`]
 766    ///
 767    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 768    fn on_mouse_down_out(
 769        mut self,
 770        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
 771    ) -> Self {
 772        self.interactivity().on_mouse_down_out(listener);
 773        self
 774    }
 775
 776    /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
 777    /// when the mouse is outside of the bounds of this element.
 778    /// The fluent API equivalent to [`Interactivity::on_mouse_up_out`]
 779    ///
 780    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 781    fn on_mouse_up_out(
 782        mut self,
 783        button: MouseButton,
 784        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
 785    ) -> Self {
 786        self.interactivity().on_mouse_up_out(button, listener);
 787        self
 788    }
 789
 790    /// Bind the given callback to the mouse move event, during the bubble phase
 791    /// The fluent API equivalent to [`Interactivity::on_mouse_move`]
 792    ///
 793    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 794    fn on_mouse_move(
 795        mut self,
 796        listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
 797    ) -> Self {
 798        self.interactivity().on_mouse_move(listener);
 799        self
 800    }
 801
 802    /// Bind the given callback to the mouse drag event of the given type. Note that this
 803    /// will be called for all move events, inside or outside of this element, as long as the
 804    /// drag was started with this element under the mouse. Useful for implementing draggable
 805    /// UIs that don't conform to a drag and drop style interaction, like resizing.
 806    /// The fluent API equivalent to [`Interactivity::on_drag_move`]
 807    ///
 808    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 809    fn on_drag_move<T: 'static>(
 810        mut self,
 811        listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
 812    ) -> Self {
 813        self.interactivity().on_drag_move(listener);
 814        self
 815    }
 816
 817    /// Bind the given callback to scroll wheel events during the bubble phase
 818    /// The fluent API equivalent to [`Interactivity::on_scroll_wheel`]
 819    ///
 820    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 821    fn on_scroll_wheel(
 822        mut self,
 823        listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
 824    ) -> Self {
 825        self.interactivity().on_scroll_wheel(listener);
 826        self
 827    }
 828
 829    /// Capture the given action, before normal action dispatch can fire
 830    /// The fluent API equivalent to [`Interactivity::on_scroll_wheel`]
 831    ///
 832    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 833    fn capture_action<A: Action>(
 834        mut self,
 835        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
 836    ) -> Self {
 837        self.interactivity().capture_action(listener);
 838        self
 839    }
 840
 841    /// Bind the given callback to an action dispatch during the bubble phase
 842    /// The fluent API equivalent to [`Interactivity::on_action`]
 843    ///
 844    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 845    fn on_action<A: Action>(
 846        mut self,
 847        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
 848    ) -> Self {
 849        self.interactivity().on_action(listener);
 850        self
 851    }
 852
 853    /// Bind the given callback to an action dispatch, based on a dynamic action parameter
 854    /// instead of a type parameter. Useful for component libraries that want to expose
 855    /// action bindings to their users.
 856    /// The fluent API equivalent to [`Interactivity::on_boxed_action`]
 857    ///
 858    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 859    fn on_boxed_action(
 860        mut self,
 861        action: &dyn Action,
 862        listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
 863    ) -> Self {
 864        self.interactivity().on_boxed_action(action, listener);
 865        self
 866    }
 867
 868    /// Bind the given callback to key down events during the bubble phase
 869    /// The fluent API equivalent to [`Interactivity::on_key_down`]
 870    ///
 871    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 872    fn on_key_down(
 873        mut self,
 874        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
 875    ) -> Self {
 876        self.interactivity().on_key_down(listener);
 877        self
 878    }
 879
 880    /// Bind the given callback to key down events during the capture phase
 881    /// The fluent API equivalent to [`Interactivity::capture_key_down`]
 882    ///
 883    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 884    fn capture_key_down(
 885        mut self,
 886        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
 887    ) -> Self {
 888        self.interactivity().capture_key_down(listener);
 889        self
 890    }
 891
 892    /// Bind the given callback to key up events during the bubble phase
 893    /// The fluent API equivalent to [`Interactivity::on_key_up`]
 894    ///
 895    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 896    fn on_key_up(
 897        mut self,
 898        listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
 899    ) -> Self {
 900        self.interactivity().on_key_up(listener);
 901        self
 902    }
 903
 904    /// Bind the given callback to key up events during the capture phase
 905    /// The fluent API equivalent to [`Interactivity::capture_key_up`]
 906    ///
 907    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 908    fn capture_key_up(
 909        mut self,
 910        listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
 911    ) -> Self {
 912        self.interactivity().capture_key_up(listener);
 913        self
 914    }
 915
 916    /// Bind the given callback to modifiers changing events.
 917    /// The fluent API equivalent to [`Interactivity::on_modifiers_changed`]
 918    ///
 919    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 920    fn on_modifiers_changed(
 921        mut self,
 922        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
 923    ) -> Self {
 924        self.interactivity().on_modifiers_changed(listener);
 925        self
 926    }
 927
 928    /// Apply the given style when the given data type is dragged over this element
 929    fn drag_over<S: 'static>(
 930        mut self,
 931        f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
 932    ) -> Self {
 933        self.interactivity().drag_over_styles.push((
 934            TypeId::of::<S>(),
 935            Box::new(move |currently_dragged: &dyn Any, window, cx| {
 936                f(
 937                    StyleRefinement::default(),
 938                    currently_dragged.downcast_ref::<S>().unwrap(),
 939                    window,
 940                    cx,
 941                )
 942            }),
 943        ));
 944        self
 945    }
 946
 947    /// Apply the given style when the given data type is dragged over this element's group
 948    fn group_drag_over<S: 'static>(
 949        mut self,
 950        group_name: impl Into<SharedString>,
 951        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 952    ) -> Self {
 953        self.interactivity().group_drag_over_styles.push((
 954            TypeId::of::<S>(),
 955            GroupStyle {
 956                group: group_name.into(),
 957                style: Box::new(f(StyleRefinement::default())),
 958            },
 959        ));
 960        self
 961    }
 962
 963    /// Bind the given callback to drop events of the given type, whether or not the drag started on this element
 964    /// The fluent API equivalent to [`Interactivity::on_drop`]
 965    ///
 966    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
 967    fn on_drop<T: 'static>(
 968        mut self,
 969        listener: impl Fn(&T, &mut Window, &mut App) + 'static,
 970    ) -> Self {
 971        self.interactivity().on_drop(listener);
 972        self
 973    }
 974
 975    /// Use the given predicate to determine whether or not a drop event should be dispatched to this element
 976    /// The fluent API equivalent to [`Interactivity::can_drop`]
 977    fn can_drop(
 978        mut self,
 979        predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
 980    ) -> Self {
 981        self.interactivity().can_drop(predicate);
 982        self
 983    }
 984
 985    /// Block the mouse from all interactions with elements behind this element's hitbox. Typically
 986    /// `block_mouse_except_scroll` should be preferred.
 987    /// The fluent API equivalent to [`Interactivity::occlude_mouse`]
 988    fn occlude(mut self) -> Self {
 989        self.interactivity().occlude_mouse();
 990        self
 991    }
 992
 993    /// Set the bounds of this element as a window control area for the platform window.
 994    /// The fluent API equivalent to [`Interactivity::window_control_area`]
 995    fn window_control_area(mut self, area: WindowControlArea) -> Self {
 996        self.interactivity().window_control_area(area);
 997        self
 998    }
 999
1000    /// Block non-scroll mouse interactions with elements behind this element's hitbox. See
1001    /// [`Hitbox::is_hovered`] for details.
1002    ///
1003    /// The fluent API equivalent to [`Interactivity::block_mouse_except_scroll`]
1004    fn block_mouse_except_scroll(mut self) -> Self {
1005        self.interactivity().block_mouse_except_scroll();
1006        self
1007    }
1008
1009    /// Set the given styles to be applied when this element, specifically, is focused.
1010    /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1011    fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1012    where
1013        Self: Sized,
1014    {
1015        self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1016        self
1017    }
1018
1019    /// Set the given styles to be applied when this element is inside another element that is focused.
1020    /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1021    fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1022    where
1023        Self: Sized,
1024    {
1025        self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1026        self
1027    }
1028}
1029
1030/// A trait for elements that want to use the standard GPUI interactivity features
1031/// that require state.
1032pub trait StatefulInteractiveElement: InteractiveElement {
1033    /// Set this element to focusable.
1034    fn focusable(mut self) -> Self {
1035        self.interactivity().focusable = true;
1036        self
1037    }
1038
1039    /// Set the overflow x and y to scroll.
1040    fn overflow_scroll(mut self) -> Self {
1041        self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1042        self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1043        self
1044    }
1045
1046    /// Set the overflow x to scroll.
1047    fn overflow_x_scroll(mut self) -> Self {
1048        self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1049        self
1050    }
1051
1052    /// Set the overflow y to scroll.
1053    fn overflow_y_scroll(mut self) -> Self {
1054        self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1055        self
1056    }
1057
1058    /// Set the space to be reserved for rendering the scrollbar.
1059    ///
1060    /// This will only affect the layout of the element when overflow for this element is set to
1061    /// `Overflow::Scroll`.
1062    fn scrollbar_width(mut self, width: impl Into<AbsoluteLength>) -> Self {
1063        self.interactivity().base_style.scrollbar_width = Some(width.into());
1064        self
1065    }
1066
1067    /// Track the scroll state of this element with the given handle.
1068    fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1069        self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1070        self
1071    }
1072
1073    /// Track the scroll state of this element with the given handle.
1074    fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1075        self.interactivity().scroll_anchor = scroll_anchor;
1076        self
1077    }
1078
1079    /// Set the given styles to be applied when this element is active.
1080    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1081    where
1082        Self: Sized,
1083    {
1084        self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1085        self
1086    }
1087
1088    /// Set the given styles to be applied when this element's group is active.
1089    fn group_active(
1090        mut self,
1091        group_name: impl Into<SharedString>,
1092        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1093    ) -> Self
1094    where
1095        Self: Sized,
1096    {
1097        self.interactivity().group_active_style = Some(GroupStyle {
1098            group: group_name.into(),
1099            style: Box::new(f(StyleRefinement::default())),
1100        });
1101        self
1102    }
1103
1104    /// Bind the given callback to click events of this element
1105    /// The fluent API equivalent to [`Interactivity::on_click`]
1106    ///
1107    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1108    fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1109    where
1110        Self: Sized,
1111    {
1112        self.interactivity().on_click(listener);
1113        self
1114    }
1115
1116    /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
1117    /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
1118    /// the [`InteractiveElement::on_drag_move`] API.
1119    /// The callback also has access to the offset of triggering click from the origin of parent element.
1120    /// The fluent API equivalent to [`Interactivity::on_drag`]
1121    ///
1122    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1123    fn on_drag<T, W>(
1124        mut self,
1125        value: T,
1126        constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1127    ) -> Self
1128    where
1129        Self: Sized,
1130        T: 'static,
1131        W: 'static + Render,
1132    {
1133        self.interactivity().on_drag(value, constructor);
1134        self
1135    }
1136
1137    /// Bind the given callback on the hover start and end events of this element. Note that the boolean
1138    /// passed to the callback is true when the hover starts and false when it ends.
1139    /// The fluent API equivalent to [`Interactivity::on_hover`]
1140    ///
1141    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1142    fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1143    where
1144        Self: Sized,
1145    {
1146        self.interactivity().on_hover(listener);
1147        self
1148    }
1149
1150    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
1151    /// The fluent API equivalent to [`Interactivity::tooltip`]
1152    fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1153    where
1154        Self: Sized,
1155    {
1156        self.interactivity().tooltip(build_tooltip);
1157        self
1158    }
1159
1160    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
1161    /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
1162    /// the tooltip. The fluent API equivalent to [`Interactivity::hoverable_tooltip`]
1163    fn hoverable_tooltip(
1164        mut self,
1165        build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1166    ) -> Self
1167    where
1168        Self: Sized,
1169    {
1170        self.interactivity().hoverable_tooltip(build_tooltip);
1171        self
1172    }
1173}
1174
1175pub(crate) type MouseDownListener =
1176    Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1177pub(crate) type MouseUpListener =
1178    Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1179
1180pub(crate) type MouseMoveListener =
1181    Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1182
1183pub(crate) type ScrollWheelListener =
1184    Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1185
1186pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1187
1188pub(crate) type DragListener =
1189    Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>;
1190
1191type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1192
1193type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1194
1195pub(crate) struct TooltipBuilder {
1196    build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1197    hoverable: bool,
1198}
1199
1200pub(crate) type KeyDownListener =
1201    Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1202
1203pub(crate) type KeyUpListener =
1204    Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1205
1206pub(crate) type ModifiersChangedListener =
1207    Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1208
1209pub(crate) type ActionListener =
1210    Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1211
1212/// Construct a new [`Div`] element
1213#[track_caller]
1214pub fn div() -> Div {
1215    Div {
1216        interactivity: Interactivity::new(),
1217        children: SmallVec::default(),
1218        prepaint_listener: None,
1219        image_cache: None,
1220    }
1221}
1222
1223/// A [`Div`] element, the all-in-one element for building complex UIs in GPUI
1224pub struct Div {
1225    interactivity: Interactivity,
1226    children: SmallVec<[StackSafe<AnyElement>; 2]>,
1227    prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1228    image_cache: Option<Box<dyn ImageCacheProvider>>,
1229}
1230
1231impl Div {
1232    /// Add a listener to be called when the children of this `Div` are prepainted.
1233    /// This allows you to store the [`Bounds`] of the children for later use.
1234    pub fn on_children_prepainted(
1235        mut self,
1236        listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1237    ) -> Self {
1238        self.prepaint_listener = Some(Box::new(listener));
1239        self
1240    }
1241
1242    /// Add an image cache at the location of this div in the element tree.
1243    pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1244        self.image_cache = Some(Box::new(cache));
1245        self
1246    }
1247}
1248
1249/// A frame state for a `Div` element, which contains layout IDs for its children.
1250///
1251/// This struct is used internally by the `Div` element to manage the layout state of its children
1252/// during the UI update cycle. It holds a small vector of `LayoutId` values, each corresponding to
1253/// a child element of the `Div`. These IDs are used to query the layout engine for the computed
1254/// bounds of the children after the layout phase is complete.
1255pub struct DivFrameState {
1256    child_layout_ids: SmallVec<[LayoutId; 2]>,
1257}
1258
1259/// Interactivity state displayed an manipulated in the inspector.
1260#[derive(Clone)]
1261pub struct DivInspectorState {
1262    /// The inspected element's base style. This is used for both inspecting and modifying the
1263    /// state. In the future it will make sense to separate the read and write, possibly tracking
1264    /// the modifications.
1265    #[cfg(any(feature = "inspector", debug_assertions))]
1266    pub base_style: Box<StyleRefinement>,
1267    /// Inspects the bounds of the element.
1268    pub bounds: Bounds<Pixels>,
1269    /// Size of the children of the element, or `bounds.size` if it has no children.
1270    pub content_size: Size<Pixels>,
1271}
1272
1273impl Styled for Div {
1274    fn style(&mut self) -> &mut StyleRefinement {
1275        &mut self.interactivity.base_style
1276    }
1277}
1278
1279impl InteractiveElement for Div {
1280    fn interactivity(&mut self) -> &mut Interactivity {
1281        &mut self.interactivity
1282    }
1283}
1284
1285impl ParentElement for Div {
1286    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1287        self.children
1288            .extend(elements.into_iter().map(StackSafe::new))
1289    }
1290}
1291
1292impl Element for Div {
1293    type RequestLayoutState = DivFrameState;
1294    type PrepaintState = Option<Hitbox>;
1295
1296    fn id(&self) -> Option<ElementId> {
1297        self.interactivity.element_id.clone()
1298    }
1299
1300    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1301        self.interactivity.source_location()
1302    }
1303
1304    #[stacksafe]
1305    fn request_layout(
1306        &mut self,
1307        global_id: Option<&GlobalElementId>,
1308        inspector_id: Option<&InspectorElementId>,
1309        window: &mut Window,
1310        cx: &mut App,
1311    ) -> (LayoutId, Self::RequestLayoutState) {
1312        let mut child_layout_ids = SmallVec::new();
1313        let image_cache = self
1314            .image_cache
1315            .as_mut()
1316            .map(|provider| provider.provide(window, cx));
1317
1318        let layout_id = window.with_image_cache(image_cache, |window| {
1319            self.interactivity.request_layout(
1320                global_id,
1321                inspector_id,
1322                window,
1323                cx,
1324                |style, window, cx| {
1325                    window.with_text_style(style.text_style().cloned(), |window| {
1326                        child_layout_ids = self
1327                            .children
1328                            .iter_mut()
1329                            .map(|child| child.request_layout(window, cx))
1330                            .collect::<SmallVec<_>>();
1331                        window.request_layout(style, child_layout_ids.iter().copied(), cx)
1332                    })
1333                },
1334            )
1335        });
1336
1337        (layout_id, DivFrameState { child_layout_ids })
1338    }
1339
1340    #[stacksafe]
1341    fn prepaint(
1342        &mut self,
1343        global_id: Option<&GlobalElementId>,
1344        inspector_id: Option<&InspectorElementId>,
1345        bounds: Bounds<Pixels>,
1346        request_layout: &mut Self::RequestLayoutState,
1347        window: &mut Window,
1348        cx: &mut App,
1349    ) -> Option<Hitbox> {
1350        let has_prepaint_listener = self.prepaint_listener.is_some();
1351        let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1352            request_layout.child_layout_ids.len()
1353        } else {
1354            0
1355        });
1356
1357        let mut child_min = point(Pixels::MAX, Pixels::MAX);
1358        let mut child_max = Point::default();
1359        if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1360            *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1361        }
1362        let content_size = if request_layout.child_layout_ids.is_empty() {
1363            bounds.size
1364        } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1365            let mut state = scroll_handle.0.borrow_mut();
1366            state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1367            for child_layout_id in &request_layout.child_layout_ids {
1368                let child_bounds = window.layout_bounds(*child_layout_id);
1369                child_min = child_min.min(&child_bounds.origin);
1370                child_max = child_max.max(&child_bounds.bottom_right());
1371                state.child_bounds.push(child_bounds);
1372            }
1373            (child_max - child_min).into()
1374        } else {
1375            for child_layout_id in &request_layout.child_layout_ids {
1376                let child_bounds = window.layout_bounds(*child_layout_id);
1377                child_min = child_min.min(&child_bounds.origin);
1378                child_max = child_max.max(&child_bounds.bottom_right());
1379
1380                if has_prepaint_listener {
1381                    children_bounds.push(child_bounds);
1382                }
1383            }
1384            (child_max - child_min).into()
1385        };
1386
1387        self.interactivity.prepaint(
1388            global_id,
1389            inspector_id,
1390            bounds,
1391            content_size,
1392            window,
1393            cx,
1394            |_style, scroll_offset, hitbox, window, cx| {
1395                window.with_element_offset(scroll_offset, |window| {
1396                    for child in &mut self.children {
1397                        child.prepaint(window, cx);
1398                    }
1399                });
1400
1401                if let Some(listener) = self.prepaint_listener.as_ref() {
1402                    listener(children_bounds, window, cx);
1403                }
1404
1405                hitbox
1406            },
1407        )
1408    }
1409
1410    #[stacksafe]
1411    fn paint(
1412        &mut self,
1413        global_id: Option<&GlobalElementId>,
1414        inspector_id: Option<&InspectorElementId>,
1415        bounds: Bounds<Pixels>,
1416        _request_layout: &mut Self::RequestLayoutState,
1417        hitbox: &mut Option<Hitbox>,
1418        window: &mut Window,
1419        cx: &mut App,
1420    ) {
1421        let image_cache = self
1422            .image_cache
1423            .as_mut()
1424            .map(|provider| provider.provide(window, cx));
1425
1426        window.with_image_cache(image_cache, |window| {
1427            self.interactivity.paint(
1428                global_id,
1429                inspector_id,
1430                bounds,
1431                hitbox.as_ref(),
1432                window,
1433                cx,
1434                |_style, window, cx| {
1435                    for child in &mut self.children {
1436                        child.paint(window, cx);
1437                    }
1438                },
1439            )
1440        });
1441    }
1442}
1443
1444impl IntoElement for Div {
1445    type Element = Self;
1446
1447    fn into_element(self) -> Self::Element {
1448        self
1449    }
1450}
1451
1452/// The interactivity struct. Powers all of the general-purpose
1453/// interactivity in the `Div` element.
1454#[derive(Default)]
1455pub struct Interactivity {
1456    /// The element ID of the element. In id is required to support a stateful subset of the interactivity such as on_click.
1457    pub element_id: Option<ElementId>,
1458    /// Whether the element was clicked. This will only be present after layout.
1459    pub active: Option<bool>,
1460    /// Whether the element was hovered. This will only be present after paint if an hitbox
1461    /// was created for the interactive element.
1462    pub hovered: Option<bool>,
1463    pub(crate) tooltip_id: Option<TooltipId>,
1464    pub(crate) content_size: Size<Pixels>,
1465    pub(crate) key_context: Option<KeyContext>,
1466    pub(crate) focusable: bool,
1467    pub(crate) tracked_focus_handle: Option<FocusHandle>,
1468    pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
1469    pub(crate) scroll_anchor: Option<ScrollAnchor>,
1470    pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
1471    pub(crate) group: Option<SharedString>,
1472    /// The base style of the element, before any modifications are applied
1473    /// by focus, active, etc.
1474    pub base_style: Box<StyleRefinement>,
1475    pub(crate) focus_style: Option<Box<StyleRefinement>>,
1476    pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
1477    pub(crate) hover_style: Option<Box<StyleRefinement>>,
1478    pub(crate) group_hover_style: Option<GroupStyle>,
1479    pub(crate) active_style: Option<Box<StyleRefinement>>,
1480    pub(crate) group_active_style: Option<GroupStyle>,
1481    pub(crate) drag_over_styles: Vec<(
1482        TypeId,
1483        Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
1484    )>,
1485    pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
1486    pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
1487    pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
1488    pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
1489    pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
1490    pub(crate) key_down_listeners: Vec<KeyDownListener>,
1491    pub(crate) key_up_listeners: Vec<KeyUpListener>,
1492    pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
1493    pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
1494    pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
1495    pub(crate) can_drop_predicate: Option<CanDropPredicate>,
1496    pub(crate) click_listeners: Vec<ClickListener>,
1497    pub(crate) drag_listener: Option<(Arc<dyn Any>, DragListener)>,
1498    pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
1499    pub(crate) tooltip_builder: Option<TooltipBuilder>,
1500    pub(crate) window_control: Option<WindowControlArea>,
1501    pub(crate) hitbox_behavior: HitboxBehavior,
1502    pub(crate) tab_index: Option<isize>,
1503    pub(crate) tab_group: bool,
1504
1505    #[cfg(any(feature = "inspector", debug_assertions))]
1506    pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
1507
1508    #[cfg(any(test, feature = "test-support"))]
1509    pub(crate) debug_selector: Option<String>,
1510}
1511
1512impl Interactivity {
1513    /// Layout this element according to this interactivity state's configured styles
1514    pub fn request_layout(
1515        &mut self,
1516        global_id: Option<&GlobalElementId>,
1517        _inspector_id: Option<&InspectorElementId>,
1518        window: &mut Window,
1519        cx: &mut App,
1520        f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
1521    ) -> LayoutId {
1522        #[cfg(any(feature = "inspector", debug_assertions))]
1523        window.with_inspector_state(
1524            _inspector_id,
1525            cx,
1526            |inspector_state: &mut Option<DivInspectorState>, _window| {
1527                if let Some(inspector_state) = inspector_state {
1528                    self.base_style = inspector_state.base_style.clone();
1529                } else {
1530                    *inspector_state = Some(DivInspectorState {
1531                        base_style: self.base_style.clone(),
1532                        bounds: Default::default(),
1533                        content_size: Default::default(),
1534                    })
1535                }
1536            },
1537        );
1538
1539        window.with_optional_element_state::<InteractiveElementState, _>(
1540            global_id,
1541            |element_state, window| {
1542                let mut element_state =
1543                    element_state.map(|element_state| element_state.unwrap_or_default());
1544
1545                if let Some(element_state) = element_state.as_ref()
1546                    && cx.has_active_drag()
1547                {
1548                    if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
1549                        *pending_mouse_down.borrow_mut() = None;
1550                    }
1551                    if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1552                        *clicked_state.borrow_mut() = ElementClickedState::default();
1553                    }
1554                }
1555
1556                // Ensure we store a focus handle in our element state if we're focusable.
1557                // If there's an explicit focus handle we're tracking, use that. Otherwise
1558                // create a new handle and store it in the element state, which lives for as
1559                // as frames contain an element with this id.
1560                if self.focusable
1561                    && self.tracked_focus_handle.is_none()
1562                    && let Some(element_state) = element_state.as_mut()
1563                {
1564                    let mut handle = element_state
1565                        .focus_handle
1566                        .get_or_insert_with(|| cx.focus_handle())
1567                        .clone()
1568                        .tab_stop(false);
1569
1570                    if let Some(index) = self.tab_index {
1571                        handle = handle.tab_index(index).tab_stop(true);
1572                    }
1573
1574                    self.tracked_focus_handle = Some(handle);
1575                }
1576
1577                if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
1578                    self.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
1579                } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
1580                    || self.base_style.overflow.y == Some(Overflow::Scroll))
1581                    && let Some(element_state) = element_state.as_mut()
1582                {
1583                    self.scroll_offset = Some(
1584                        element_state
1585                            .scroll_offset
1586                            .get_or_insert_with(Rc::default)
1587                            .clone(),
1588                    );
1589                }
1590
1591                let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
1592                let layout_id = f(style, window, cx);
1593                (layout_id, element_state)
1594            },
1595        )
1596    }
1597
1598    /// Commit the bounds of this element according to this interactivity state's configured styles.
1599    pub fn prepaint<R>(
1600        &mut self,
1601        global_id: Option<&GlobalElementId>,
1602        _inspector_id: Option<&InspectorElementId>,
1603        bounds: Bounds<Pixels>,
1604        content_size: Size<Pixels>,
1605        window: &mut Window,
1606        cx: &mut App,
1607        f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
1608    ) -> R {
1609        self.content_size = content_size;
1610
1611        #[cfg(any(feature = "inspector", debug_assertions))]
1612        window.with_inspector_state(
1613            _inspector_id,
1614            cx,
1615            |inspector_state: &mut Option<DivInspectorState>, _window| {
1616                if let Some(inspector_state) = inspector_state {
1617                    inspector_state.bounds = bounds;
1618                    inspector_state.content_size = content_size;
1619                }
1620            },
1621        );
1622
1623        if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1624            window.set_focus_handle(focus_handle, cx);
1625        }
1626        window.with_optional_element_state::<InteractiveElementState, _>(
1627            global_id,
1628            |element_state, window| {
1629                let mut element_state =
1630                    element_state.map(|element_state| element_state.unwrap_or_default());
1631                let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
1632
1633                if let Some(element_state) = element_state.as_mut() {
1634                    if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1635                        let clicked_state = clicked_state.borrow();
1636                        self.active = Some(clicked_state.element);
1637                    }
1638                    if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
1639                        if self.tooltip_builder.is_some() {
1640                            self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
1641                        } else {
1642                            // If there is no longer a tooltip builder, remove the active tooltip.
1643                            element_state.active_tooltip.take();
1644                        }
1645                    }
1646                }
1647
1648                window.with_text_style(style.text_style().cloned(), |window| {
1649                    window.with_content_mask(
1650                        style.overflow_mask(bounds, window.rem_size()),
1651                        |window| {
1652                            let hitbox = if self.should_insert_hitbox(&style, window, cx) {
1653                                Some(window.insert_hitbox(bounds, self.hitbox_behavior))
1654                            } else {
1655                                None
1656                            };
1657
1658                            let scroll_offset =
1659                                self.clamp_scroll_position(bounds, &style, window, cx);
1660                            let result = f(&style, scroll_offset, hitbox, window, cx);
1661                            (result, element_state)
1662                        },
1663                    )
1664                })
1665            },
1666        )
1667    }
1668
1669    fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
1670        self.hitbox_behavior != HitboxBehavior::Normal
1671            || self.window_control.is_some()
1672            || style.mouse_cursor.is_some()
1673            || self.group.is_some()
1674            || self.scroll_offset.is_some()
1675            || self.tracked_focus_handle.is_some()
1676            || self.hover_style.is_some()
1677            || self.group_hover_style.is_some()
1678            || self.hover_listener.is_some()
1679            || !self.mouse_up_listeners.is_empty()
1680            || !self.mouse_down_listeners.is_empty()
1681            || !self.mouse_move_listeners.is_empty()
1682            || !self.click_listeners.is_empty()
1683            || !self.scroll_wheel_listeners.is_empty()
1684            || self.drag_listener.is_some()
1685            || !self.drop_listeners.is_empty()
1686            || self.tooltip_builder.is_some()
1687            || window.is_inspector_picking(cx)
1688    }
1689
1690    fn clamp_scroll_position(
1691        &self,
1692        bounds: Bounds<Pixels>,
1693        style: &Style,
1694        window: &mut Window,
1695        _cx: &mut App,
1696    ) -> Point<Pixels> {
1697        fn round_to_two_decimals(pixels: Pixels) -> Pixels {
1698            const ROUNDING_FACTOR: f32 = 100.0;
1699            (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
1700        }
1701
1702        if let Some(scroll_offset) = self.scroll_offset.as_ref() {
1703            let mut scroll_to_bottom = false;
1704            let mut tracked_scroll_handle = self
1705                .tracked_scroll_handle
1706                .as_ref()
1707                .map(|handle| handle.0.borrow_mut());
1708            if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
1709                scroll_handle_state.overflow = style.overflow;
1710                scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
1711            }
1712
1713            let rem_size = window.rem_size();
1714            let padding = style.padding.to_pixels(bounds.size.into(), rem_size);
1715            let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
1716            // The floating point values produced by Taffy and ours often vary
1717            // slightly after ~5 decimal places. This can lead to cases where after
1718            // subtracting these, the container becomes scrollable for less than
1719            // 0.00000x pixels. As we generally don't benefit from a precision that
1720            // high for the maximum scroll, we round the scroll max to 2 decimal
1721            // places here.
1722            let padded_content_size = self.content_size + padding_size;
1723            let scroll_max = (padded_content_size - bounds.size)
1724                .map(round_to_two_decimals)
1725                .max(&Default::default());
1726            // Clamp scroll offset in case scroll max is smaller now (e.g., if children
1727            // were removed or the bounds became larger).
1728            let mut scroll_offset = scroll_offset.borrow_mut();
1729
1730            scroll_offset.x = scroll_offset.x.clamp(-scroll_max.width, px(0.));
1731            if scroll_to_bottom {
1732                scroll_offset.y = -scroll_max.height;
1733            } else {
1734                scroll_offset.y = scroll_offset.y.clamp(-scroll_max.height, px(0.));
1735            }
1736
1737            if let Some(mut scroll_handle_state) = tracked_scroll_handle {
1738                scroll_handle_state.max_offset = scroll_max;
1739                scroll_handle_state.bounds = bounds;
1740            }
1741
1742            *scroll_offset
1743        } else {
1744            Point::default()
1745        }
1746    }
1747
1748    /// Paint this element according to this interactivity state's configured styles
1749    /// and bind the element's mouse and keyboard events.
1750    ///
1751    /// content_size is the size of the content of the element, which may be larger than the
1752    /// element's bounds if the element is scrollable.
1753    ///
1754    /// the final computed style will be passed to the provided function, along
1755    /// with the current scroll offset
1756    pub fn paint(
1757        &mut self,
1758        global_id: Option<&GlobalElementId>,
1759        _inspector_id: Option<&InspectorElementId>,
1760        bounds: Bounds<Pixels>,
1761        hitbox: Option<&Hitbox>,
1762        window: &mut Window,
1763        cx: &mut App,
1764        f: impl FnOnce(&Style, &mut Window, &mut App),
1765    ) {
1766        self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
1767        window.with_optional_element_state::<InteractiveElementState, _>(
1768            global_id,
1769            |element_state, window| {
1770                let mut element_state =
1771                    element_state.map(|element_state| element_state.unwrap_or_default());
1772
1773                let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
1774
1775                #[cfg(any(feature = "test-support", test))]
1776                if let Some(debug_selector) = &self.debug_selector {
1777                    window
1778                        .next_frame
1779                        .debug_bounds
1780                        .insert(debug_selector.clone(), bounds);
1781                }
1782
1783                self.paint_hover_group_handler(window, cx);
1784
1785                if style.visibility == Visibility::Hidden {
1786                    return ((), element_state);
1787                }
1788
1789                let mut tab_group = None;
1790                if self.tab_group {
1791                    tab_group = self.tab_index;
1792                }
1793                if let Some(focus_handle) = &self.tracked_focus_handle {
1794                    window.next_frame.tab_stops.insert(focus_handle);
1795                }
1796
1797                window.with_element_opacity(style.opacity, |window| {
1798                    style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
1799                        window.with_text_style(style.text_style().cloned(), |window| {
1800                            window.with_content_mask(
1801                                style.overflow_mask(bounds, window.rem_size()),
1802                                |window| {
1803                                    window.with_tab_group(tab_group, |window| {
1804                                        if let Some(hitbox) = hitbox {
1805                                            #[cfg(debug_assertions)]
1806                                            self.paint_debug_info(
1807                                                global_id, hitbox, &style, window, cx,
1808                                            );
1809
1810                                            if let Some(drag) = cx.active_drag.as_ref() {
1811                                                if let Some(mouse_cursor) = drag.cursor_style {
1812                                                    window.set_window_cursor_style(mouse_cursor);
1813                                                }
1814                                            } else {
1815                                                if let Some(mouse_cursor) = style.mouse_cursor {
1816                                                    window.set_cursor_style(mouse_cursor, hitbox);
1817                                                }
1818                                            }
1819
1820                                            if let Some(group) = self.group.clone() {
1821                                                GroupHitboxes::push(group, hitbox.id, cx);
1822                                            }
1823
1824                                            if let Some(area) = self.window_control {
1825                                                window.insert_window_control_hitbox(
1826                                                    area,
1827                                                    hitbox.clone(),
1828                                                );
1829                                            }
1830
1831                                            self.paint_mouse_listeners(
1832                                                hitbox,
1833                                                element_state.as_mut(),
1834                                                window,
1835                                                cx,
1836                                            );
1837                                            self.paint_scroll_listener(hitbox, &style, window, cx);
1838                                        }
1839
1840                                        self.paint_keyboard_listeners(window, cx);
1841                                        f(&style, window, cx);
1842
1843                                        if let Some(_hitbox) = hitbox {
1844                                            #[cfg(any(feature = "inspector", debug_assertions))]
1845                                            window.insert_inspector_hitbox(
1846                                                _hitbox.id,
1847                                                _inspector_id,
1848                                                cx,
1849                                            );
1850
1851                                            if let Some(group) = self.group.as_ref() {
1852                                                GroupHitboxes::pop(group, cx);
1853                                            }
1854                                        }
1855                                    })
1856                                },
1857                            );
1858                        });
1859                    });
1860                });
1861
1862                ((), element_state)
1863            },
1864        );
1865    }
1866
1867    #[cfg(debug_assertions)]
1868    fn paint_debug_info(
1869        &self,
1870        global_id: Option<&GlobalElementId>,
1871        hitbox: &Hitbox,
1872        style: &Style,
1873        window: &mut Window,
1874        cx: &mut App,
1875    ) {
1876        use crate::{BorderStyle, TextAlign};
1877
1878        if global_id.is_some()
1879            && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
1880            && hitbox.is_hovered(window)
1881        {
1882            const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
1883            let element_id = format!("{:?}", global_id.unwrap());
1884            let str_len = element_id.len();
1885
1886            let render_debug_text = |window: &mut Window| {
1887                if let Some(text) = window
1888                    .text_system()
1889                    .shape_text(
1890                        element_id.into(),
1891                        FONT_SIZE,
1892                        &[window.text_style().to_run(str_len)],
1893                        None,
1894                        None,
1895                    )
1896                    .ok()
1897                    .and_then(|mut text| text.pop())
1898                {
1899                    text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
1900                        .ok();
1901
1902                    let text_bounds = crate::Bounds {
1903                        origin: hitbox.origin,
1904                        size: text.size(FONT_SIZE),
1905                    };
1906                    if self.source_location.is_some()
1907                        && text_bounds.contains(&window.mouse_position())
1908                        && window.modifiers().secondary()
1909                    {
1910                        let secondary_held = window.modifiers().secondary();
1911                        window.on_key_event({
1912                            move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
1913                                if e.modifiers.secondary() != secondary_held
1914                                    && text_bounds.contains(&window.mouse_position())
1915                                {
1916                                    window.refresh();
1917                                }
1918                            }
1919                        });
1920
1921                        let was_hovered = hitbox.is_hovered(window);
1922                        let current_view = window.current_view();
1923                        window.on_mouse_event({
1924                            let hitbox = hitbox.clone();
1925                            move |_: &MouseMoveEvent, phase, window, cx| {
1926                                if phase == DispatchPhase::Capture {
1927                                    let hovered = hitbox.is_hovered(window);
1928                                    if hovered != was_hovered {
1929                                        cx.notify(current_view)
1930                                    }
1931                                }
1932                            }
1933                        });
1934
1935                        window.on_mouse_event({
1936                            let hitbox = hitbox.clone();
1937                            let location = self.source_location.unwrap();
1938                            move |e: &crate::MouseDownEvent, phase, window, cx| {
1939                                if text_bounds.contains(&e.position)
1940                                    && phase.capture()
1941                                    && hitbox.is_hovered(window)
1942                                {
1943                                    cx.stop_propagation();
1944                                    let Ok(dir) = std::env::current_dir() else {
1945                                        return;
1946                                    };
1947
1948                                    eprintln!(
1949                                        "This element was created at:\n{}:{}:{}",
1950                                        dir.join(location.file()).to_string_lossy(),
1951                                        location.line(),
1952                                        location.column()
1953                                    );
1954                                }
1955                            }
1956                        });
1957                        window.paint_quad(crate::outline(
1958                            crate::Bounds {
1959                                origin: hitbox.origin
1960                                    + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
1961                                size: crate::Size {
1962                                    width: text_bounds.size.width,
1963                                    height: crate::px(1.),
1964                                },
1965                            },
1966                            crate::red(),
1967                            BorderStyle::default(),
1968                        ))
1969                    }
1970                }
1971            };
1972
1973            window.with_text_style(
1974                Some(crate::TextStyleRefinement {
1975                    color: Some(crate::red()),
1976                    line_height: Some(FONT_SIZE.into()),
1977                    background_color: Some(crate::white()),
1978                    ..Default::default()
1979                }),
1980                render_debug_text,
1981            )
1982        }
1983    }
1984
1985    fn paint_mouse_listeners(
1986        &mut self,
1987        hitbox: &Hitbox,
1988        element_state: Option<&mut InteractiveElementState>,
1989        window: &mut Window,
1990        cx: &mut App,
1991    ) {
1992        let is_focused = self
1993            .tracked_focus_handle
1994            .as_ref()
1995            .map(|handle| handle.is_focused(window))
1996            .unwrap_or(false);
1997
1998        // If this element can be focused, register a mouse down listener
1999        // that will automatically transfer focus when hitting the element.
2000        // This behavior can be suppressed by using `cx.prevent_default()`.
2001        if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2002            let hitbox = hitbox.clone();
2003            window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _| {
2004                if phase == DispatchPhase::Bubble
2005                    && hitbox.is_hovered(window)
2006                    && !window.default_prevented()
2007                {
2008                    window.focus(&focus_handle);
2009                    // If there is a parent that is also focusable, prevent it
2010                    // from transferring focus because we already did so.
2011                    window.prevent_default();
2012                }
2013            });
2014        }
2015
2016        for listener in self.mouse_down_listeners.drain(..) {
2017            let hitbox = hitbox.clone();
2018            window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2019                listener(event, phase, &hitbox, window, cx);
2020            })
2021        }
2022
2023        for listener in self.mouse_up_listeners.drain(..) {
2024            let hitbox = hitbox.clone();
2025            window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2026                listener(event, phase, &hitbox, window, cx);
2027            })
2028        }
2029
2030        for listener in self.mouse_move_listeners.drain(..) {
2031            let hitbox = hitbox.clone();
2032            window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2033                listener(event, phase, &hitbox, window, cx);
2034            })
2035        }
2036
2037        for listener in self.scroll_wheel_listeners.drain(..) {
2038            let hitbox = hitbox.clone();
2039            window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2040                listener(event, phase, &hitbox, window, cx);
2041            })
2042        }
2043
2044        if self.hover_style.is_some()
2045            || self.base_style.mouse_cursor.is_some()
2046            || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2047        {
2048            let hitbox = hitbox.clone();
2049            let was_hovered = hitbox.is_hovered(window);
2050            let current_view = window.current_view();
2051            window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2052                let hovered = hitbox.is_hovered(window);
2053                if phase == DispatchPhase::Capture && hovered != was_hovered {
2054                    cx.notify(current_view);
2055                }
2056            });
2057        }
2058        let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2059
2060        let mut drag_listener = mem::take(&mut self.drag_listener);
2061        let drop_listeners = mem::take(&mut self.drop_listeners);
2062        let click_listeners = mem::take(&mut self.click_listeners);
2063        let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2064
2065        if !drop_listeners.is_empty() {
2066            let hitbox = hitbox.clone();
2067            window.on_mouse_event({
2068                move |_: &MouseUpEvent, phase, window, cx| {
2069                    if let Some(drag) = &cx.active_drag
2070                        && phase == DispatchPhase::Bubble
2071                        && hitbox.is_hovered(window)
2072                    {
2073                        let drag_state_type = drag.value.as_ref().type_id();
2074                        for (drop_state_type, listener) in &drop_listeners {
2075                            if *drop_state_type == drag_state_type {
2076                                let drag = cx
2077                                    .active_drag
2078                                    .take()
2079                                    .expect("checked for type drag state type above");
2080
2081                                let mut can_drop = true;
2082                                if let Some(predicate) = &can_drop_predicate {
2083                                    can_drop = predicate(drag.value.as_ref(), window, cx);
2084                                }
2085
2086                                if can_drop {
2087                                    listener(drag.value.as_ref(), window, cx);
2088                                    window.refresh();
2089                                    cx.stop_propagation();
2090                                }
2091                            }
2092                        }
2093                    }
2094                }
2095            });
2096        }
2097
2098        if let Some(element_state) = element_state {
2099            if !click_listeners.is_empty() || drag_listener.is_some() {
2100                let pending_mouse_down = element_state
2101                    .pending_mouse_down
2102                    .get_or_insert_with(Default::default)
2103                    .clone();
2104
2105                let clicked_state = element_state
2106                    .clicked_state
2107                    .get_or_insert_with(Default::default)
2108                    .clone();
2109
2110                window.on_mouse_event({
2111                    let pending_mouse_down = pending_mouse_down.clone();
2112                    let hitbox = hitbox.clone();
2113                    move |event: &MouseDownEvent, phase, window, _cx| {
2114                        if phase == DispatchPhase::Bubble
2115                            && event.button == MouseButton::Left
2116                            && hitbox.is_hovered(window)
2117                        {
2118                            *pending_mouse_down.borrow_mut() = Some(event.clone());
2119                            window.refresh();
2120                        }
2121                    }
2122                });
2123
2124                window.on_mouse_event({
2125                    let pending_mouse_down = pending_mouse_down.clone();
2126                    let hitbox = hitbox.clone();
2127                    move |event: &MouseMoveEvent, phase, window, cx| {
2128                        if phase == DispatchPhase::Capture {
2129                            return;
2130                        }
2131
2132                        let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2133                        if let Some(mouse_down) = pending_mouse_down.clone()
2134                            && !cx.has_active_drag()
2135                            && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2136                            && let Some((drag_value, drag_listener)) = drag_listener.take()
2137                        {
2138                            *clicked_state.borrow_mut() = ElementClickedState::default();
2139                            let cursor_offset = event.position - hitbox.origin;
2140                            let drag =
2141                                (drag_listener)(drag_value.as_ref(), cursor_offset, window, cx);
2142                            cx.active_drag = Some(AnyDrag {
2143                                view: drag,
2144                                value: drag_value,
2145                                cursor_offset,
2146                                cursor_style: drag_cursor_style,
2147                            });
2148                            pending_mouse_down.take();
2149                            window.refresh();
2150                            cx.stop_propagation();
2151                        }
2152                    }
2153                });
2154
2155                if is_focused {
2156                    // Press enter, space to trigger click, when the element is focused.
2157                    window.on_key_event({
2158                        let click_listeners = click_listeners.clone();
2159                        let hitbox = hitbox.clone();
2160                        move |event: &KeyUpEvent, phase, window, cx| {
2161                            if phase.bubble() && !window.default_prevented() {
2162                                let stroke = &event.keystroke;
2163                                let keyboard_button = if stroke.key.eq("enter") {
2164                                    Some(KeyboardButton::Enter)
2165                                } else if stroke.key.eq("space") {
2166                                    Some(KeyboardButton::Space)
2167                                } else {
2168                                    None
2169                                };
2170
2171                                if let Some(button) = keyboard_button
2172                                    && !stroke.modifiers.modified()
2173                                {
2174                                    let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2175                                        button,
2176                                        bounds: hitbox.bounds,
2177                                    });
2178
2179                                    for listener in &click_listeners {
2180                                        listener(&click_event, window, cx);
2181                                    }
2182                                }
2183                            }
2184                        }
2185                    });
2186                }
2187
2188                window.on_mouse_event({
2189                    let mut captured_mouse_down = None;
2190                    let hitbox = hitbox.clone();
2191                    move |event: &MouseUpEvent, phase, window, cx| match phase {
2192                        // Clear the pending mouse down during the capture phase,
2193                        // so that it happens even if another event handler stops
2194                        // propagation.
2195                        DispatchPhase::Capture => {
2196                            let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2197                            if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2198                                captured_mouse_down = pending_mouse_down.take();
2199                                window.refresh();
2200                            } else if pending_mouse_down.is_some() {
2201                                // Clear the pending mouse down event (without firing click handlers)
2202                                // if the hitbox is not being hovered.
2203                                // This avoids dragging elements that changed their position
2204                                // immediately after being clicked.
2205                                // See https://github.com/zed-industries/zed/issues/24600 for more details
2206                                pending_mouse_down.take();
2207                                window.refresh();
2208                            }
2209                        }
2210                        // Fire click handlers during the bubble phase.
2211                        DispatchPhase::Bubble => {
2212                            if let Some(mouse_down) = captured_mouse_down.take() {
2213                                let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2214                                    down: mouse_down,
2215                                    up: event.clone(),
2216                                });
2217                                for listener in &click_listeners {
2218                                    listener(&mouse_click, window, cx);
2219                                }
2220                            }
2221                        }
2222                    }
2223                });
2224            }
2225
2226            if let Some(hover_listener) = self.hover_listener.take() {
2227                let hitbox = hitbox.clone();
2228                let was_hovered = element_state
2229                    .hover_state
2230                    .get_or_insert_with(Default::default)
2231                    .clone();
2232                let has_mouse_down = element_state
2233                    .pending_mouse_down
2234                    .get_or_insert_with(Default::default)
2235                    .clone();
2236
2237                window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2238                    if phase != DispatchPhase::Bubble {
2239                        return;
2240                    }
2241                    let is_hovered = has_mouse_down.borrow().is_none()
2242                        && !cx.has_active_drag()
2243                        && hitbox.is_hovered(window);
2244                    let mut was_hovered = was_hovered.borrow_mut();
2245
2246                    if is_hovered != *was_hovered {
2247                        *was_hovered = is_hovered;
2248                        drop(was_hovered);
2249
2250                        hover_listener(&is_hovered, window, cx);
2251                    }
2252                });
2253            }
2254
2255            if let Some(tooltip_builder) = self.tooltip_builder.take() {
2256                let active_tooltip = element_state
2257                    .active_tooltip
2258                    .get_or_insert_with(Default::default)
2259                    .clone();
2260                let pending_mouse_down = element_state
2261                    .pending_mouse_down
2262                    .get_or_insert_with(Default::default)
2263                    .clone();
2264
2265                let tooltip_is_hoverable = tooltip_builder.hoverable;
2266                let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
2267                    Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
2268                });
2269                // Use bounds instead of testing hitbox since this is called during prepaint.
2270                let check_is_hovered_during_prepaint = Rc::new({
2271                    let pending_mouse_down = pending_mouse_down.clone();
2272                    let source_bounds = hitbox.bounds;
2273                    move |window: &Window| {
2274                        pending_mouse_down.borrow().is_none()
2275                            && source_bounds.contains(&window.mouse_position())
2276                    }
2277                });
2278                let check_is_hovered = Rc::new({
2279                    let hitbox = hitbox.clone();
2280                    move |window: &Window| {
2281                        pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
2282                    }
2283                });
2284                register_tooltip_mouse_handlers(
2285                    &active_tooltip,
2286                    self.tooltip_id,
2287                    build_tooltip,
2288                    check_is_hovered,
2289                    check_is_hovered_during_prepaint,
2290                    window,
2291                );
2292            }
2293
2294            let active_state = element_state
2295                .clicked_state
2296                .get_or_insert_with(Default::default)
2297                .clone();
2298            if active_state.borrow().is_clicked() {
2299                window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
2300                    if phase == DispatchPhase::Capture {
2301                        *active_state.borrow_mut() = ElementClickedState::default();
2302                        window.refresh();
2303                    }
2304                });
2305            } else {
2306                let active_group_hitbox = self
2307                    .group_active_style
2308                    .as_ref()
2309                    .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
2310                let hitbox = hitbox.clone();
2311                window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
2312                    if phase == DispatchPhase::Bubble && !window.default_prevented() {
2313                        let group_hovered = active_group_hitbox
2314                            .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
2315                        let element_hovered = hitbox.is_hovered(window);
2316                        if group_hovered || element_hovered {
2317                            *active_state.borrow_mut() = ElementClickedState {
2318                                group: group_hovered,
2319                                element: element_hovered,
2320                            };
2321                            window.refresh();
2322                        }
2323                    }
2324                });
2325            }
2326        }
2327    }
2328
2329    fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
2330        let key_down_listeners = mem::take(&mut self.key_down_listeners);
2331        let key_up_listeners = mem::take(&mut self.key_up_listeners);
2332        let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
2333        let action_listeners = mem::take(&mut self.action_listeners);
2334        if let Some(context) = self.key_context.clone() {
2335            window.set_key_context(context);
2336        }
2337
2338        for listener in key_down_listeners {
2339            window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
2340                listener(event, phase, window, cx);
2341            })
2342        }
2343
2344        for listener in key_up_listeners {
2345            window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
2346                listener(event, phase, window, cx);
2347            })
2348        }
2349
2350        for listener in modifiers_changed_listeners {
2351            window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
2352                listener(event, window, cx);
2353            })
2354        }
2355
2356        for (action_type, listener) in action_listeners {
2357            window.on_action(action_type, listener)
2358        }
2359    }
2360
2361    fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
2362        let group_hitbox = self
2363            .group_hover_style
2364            .as_ref()
2365            .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
2366
2367        if let Some(group_hitbox) = group_hitbox {
2368            let was_hovered = group_hitbox.is_hovered(window);
2369            let current_view = window.current_view();
2370            window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2371                let hovered = group_hitbox.is_hovered(window);
2372                if phase == DispatchPhase::Capture && hovered != was_hovered {
2373                    cx.notify(current_view);
2374                }
2375            });
2376        }
2377    }
2378
2379    fn paint_scroll_listener(
2380        &self,
2381        hitbox: &Hitbox,
2382        style: &Style,
2383        window: &mut Window,
2384        _cx: &mut App,
2385    ) {
2386        if let Some(scroll_offset) = self.scroll_offset.clone() {
2387            let overflow = style.overflow;
2388            let allow_concurrent_scroll = style.allow_concurrent_scroll;
2389            let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
2390            let line_height = window.line_height();
2391            let hitbox = hitbox.clone();
2392            let current_view = window.current_view();
2393            window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2394                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
2395                    let mut scroll_offset = scroll_offset.borrow_mut();
2396                    let old_scroll_offset = *scroll_offset;
2397                    let delta = event.delta.pixel_delta(line_height);
2398
2399                    let mut delta_x = Pixels::ZERO;
2400                    if overflow.x == Overflow::Scroll {
2401                        if !delta.x.is_zero() {
2402                            delta_x = delta.x;
2403                        } else if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll {
2404                            delta_x = delta.y;
2405                        }
2406                    }
2407                    let mut delta_y = Pixels::ZERO;
2408                    if overflow.y == Overflow::Scroll {
2409                        if !delta.y.is_zero() {
2410                            delta_y = delta.y;
2411                        } else if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll {
2412                            delta_y = delta.x;
2413                        }
2414                    }
2415                    if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
2416                        if delta_x.abs() > delta_y.abs() {
2417                            delta_y = Pixels::ZERO;
2418                        } else {
2419                            delta_x = Pixels::ZERO;
2420                        }
2421                    }
2422                    scroll_offset.y += delta_y;
2423                    scroll_offset.x += delta_x;
2424                    if *scroll_offset != old_scroll_offset {
2425                        cx.notify(current_view);
2426                    }
2427                }
2428            });
2429        }
2430    }
2431
2432    /// Compute the visual style for this element, based on the current bounds and the element's state.
2433    pub fn compute_style(
2434        &self,
2435        global_id: Option<&GlobalElementId>,
2436        hitbox: Option<&Hitbox>,
2437        window: &mut Window,
2438        cx: &mut App,
2439    ) -> Style {
2440        window.with_optional_element_state(global_id, |element_state, window| {
2441            let mut element_state =
2442                element_state.map(|element_state| element_state.unwrap_or_default());
2443            let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2444            (style, element_state)
2445        })
2446    }
2447
2448    /// Called from internal methods that have already called with_element_state.
2449    fn compute_style_internal(
2450        &self,
2451        hitbox: Option<&Hitbox>,
2452        element_state: Option<&mut InteractiveElementState>,
2453        window: &mut Window,
2454        cx: &mut App,
2455    ) -> Style {
2456        let mut style = Style::default();
2457        style.refine(&self.base_style);
2458
2459        if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2460            if let Some(in_focus_style) = self.in_focus_style.as_ref()
2461                && focus_handle.within_focused(window, cx)
2462            {
2463                style.refine(in_focus_style);
2464            }
2465
2466            if let Some(focus_style) = self.focus_style.as_ref()
2467                && focus_handle.is_focused(window)
2468            {
2469                style.refine(focus_style);
2470            }
2471        }
2472
2473        if let Some(hitbox) = hitbox {
2474            if !cx.has_active_drag() {
2475                if let Some(group_hover) = self.group_hover_style.as_ref()
2476                    && let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx)
2477                    && group_hitbox_id.is_hovered(window)
2478                {
2479                    style.refine(&group_hover.style);
2480                }
2481
2482                if let Some(hover_style) = self.hover_style.as_ref()
2483                    && hitbox.is_hovered(window)
2484                {
2485                    style.refine(hover_style);
2486                }
2487            }
2488
2489            if let Some(drag) = cx.active_drag.take() {
2490                let mut can_drop = true;
2491                if let Some(can_drop_predicate) = &self.can_drop_predicate {
2492                    can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
2493                }
2494
2495                if can_drop {
2496                    for (state_type, group_drag_style) in &self.group_drag_over_styles {
2497                        if let Some(group_hitbox_id) =
2498                            GroupHitboxes::get(&group_drag_style.group, cx)
2499                            && *state_type == drag.value.as_ref().type_id()
2500                            && group_hitbox_id.is_hovered(window)
2501                        {
2502                            style.refine(&group_drag_style.style);
2503                        }
2504                    }
2505
2506                    for (state_type, build_drag_over_style) in &self.drag_over_styles {
2507                        if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
2508                        {
2509                            style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
2510                        }
2511                    }
2512                }
2513
2514                style.mouse_cursor = drag.cursor_style;
2515                cx.active_drag = Some(drag);
2516            }
2517        }
2518
2519        if let Some(element_state) = element_state {
2520            let clicked_state = element_state
2521                .clicked_state
2522                .get_or_insert_with(Default::default)
2523                .borrow();
2524            if clicked_state.group
2525                && let Some(group) = self.group_active_style.as_ref()
2526            {
2527                style.refine(&group.style)
2528            }
2529
2530            if let Some(active_style) = self.active_style.as_ref()
2531                && clicked_state.element
2532            {
2533                style.refine(active_style)
2534            }
2535        }
2536
2537        style
2538    }
2539}
2540
2541/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks
2542/// and scroll offsets.
2543#[derive(Default)]
2544pub struct InteractiveElementState {
2545    pub(crate) focus_handle: Option<FocusHandle>,
2546    pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
2547    pub(crate) hover_state: Option<Rc<RefCell<bool>>>,
2548    pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
2549    pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2550    pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
2551}
2552
2553/// Whether or not the element or a group that contains it is clicked by the mouse.
2554#[derive(Copy, Clone, Default, Eq, PartialEq)]
2555pub struct ElementClickedState {
2556    /// True if this element's group has been clicked, false otherwise
2557    pub group: bool,
2558
2559    /// True if this element has been clicked, false otherwise
2560    pub element: bool,
2561}
2562
2563impl ElementClickedState {
2564    fn is_clicked(&self) -> bool {
2565        self.group || self.element
2566    }
2567}
2568
2569pub(crate) enum ActiveTooltip {
2570    /// Currently delaying before showing the tooltip.
2571    WaitingForShow { _task: Task<()> },
2572    /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
2573    Visible {
2574        tooltip: AnyTooltip,
2575        is_hoverable: bool,
2576    },
2577    /// Tooltip is visible and hoverable, but the mouse is no longer hovering. Currently delaying
2578    /// before hiding it.
2579    WaitingForHide {
2580        tooltip: AnyTooltip,
2581        _task: Task<()>,
2582    },
2583}
2584
2585pub(crate) fn clear_active_tooltip(
2586    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2587    window: &mut Window,
2588) {
2589    match active_tooltip.borrow_mut().take() {
2590        None => {}
2591        Some(ActiveTooltip::WaitingForShow { .. }) => {}
2592        Some(ActiveTooltip::Visible { .. }) => window.refresh(),
2593        Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
2594    }
2595}
2596
2597pub(crate) fn clear_active_tooltip_if_not_hoverable(
2598    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2599    window: &mut Window,
2600) {
2601    let should_clear = match active_tooltip.borrow().as_ref() {
2602        None => false,
2603        Some(ActiveTooltip::WaitingForShow { .. }) => false,
2604        Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
2605        Some(ActiveTooltip::WaitingForHide { .. }) => false,
2606    };
2607    if should_clear {
2608        active_tooltip.borrow_mut().take();
2609        window.refresh();
2610    }
2611}
2612
2613pub(crate) fn set_tooltip_on_window(
2614    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2615    window: &mut Window,
2616) -> Option<TooltipId> {
2617    let tooltip = match active_tooltip.borrow().as_ref() {
2618        None => return None,
2619        Some(ActiveTooltip::WaitingForShow { .. }) => return None,
2620        Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
2621        Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
2622    };
2623    Some(window.set_tooltip(tooltip))
2624}
2625
2626pub(crate) fn register_tooltip_mouse_handlers(
2627    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2628    tooltip_id: Option<TooltipId>,
2629    build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
2630    check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
2631    check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
2632    window: &mut Window,
2633) {
2634    window.on_mouse_event({
2635        let active_tooltip = active_tooltip.clone();
2636        let build_tooltip = build_tooltip.clone();
2637        let check_is_hovered = check_is_hovered.clone();
2638        move |_: &MouseMoveEvent, phase, window, cx| {
2639            handle_tooltip_mouse_move(
2640                &active_tooltip,
2641                &build_tooltip,
2642                &check_is_hovered,
2643                &check_is_hovered_during_prepaint,
2644                phase,
2645                window,
2646                cx,
2647            )
2648        }
2649    });
2650
2651    window.on_mouse_event({
2652        let active_tooltip = active_tooltip.clone();
2653        move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
2654            if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
2655                clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
2656            }
2657        }
2658    });
2659
2660    window.on_mouse_event({
2661        let active_tooltip = active_tooltip.clone();
2662        move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
2663            if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
2664                clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
2665            }
2666        }
2667    });
2668}
2669
2670/// Handles displaying tooltips when an element is hovered.
2671///
2672/// The mouse hovering logic also relies on being called from window prepaint in order to handle the
2673/// case where the element the tooltip is on is not rendered - in that case its mouse listeners are
2674/// also not registered. During window prepaint, the hitbox information is not available, so
2675/// `check_is_hovered_during_prepaint` is used which bases the check off of the absolute bounds of
2676/// the element.
2677///
2678/// TODO: There's a minor bug due to the use of absolute bounds while checking during prepaint - it
2679/// does not know if the hitbox is occluded. In the case where a tooltip gets displayed and then
2680/// gets occluded after display, it will stick around until the mouse exits the hover bounds.
2681fn handle_tooltip_mouse_move(
2682    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2683    build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
2684    check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
2685    check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
2686    phase: DispatchPhase,
2687    window: &mut Window,
2688    cx: &mut App,
2689) {
2690    // Separates logic for what mutation should occur from applying it, to avoid overlapping
2691    // RefCell borrows.
2692    enum Action {
2693        None,
2694        CancelShow,
2695        ScheduleShow,
2696    }
2697
2698    let action = match active_tooltip.borrow().as_ref() {
2699        None => {
2700            let is_hovered = check_is_hovered(window);
2701            if is_hovered && phase.bubble() {
2702                Action::ScheduleShow
2703            } else {
2704                Action::None
2705            }
2706        }
2707        Some(ActiveTooltip::WaitingForShow { .. }) => {
2708            let is_hovered = check_is_hovered(window);
2709            if is_hovered {
2710                Action::None
2711            } else {
2712                Action::CancelShow
2713            }
2714        }
2715        // These are handled in check_visible_and_update.
2716        Some(ActiveTooltip::Visible { .. }) | Some(ActiveTooltip::WaitingForHide { .. }) => {
2717            Action::None
2718        }
2719    };
2720
2721    match action {
2722        Action::None => {}
2723        Action::CancelShow => {
2724            // Cancel waiting to show tooltip when it is no longer hovered.
2725            active_tooltip.borrow_mut().take();
2726        }
2727        Action::ScheduleShow => {
2728            let delayed_show_task = window.spawn(cx, {
2729                let active_tooltip = active_tooltip.clone();
2730                let build_tooltip = build_tooltip.clone();
2731                let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
2732                async move |cx| {
2733                    cx.background_executor().timer(TOOLTIP_SHOW_DELAY).await;
2734                    cx.update(|window, cx| {
2735                        let new_tooltip =
2736                            build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
2737                                let active_tooltip = active_tooltip.clone();
2738                                ActiveTooltip::Visible {
2739                                    tooltip: AnyTooltip {
2740                                        view,
2741                                        mouse_position: window.mouse_position(),
2742                                        check_visible_and_update: Rc::new(
2743                                            move |tooltip_bounds, window, cx| {
2744                                                handle_tooltip_check_visible_and_update(
2745                                                    &active_tooltip,
2746                                                    tooltip_is_hoverable,
2747                                                    &check_is_hovered_during_prepaint,
2748                                                    tooltip_bounds,
2749                                                    window,
2750                                                    cx,
2751                                                )
2752                                            },
2753                                        ),
2754                                    },
2755                                    is_hoverable: tooltip_is_hoverable,
2756                                }
2757                            });
2758                        *active_tooltip.borrow_mut() = new_tooltip;
2759                        window.refresh();
2760                    })
2761                    .ok();
2762                }
2763            });
2764            active_tooltip
2765                .borrow_mut()
2766                .replace(ActiveTooltip::WaitingForShow {
2767                    _task: delayed_show_task,
2768                });
2769        }
2770    }
2771}
2772
2773/// Returns a callback which will be called by window prepaint to update tooltip visibility. The
2774/// purpose of doing this logic here instead of the mouse move handler is that the mouse move
2775/// handler won't get called when the element is not painted (e.g. via use of `visible_on_hover`).
2776fn handle_tooltip_check_visible_and_update(
2777    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2778    tooltip_is_hoverable: bool,
2779    check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
2780    tooltip_bounds: Bounds<Pixels>,
2781    window: &mut Window,
2782    cx: &mut App,
2783) -> bool {
2784    // Separates logic for what mutation should occur from applying it, to avoid overlapping RefCell
2785    // borrows.
2786    enum Action {
2787        None,
2788        Hide,
2789        ScheduleHide(AnyTooltip),
2790        CancelHide(AnyTooltip),
2791    }
2792
2793    let is_hovered = check_is_hovered(window)
2794        || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
2795    let action = match active_tooltip.borrow().as_ref() {
2796        Some(ActiveTooltip::Visible { tooltip, .. }) => {
2797            if is_hovered {
2798                Action::None
2799            } else {
2800                if tooltip_is_hoverable {
2801                    Action::ScheduleHide(tooltip.clone())
2802                } else {
2803                    Action::Hide
2804                }
2805            }
2806        }
2807        Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
2808            if is_hovered {
2809                Action::CancelHide(tooltip.clone())
2810            } else {
2811                Action::None
2812            }
2813        }
2814        None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
2815    };
2816
2817    match action {
2818        Action::None => {}
2819        Action::Hide => clear_active_tooltip(active_tooltip, window),
2820        Action::ScheduleHide(tooltip) => {
2821            let delayed_hide_task = window.spawn(cx, {
2822                let active_tooltip = active_tooltip.clone();
2823                async move |cx| {
2824                    cx.background_executor()
2825                        .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
2826                        .await;
2827                    if active_tooltip.borrow_mut().take().is_some() {
2828                        cx.update(|window, _cx| window.refresh()).ok();
2829                    }
2830                }
2831            });
2832            active_tooltip
2833                .borrow_mut()
2834                .replace(ActiveTooltip::WaitingForHide {
2835                    tooltip,
2836                    _task: delayed_hide_task,
2837                });
2838        }
2839        Action::CancelHide(tooltip) => {
2840            // Cancel waiting to hide tooltip when it becomes hovered.
2841            active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
2842                tooltip,
2843                is_hoverable: true,
2844            });
2845        }
2846    }
2847
2848    active_tooltip.borrow().is_some()
2849}
2850
2851#[derive(Default)]
2852pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
2853
2854impl Global for GroupHitboxes {}
2855
2856impl GroupHitboxes {
2857    pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
2858        cx.default_global::<Self>()
2859            .0
2860            .get(name)
2861            .and_then(|bounds_stack| bounds_stack.last())
2862            .cloned()
2863    }
2864
2865    pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
2866        cx.default_global::<Self>()
2867            .0
2868            .entry(name)
2869            .or_default()
2870            .push(hitbox_id);
2871    }
2872
2873    pub fn pop(name: &SharedString, cx: &mut App) {
2874        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
2875    }
2876}
2877
2878/// A wrapper around an element that can store state, produced after assigning an ElementId.
2879pub struct Stateful<E> {
2880    pub(crate) element: E,
2881}
2882
2883impl<E> Styled for Stateful<E>
2884where
2885    E: Styled,
2886{
2887    fn style(&mut self) -> &mut StyleRefinement {
2888        self.element.style()
2889    }
2890}
2891
2892impl<E> StatefulInteractiveElement for Stateful<E>
2893where
2894    E: Element,
2895    Self: InteractiveElement,
2896{
2897}
2898
2899impl<E> InteractiveElement for Stateful<E>
2900where
2901    E: InteractiveElement,
2902{
2903    fn interactivity(&mut self) -> &mut Interactivity {
2904        self.element.interactivity()
2905    }
2906}
2907
2908impl<E> Element for Stateful<E>
2909where
2910    E: Element,
2911{
2912    type RequestLayoutState = E::RequestLayoutState;
2913    type PrepaintState = E::PrepaintState;
2914
2915    fn id(&self) -> Option<ElementId> {
2916        self.element.id()
2917    }
2918
2919    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
2920        self.element.source_location()
2921    }
2922
2923    fn request_layout(
2924        &mut self,
2925        id: Option<&GlobalElementId>,
2926        inspector_id: Option<&InspectorElementId>,
2927        window: &mut Window,
2928        cx: &mut App,
2929    ) -> (LayoutId, Self::RequestLayoutState) {
2930        self.element.request_layout(id, inspector_id, window, cx)
2931    }
2932
2933    fn prepaint(
2934        &mut self,
2935        id: Option<&GlobalElementId>,
2936        inspector_id: Option<&InspectorElementId>,
2937        bounds: Bounds<Pixels>,
2938        state: &mut Self::RequestLayoutState,
2939        window: &mut Window,
2940        cx: &mut App,
2941    ) -> E::PrepaintState {
2942        self.element
2943            .prepaint(id, inspector_id, bounds, state, window, cx)
2944    }
2945
2946    fn paint(
2947        &mut self,
2948        id: Option<&GlobalElementId>,
2949        inspector_id: Option<&InspectorElementId>,
2950        bounds: Bounds<Pixels>,
2951        request_layout: &mut Self::RequestLayoutState,
2952        prepaint: &mut Self::PrepaintState,
2953        window: &mut Window,
2954        cx: &mut App,
2955    ) {
2956        self.element.paint(
2957            id,
2958            inspector_id,
2959            bounds,
2960            request_layout,
2961            prepaint,
2962            window,
2963            cx,
2964        );
2965    }
2966}
2967
2968impl<E> IntoElement for Stateful<E>
2969where
2970    E: Element,
2971{
2972    type Element = Self;
2973
2974    fn into_element(self) -> Self::Element {
2975        self
2976    }
2977}
2978
2979impl<E> ParentElement for Stateful<E>
2980where
2981    E: ParentElement,
2982{
2983    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
2984        self.element.extend(elements)
2985    }
2986}
2987
2988/// Represents an element that can be scrolled *to* in its parent element.
2989///
2990/// Contrary to [ScrollHandle::scroll_to_item], an anchored element does not have to be an immediate child of the parent.
2991#[derive(Clone)]
2992pub struct ScrollAnchor {
2993    handle: ScrollHandle,
2994    last_origin: Rc<RefCell<Point<Pixels>>>,
2995}
2996
2997impl ScrollAnchor {
2998    /// Creates a [ScrollAnchor] associated with a given [ScrollHandle].
2999    pub fn for_handle(handle: ScrollHandle) -> Self {
3000        Self {
3001            handle,
3002            last_origin: Default::default(),
3003        }
3004    }
3005    /// Request scroll to this item on the next frame.
3006    pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
3007        let this = self.clone();
3008
3009        window.on_next_frame(move |_, _| {
3010            let viewport_bounds = this.handle.bounds();
3011            let self_bounds = *this.last_origin.borrow();
3012            this.handle.set_offset(viewport_bounds.origin - self_bounds);
3013        });
3014    }
3015}
3016
3017#[derive(Default, Debug)]
3018struct ScrollHandleState {
3019    offset: Rc<RefCell<Point<Pixels>>>,
3020    bounds: Bounds<Pixels>,
3021    max_offset: Size<Pixels>,
3022    child_bounds: Vec<Bounds<Pixels>>,
3023    scroll_to_bottom: bool,
3024    overflow: Point<Overflow>,
3025}
3026
3027/// A handle to the scrollable aspects of an element.
3028/// Used for accessing scroll state, like the current scroll offset,
3029/// and for mutating the scroll state, like scrolling to a specific child.
3030#[derive(Clone, Debug)]
3031pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
3032
3033impl Default for ScrollHandle {
3034    fn default() -> Self {
3035        Self::new()
3036    }
3037}
3038
3039impl ScrollHandle {
3040    /// Construct a new scroll handle.
3041    pub fn new() -> Self {
3042        Self(Rc::default())
3043    }
3044
3045    /// Get the current scroll offset.
3046    pub fn offset(&self) -> Point<Pixels> {
3047        *self.0.borrow().offset.borrow()
3048    }
3049
3050    /// Get the maximum scroll offset.
3051    pub fn max_offset(&self) -> Size<Pixels> {
3052        self.0.borrow().max_offset
3053    }
3054
3055    /// Get the top child that's scrolled into view.
3056    pub fn top_item(&self) -> usize {
3057        let state = self.0.borrow();
3058        let top = state.bounds.top() - state.offset.borrow().y;
3059
3060        match state.child_bounds.binary_search_by(|bounds| {
3061            if top < bounds.top() {
3062                Ordering::Greater
3063            } else if top > bounds.bottom() {
3064                Ordering::Less
3065            } else {
3066                Ordering::Equal
3067            }
3068        }) {
3069            Ok(ix) => ix,
3070            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
3071        }
3072    }
3073
3074    /// Return the bounds into which this child is painted
3075    pub fn bounds(&self) -> Bounds<Pixels> {
3076        self.0.borrow().bounds
3077    }
3078
3079    /// Get the bounds for a specific child.
3080    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
3081        self.0.borrow().child_bounds.get(ix).cloned()
3082    }
3083
3084    /// scroll_to_item scrolls the minimal amount to ensure that the child is
3085    /// fully visible
3086    pub fn scroll_to_item(&self, ix: usize) {
3087        let state = self.0.borrow();
3088
3089        let Some(bounds) = state.child_bounds.get(ix) else {
3090            return;
3091        };
3092
3093        let mut scroll_offset = state.offset.borrow_mut();
3094
3095        if state.overflow.y == Overflow::Scroll {
3096            if bounds.top() + scroll_offset.y < state.bounds.top() {
3097                scroll_offset.y = state.bounds.top() - bounds.top();
3098            } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
3099                scroll_offset.y = state.bounds.bottom() - bounds.bottom();
3100            }
3101        }
3102
3103        if state.overflow.x == Overflow::Scroll {
3104            if bounds.left() + scroll_offset.x < state.bounds.left() {
3105                scroll_offset.x = state.bounds.left() - bounds.left();
3106            } else if bounds.right() + scroll_offset.x > state.bounds.right() {
3107                scroll_offset.x = state.bounds.right() - bounds.right();
3108            }
3109        }
3110    }
3111
3112    /// Scrolls to the bottom.
3113    pub fn scroll_to_bottom(&self) {
3114        let mut state = self.0.borrow_mut();
3115        state.scroll_to_bottom = true;
3116    }
3117
3118    /// Set the offset explicitly. The offset is the distance from the top left of the
3119    /// parent container to the top left of the first child.
3120    /// As you scroll further down the offset becomes more negative.
3121    pub fn set_offset(&self, mut position: Point<Pixels>) {
3122        let state = self.0.borrow();
3123        *state.offset.borrow_mut() = position;
3124    }
3125
3126    /// Get the logical scroll top, based on a child index and a pixel offset.
3127    pub fn logical_scroll_top(&self) -> (usize, Pixels) {
3128        let ix = self.top_item();
3129        let state = self.0.borrow();
3130
3131        if let Some(child_bounds) = state.child_bounds.get(ix) {
3132            (
3133                ix,
3134                child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
3135            )
3136        } else {
3137            (ix, px(0.))
3138        }
3139    }
3140
3141    /// Get the count of children for scrollable item.
3142    pub fn children_count(&self) -> usize {
3143        self.0.borrow().child_bounds.len()
3144    }
3145}