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