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