div.rs

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