div.rs

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