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