div.rs

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