Skip to main content

gpui/elements/
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    Display, Element, ElementId, Entity, EntityId, ExternalDragPayload, ExternalDragPayloadSource,
21    FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, HitboxId, InspectorElementId,
22    IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, KeyboardButton, KeyboardClickEvent,
23    LayoutId, ModifiersChangedEvent, MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent,
24    MouseMoveEvent, MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement,
25    PinchEvent, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style,
26    StyleRefinement, Styled, Task, TooltipId, Visibility, Window, WindowControlArea, point, px,
27    size,
28};
29use collections::HashMap;
30use gpui_util::ResultExt;
31use refineable::Refineable;
32use smallvec::SmallVec;
33use stacksafe::{StackSafe, stacksafe};
34use std::{
35    any::{Any, TypeId},
36    cell::RefCell,
37    cmp::Ordering,
38    fmt::Debug,
39    marker::PhantomData,
40    mem,
41    rc::Rc,
42    sync::Arc,
43    time::Duration,
44};
45
46use super::ImageCacheProvider;
47
48const DRAG_THRESHOLD: f64 = 2.;
49const DEFAULT_TOOLTIP_SHOW_DELAY: Duration = Duration::from_millis(500);
50const HOVERABLE_TOOLTIP_HIDE_DELAY: Duration = Duration::from_millis(500);
51
52/// The styling information for a given group.
53pub struct GroupStyle {
54    /// The identifier for this group.
55    pub group: SharedString,
56
57    /// The specific style refinement that this group would apply
58    /// to its children.
59    pub style: Box<StyleRefinement>,
60}
61
62/// An event for when a drag is moving over this element, with the given state type.
63pub struct DragMoveEvent<T> {
64    /// The mouse move event that triggered this drag move event.
65    pub event: MouseMoveEvent,
66
67    /// The bounds of this element.
68    pub bounds: Bounds<Pixels>,
69    drag: PhantomData<T>,
70    dragged_item: Arc<dyn Any>,
71}
72
73impl<T: 'static> DragMoveEvent<T> {
74    /// Returns the drag state for this event.
75    pub fn drag<'b>(&self, cx: &'b App) -> &'b T {
76        cx.active_drag
77            .as_ref()
78            .and_then(|drag| drag.value.downcast_ref::<T>())
79            .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
80    }
81
82    /// An item that is about to be dropped.
83    pub fn dragged_item(&self) -> &dyn Any {
84        self.dragged_item.as_ref()
85    }
86}
87
88impl Interactivity {
89    /// Create an `Interactivity`, capturing the caller location in debug mode.
90    #[cfg(any(feature = "inspector", debug_assertions))]
91    #[track_caller]
92    pub fn new() -> Interactivity {
93        Interactivity {
94            source_location: Some(core::panic::Location::caller()),
95            ..Default::default()
96        }
97    }
98
99    /// Create an `Interactivity`, capturing the caller location in debug mode.
100    #[cfg(not(any(feature = "inspector", debug_assertions)))]
101    pub fn new() -> Interactivity {
102        Interactivity::default()
103    }
104
105    /// Gets the source location of construction. Returns `None` when not in debug mode.
106    pub fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
107        #[cfg(any(feature = "inspector", debug_assertions))]
108        {
109            self.source_location
110        }
111
112        #[cfg(not(any(feature = "inspector", debug_assertions)))]
113        {
114            None
115        }
116    }
117
118    /// Bind the given callback to the mouse down event for the given mouse button, during the bubble phase.
119    /// The imperative API equivalent of [`InteractiveElement::on_mouse_down`].
120    ///
121    /// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
122    pub fn on_mouse_down(
123        &mut self,
124        button: MouseButton,
125        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
126    ) {
127        self.mouse_down_listeners
128            .push(Box::new(move |event, phase, hitbox, window, cx| {
129                if phase == DispatchPhase::Bubble
130                    && event.button == button
131                    && hitbox.is_hovered(window)
132                {
133                    (listener)(event, window, cx)
134                }
135            }));
136    }
137
138    /// Bind the given callback to the mouse down event for any button, during the capture phase.
139    /// The imperative API equivalent of [`InteractiveElement::capture_any_mouse_down`].
140    ///
141    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
142    pub fn capture_any_mouse_down(
143        &mut self,
144        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
145    ) {
146        self.mouse_down_listeners
147            .push(Box::new(move |event, phase, hitbox, window, cx| {
148                if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
149                    (listener)(event, window, cx)
150                }
151            }));
152    }
153
154    /// Bind the given callback to the mouse down event for any button, during the bubble phase.
155    /// The imperative API equivalent to [`InteractiveElement::on_any_mouse_down`].
156    ///
157    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
158    pub fn on_any_mouse_down(
159        &mut self,
160        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
161    ) {
162        self.mouse_down_listeners
163            .push(Box::new(move |event, phase, hitbox, window, cx| {
164                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
165                    (listener)(event, window, cx)
166                }
167            }));
168    }
169
170    /// Bind the given callback to the mouse pressure event, during the bubble phase
171    /// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
172    ///
173    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
174    pub fn on_mouse_pressure(
175        &mut self,
176        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
177    ) {
178        self.mouse_pressure_listeners
179            .push(Box::new(move |event, phase, hitbox, window, cx| {
180                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
181                    (listener)(event, window, cx)
182                }
183            }));
184    }
185
186    /// Bind the given callback to the mouse pressure event, during the capture phase
187    /// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
188    ///
189    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
190    pub fn capture_mouse_pressure(
191        &mut self,
192        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
193    ) {
194        self.mouse_pressure_listeners
195            .push(Box::new(move |event, phase, hitbox, window, cx| {
196                if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
197                    (listener)(event, window, cx)
198                }
199            }));
200    }
201
202    /// Bind the given callback to the mouse up event for the given button, during the bubble phase.
203    /// The imperative API equivalent to [`InteractiveElement::on_mouse_up`].
204    ///
205    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
206    pub fn on_mouse_up(
207        &mut self,
208        button: MouseButton,
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
214                    && event.button == button
215                    && hitbox.is_hovered(window)
216                {
217                    (listener)(event, window, cx)
218                }
219            }));
220    }
221
222    /// Bind the given callback to the mouse up event for any button, during the capture phase.
223    /// The imperative API equivalent to [`InteractiveElement::capture_any_mouse_up`].
224    ///
225    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
226    pub fn capture_any_mouse_up(
227        &mut self,
228        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
229    ) {
230        self.mouse_up_listeners
231            .push(Box::new(move |event, phase, hitbox, window, cx| {
232                if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
233                    (listener)(event, window, cx)
234                }
235            }));
236    }
237
238    /// Bind the given callback to the mouse up event for any button, during the bubble phase.
239    /// The imperative API equivalent to [`Interactivity::on_any_mouse_up`].
240    ///
241    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
242    pub fn on_any_mouse_up(
243        &mut self,
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::Bubble && hitbox.is_hovered(window) {
249                    (listener)(event, window, cx)
250                }
251            }));
252    }
253
254    /// Bind the given callback to the mouse down event, on any button, during the capture phase,
255    /// when the mouse is outside of the bounds of this element.
256    /// The imperative API equivalent to [`InteractiveElement::on_mouse_down_out`].
257    ///
258    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
259    pub fn on_mouse_down_out(
260        &mut self,
261        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
262    ) {
263        self.mouse_down_listeners
264            .push(Box::new(move |event, phase, hitbox, window, cx| {
265                if phase == DispatchPhase::Capture
266                    && !window.has_active_prompt()
267                    && !hitbox.contains(&window.mouse_position())
268                {
269                    (listener)(event, window, cx)
270                }
271            }));
272    }
273
274    /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
275    /// when the mouse is outside of the bounds of this element.
276    /// The imperative API equivalent to [`InteractiveElement::on_mouse_up_out`].
277    ///
278    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
279    pub fn on_mouse_up_out(
280        &mut self,
281        button: MouseButton,
282        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
283    ) {
284        self.mouse_up_listeners
285            .push(Box::new(move |event, phase, hitbox, window, cx| {
286                if phase == DispatchPhase::Capture
287                    && event.button == button
288                    && !hitbox.is_hovered(window)
289                {
290                    (listener)(event, window, cx);
291                }
292            }));
293    }
294
295    /// Bind the given callback to the mouse move event, during the bubble phase.
296    /// The imperative API equivalent to [`InteractiveElement::on_mouse_move`].
297    ///
298    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
299    pub fn on_mouse_move(
300        &mut self,
301        listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
302    ) {
303        self.mouse_move_listeners
304            .push(Box::new(move |event, phase, hitbox, window, cx| {
305                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
306                    (listener)(event, window, cx);
307                }
308            }));
309    }
310
311    /// Bind the given callback to the mouse exit event, during the bubble phase.
312    /// The imperative API equivalent to [`InteractiveElement::on_mouse_exit`].
313    ///
314    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
315    pub fn on_mouse_exit(
316        &mut self,
317        listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
318    ) {
319        self.mouse_exit_listeners
320            .push(Box::new(move |event, phase, hitbox, window, cx| {
321                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
322                    (listener)(event, window, cx);
323                }
324            }));
325    }
326
327    /// Bind the given callback to the mouse drag event of the given type. Note that this
328    /// will be called for all move events, inside or outside of this element, as long as the
329    /// drag was started with this element under the mouse. Useful for implementing draggable
330    /// UIs that don't conform to a drag and drop style interaction, like resizing.
331    /// The imperative API equivalent to [`InteractiveElement::on_drag_move`].
332    ///
333    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
334    pub fn on_drag_move<T>(
335        &mut self,
336        listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
337    ) where
338        T: 'static,
339    {
340        self.mouse_move_listeners
341            .push(Box::new(move |event, phase, hitbox, window, cx| {
342                if phase == DispatchPhase::Capture
343                    && let Some(drag) = &cx.active_drag
344                    && drag.value.as_ref().type_id() == TypeId::of::<T>()
345                {
346                    (listener)(
347                        &DragMoveEvent {
348                            event: event.clone(),
349                            bounds: hitbox.bounds,
350                            drag: PhantomData,
351                            dragged_item: Arc::clone(&drag.value),
352                        },
353                        window,
354                        cx,
355                    );
356                }
357            }));
358    }
359
360    /// Bind the given callback to scroll wheel events during the bubble phase.
361    /// The imperative API equivalent to [`InteractiveElement::on_scroll_wheel`].
362    ///
363    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
364    pub fn on_scroll_wheel(
365        &mut self,
366        listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
367    ) {
368        self.scroll_wheel_listeners
369            .push(Box::new(move |event, phase, hitbox, window, cx| {
370                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
371                    (listener)(event, window, cx);
372                }
373            }));
374    }
375
376    /// Bind the given callback to pinch gesture events during the bubble phase.
377    ///
378    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
379    pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
380        self.pinch_listeners
381            .push(Box::new(move |event, phase, hitbox, window, cx| {
382                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
383                    (listener)(event, window, cx);
384                }
385            }));
386    }
387
388    /// Bind the given callback to pinch gesture events during the capture phase.
389    ///
390    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
391    pub fn capture_pinch(
392        &mut self,
393        listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
394    ) {
395        self.pinch_listeners
396            .push(Box::new(move |event, phase, _hitbox, window, cx| {
397                if phase == DispatchPhase::Capture {
398                    (listener)(event, window, cx);
399                } else {
400                    cx.propagate();
401                }
402            }));
403    }
404
405    /// Bind the given callback to an action dispatch during the capture phase.
406    /// The imperative API equivalent to [`InteractiveElement::capture_action`].
407    ///
408    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
409    pub fn capture_action<A: Action>(
410        &mut self,
411        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
412    ) {
413        self.action_listeners.push((
414            TypeId::of::<A>(),
415            Box::new(move |action, phase, window, cx| {
416                let action = action.downcast_ref().unwrap();
417                if phase == DispatchPhase::Capture {
418                    (listener)(action, window, cx)
419                } else {
420                    cx.propagate();
421                }
422            }),
423        ));
424    }
425
426    /// Bind the given callback to an action dispatch during the bubble phase.
427    /// The imperative API equivalent to [`InteractiveElement::on_action`].
428    ///
429    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
430    #[track_caller]
431    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
432        self.action_listeners.push((
433            TypeId::of::<A>(),
434            Box::new(move |action, phase, window, cx| {
435                let action = action.downcast_ref().unwrap();
436                if phase == DispatchPhase::Bubble {
437                    (listener)(action, window, cx)
438                }
439            }),
440        ));
441    }
442
443    /// Bind the given callback to an action dispatch, based on a dynamic action parameter
444    /// instead of a type parameter. Useful for component libraries that want to expose
445    /// action bindings to their users.
446    /// The imperative API equivalent to [`InteractiveElement::on_boxed_action`].
447    ///
448    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
449    pub fn on_boxed_action(
450        &mut self,
451        action: &dyn Action,
452        listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
453    ) {
454        let action = action.boxed_clone();
455        self.action_listeners.push((
456            (*action).type_id(),
457            Box::new(move |_, phase, window, cx| {
458                if phase == DispatchPhase::Bubble {
459                    (listener)(&*action, window, cx)
460                }
461            }),
462        ));
463    }
464
465    /// Bind the given callback to key down events during the bubble phase.
466    /// The imperative API equivalent to [`InteractiveElement::on_key_down`].
467    ///
468    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
469    pub fn on_key_down(
470        &mut self,
471        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
472    ) {
473        self.key_down_listeners
474            .push(Box::new(move |event, phase, window, cx| {
475                if phase == DispatchPhase::Bubble {
476                    (listener)(event, window, cx)
477                }
478            }));
479    }
480
481    /// Bind the given callback to key down events during the capture phase.
482    /// The imperative API equivalent to [`InteractiveElement::capture_key_down`].
483    ///
484    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
485    pub fn capture_key_down(
486        &mut self,
487        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
488    ) {
489        self.key_down_listeners
490            .push(Box::new(move |event, phase, window, cx| {
491                if phase == DispatchPhase::Capture {
492                    listener(event, window, cx)
493                }
494            }));
495    }
496
497    /// Bind the given callback to key up events during the bubble phase.
498    /// The imperative API equivalent to [`InteractiveElement::on_key_up`].
499    ///
500    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
501    pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
502        self.key_up_listeners
503            .push(Box::new(move |event, phase, window, cx| {
504                if phase == DispatchPhase::Bubble {
505                    listener(event, window, cx)
506                }
507            }));
508    }
509
510    /// Bind the given callback to key up events during the capture phase.
511    /// The imperative API equivalent to [`InteractiveElement::on_key_up`].
512    ///
513    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
514    pub fn capture_key_up(
515        &mut self,
516        listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
517    ) {
518        self.key_up_listeners
519            .push(Box::new(move |event, phase, window, cx| {
520                if phase == DispatchPhase::Capture {
521                    listener(event, window, cx)
522                }
523            }));
524    }
525
526    /// Bind the given callback to modifiers changing events.
527    /// The imperative API equivalent to [`InteractiveElement::on_modifiers_changed`].
528    ///
529    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
530    pub fn on_modifiers_changed(
531        &mut self,
532        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
533    ) {
534        self.modifiers_changed_listeners
535            .push(Box::new(move |event, window, cx| {
536                listener(event, window, cx)
537            }));
538    }
539
540    /// Bind the given callback to drop events of the given type, whether or not the drag started on this element.
541    /// The imperative API equivalent to [`InteractiveElement::on_drop`].
542    ///
543    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
544    pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
545        self.drop_listeners.push((
546            TypeId::of::<T>(),
547            Box::new(move |dragged_value, window, cx| {
548                listener(dragged_value.downcast_ref().unwrap(), window, cx);
549            }),
550        ));
551    }
552
553    /// Use the given predicate to determine whether or not a drop event should be dispatched to this element.
554    /// The imperative API equivalent to [`InteractiveElement::can_drop`].
555    pub fn can_drop(
556        &mut self,
557        predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
558    ) {
559        self.can_drop_predicate = Some(Box::new(predicate));
560    }
561
562    /// Bind the given callback to click events of this element.
563    /// The imperative API equivalent to [`StatefulInteractiveElement::on_click`].
564    ///
565    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
566    pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
567    where
568        Self: Sized,
569    {
570        self.click_listeners.push(Rc::new(move |event, window, cx| {
571            listener(event, window, cx)
572        }));
573    }
574
575    /// Bind the given callback to non-primary click events of this element.
576    /// The imperative API equivalent to [`StatefulInteractiveElement::on_aux_click`].
577    ///
578    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
579    pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
580    where
581        Self: Sized,
582    {
583        self.aux_click_listeners
584            .push(Rc::new(move |event, window, cx| {
585                listener(event, window, cx)
586            }));
587    }
588
589    /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
590    /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
591    /// the [`Self::on_drag_move`] API.
592    /// The imperative API equivalent to [`StatefulInteractiveElement::on_drag`].
593    ///
594    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
595    pub fn on_drag<T, W>(
596        &mut self,
597        value: T,
598        constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
599    ) where
600        Self: Sized,
601        T: 'static,
602        W: 'static + Render,
603    {
604        debug_assert!(
605            self.drag_listener.is_none(),
606            "calling on_drag more than once on the same element is not supported"
607        );
608        self.drag_listener = Some(DragListener {
609            value: Arc::new(value),
610            render: Box::new(move |value, offset, window, cx| {
611                constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
612            }),
613            external_payload: None,
614        });
615    }
616
617    /// Registers a callback resolving a payload to offer the platform if a drag started by this
618    /// element leaves the window. It is invoked at most once per drag gesture, when the pointer
619    /// exits the viewport. Must be called after [`Self::on_drag`], with the same dragged value
620    /// type `T`.
621    pub fn external_drag_payload<T>(
622        &mut self,
623        resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
624    ) where
625        Self: Sized,
626        T: 'static,
627    {
628        let Some(drag_listener) = self.drag_listener.as_mut() else {
629            debug_assert!(false, "external_drag_payload must be called after on_drag");
630            return;
631        };
632        debug_assert!(
633            drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
634            "external_drag_payload must use the same dragged value type as on_drag"
635        );
636        debug_assert!(
637            drag_listener.external_payload.is_none(),
638            "calling external_drag_payload more than once on the same element is not supported"
639        );
640        drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
641            resolver(value.downcast_ref::<T>()?, window, cx)
642        }));
643    }
644
645    /// Bind the given callback on the hover start and end events of this element. Note that the boolean
646    /// passed to the callback is true when the hover starts and false when it ends.
647    /// The imperative API equivalent to [`StatefulInteractiveElement::on_hover`].
648    ///
649    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
650    pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
651    where
652        Self: Sized,
653    {
654        debug_assert!(
655            self.hover_listener.is_none(),
656            "calling on_hover more than once on the same element is not supported"
657        );
658        self.hover_listener = Some(Box::new(listener));
659    }
660
661    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
662    /// The imperative API equivalent to [`StatefulInteractiveElement::tooltip`].
663    pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
664    where
665        Self: Sized,
666    {
667        debug_assert!(
668            self.tooltip_builder.is_none(),
669            "calling tooltip more than once on the same element is not supported"
670        );
671        self.tooltip_builder = Some(TooltipBuilder {
672            build: Rc::new(build_tooltip),
673            hoverable: false,
674        });
675    }
676
677    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
678    /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
679    /// the tooltip. The imperative API equivalent to [`StatefulInteractiveElement::hoverable_tooltip`].
680    pub fn hoverable_tooltip(
681        &mut self,
682        build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
683    ) where
684        Self: Sized,
685    {
686        debug_assert!(
687            self.tooltip_builder.is_none(),
688            "calling tooltip more than once on the same element is not supported"
689        );
690        self.tooltip_builder = Some(TooltipBuilder {
691            build: Rc::new(build_tooltip),
692            hoverable: true,
693        });
694    }
695
696    /// Set the delay before this element's tooltip is shown.
697    /// The imperative API equivalent to [`StatefulInteractiveElement::tooltip_show_delay`].
698    pub fn tooltip_show_delay(&mut self, delay: Duration) {
699        self.tooltip_show_delay = Some(delay);
700    }
701
702    /// Block the mouse from all interactions with elements behind this element's hitbox. Typically
703    /// `block_mouse_except_scroll` should be preferred.
704    ///
705    /// The imperative API equivalent to [`InteractiveElement::occlude`]
706    pub fn occlude_mouse(&mut self) {
707        self.hitbox_behavior = HitboxBehavior::BlockMouse;
708    }
709
710    /// Set the bounds of this element as a window control area for the platform window.
711    /// The imperative API equivalent to [`InteractiveElement::window_control_area`]
712    pub fn window_control_area(&mut self, area: WindowControlArea) {
713        self.window_control = Some(area);
714    }
715
716    /// Block non-scroll mouse interactions with elements behind this element's hitbox.
717    /// The imperative API equivalent to [`InteractiveElement::block_mouse_except_scroll`].
718    ///
719    /// See [`Hitbox::is_hovered`] for details.
720    pub fn block_mouse_except_scroll(&mut self) {
721        self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
722    }
723
724    fn has_pinch_listeners(&self) -> bool {
725        !self.pinch_listeners.is_empty()
726    }
727}
728
729/// A trait for elements that want to use the standard GPUI event handlers that don't
730/// require any state.
731pub trait InteractiveElement: Sized {
732    /// Retrieve the interactivity state associated with this element
733    fn interactivity(&mut self) -> &mut Interactivity;
734
735    /// Assign this element to a group of elements that can be styled together
736    fn group(mut self, group: impl Into<SharedString>) -> Self {
737        self.interactivity().group = Some(group.into());
738        self
739    }
740
741    /// Assign this element an ID, so that it can be used with interactivity
742    fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
743        self.interactivity().element_id = Some(id.into());
744
745        Stateful { element: self }
746    }
747
748    /// Track the focus state of the given focus handle on this element.
749    /// If the focus handle is focused by the application, this element will
750    /// apply its focused styles.
751    fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
752        self.interactivity().focusable = true;
753        self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
754        self
755    }
756
757    /// Set whether this element is a tab stop.
758    ///
759    /// When false, the element remains in tab-index order but cannot be reached via keyboard navigation.
760    /// Useful for container elements: focus the container, then call `window.focus_next(cx)` to focus
761    /// the first tab stop inside it while having the container element itself be unreachable via the keyboard.
762    /// Should only be used with `tab_index`.
763    fn tab_stop(mut self, tab_stop: bool) -> Self {
764        self.interactivity().tab_stop = tab_stop;
765        self
766    }
767
768    /// Set index of the tab stop order, and set this node as a tab stop.
769    /// This will default the element to being a tab stop. See [`Self::tab_stop`] for more information.
770    /// This should only be used in conjunction with `tab_group`
771    /// in order to not interfere with the tab index of other elements.
772    fn tab_index(mut self, index: isize) -> Self {
773        self.interactivity().focusable = true;
774        self.interactivity().tab_index = Some(index);
775        self.interactivity().tab_stop = true;
776        self
777    }
778
779    /// Designate this div as a "tab group". Tab groups have their own location in the tab-index order,
780    /// but for children of the tab group, the tab index is reset to 0. This can be useful for swapping
781    /// the order of tab stops within the group, without having to renumber all the tab stops in the whole
782    /// application.
783    fn tab_group(mut self) -> Self {
784        self.interactivity().tab_group = true;
785        if self.interactivity().tab_index.is_none() {
786            self.interactivity().tab_index = Some(0);
787        }
788        self
789    }
790
791    /// Set the keymap context for this element. This will be used to determine
792    /// which action to dispatch from the keymap.
793    fn key_context<C, E>(mut self, key_context: C) -> Self
794    where
795        C: TryInto<KeyContext, Error = E>,
796        E: std::fmt::Display,
797    {
798        if let Some(key_context) = key_context.try_into().log_err() {
799            self.interactivity().key_context = Some(key_context);
800        }
801        self
802    }
803
804    /// Apply the given style to this element when the mouse hovers over it
805    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
806        debug_assert!(
807            self.interactivity().hover_style.is_none(),
808            "hover style already set"
809        );
810        self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
811        self
812    }
813
814    /// Apply the given style to this element when the mouse hovers over a group member
815    fn group_hover(
816        mut self,
817        group_name: impl Into<SharedString>,
818        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
819    ) -> Self {
820        self.interactivity().group_hover_style = Some(GroupStyle {
821            group: group_name.into(),
822            style: Box::new(f(StyleRefinement::default())),
823        });
824        self
825    }
826
827    /// Bind the given callback to the mouse down event for the given mouse button.
828    /// The fluent API equivalent to [`Interactivity::on_mouse_down`].
829    ///
830    /// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
831    fn on_mouse_down(
832        mut self,
833        button: MouseButton,
834        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
835    ) -> Self {
836        self.interactivity().on_mouse_down(button, listener);
837        self
838    }
839
840    #[cfg(any(test, feature = "test-support"))]
841    /// Set a key that can be used to look up this element's bounds
842    /// in the [`crate::VisualTestContext::debug_bounds`] map
843    /// This is a noop in release builds
844    fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
845        self.interactivity().debug_selector = Some(f());
846        self
847    }
848
849    #[cfg(not(any(test, feature = "test-support")))]
850    /// Set a key that can be used to look up this element's bounds
851    /// in the [`crate::VisualTestContext::debug_bounds`] map
852    /// This is a noop in release builds
853    #[inline]
854    fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
855        self
856    }
857
858    /// Bind the given callback to the mouse down event for any button, during the capture phase.
859    /// The fluent API equivalent to [`Interactivity::capture_any_mouse_down`].
860    ///
861    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
862    fn capture_any_mouse_down(
863        mut self,
864        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
865    ) -> Self {
866        self.interactivity().capture_any_mouse_down(listener);
867        self
868    }
869
870    /// Bind the given callback to the mouse down event for any button, during the capture phase.
871    /// The fluent API equivalent to [`Interactivity::on_any_mouse_down`].
872    ///
873    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
874    fn on_any_mouse_down(
875        mut self,
876        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
877    ) -> Self {
878        self.interactivity().on_any_mouse_down(listener);
879        self
880    }
881
882    /// Bind the given callback to the mouse up event for the given button, during the bubble phase.
883    /// The fluent API equivalent to [`Interactivity::on_mouse_up`].
884    ///
885    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
886    fn on_mouse_up(
887        mut self,
888        button: MouseButton,
889        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
890    ) -> Self {
891        self.interactivity().on_mouse_up(button, listener);
892        self
893    }
894
895    /// Bind the given callback to the mouse up event for any button, during the capture phase.
896    /// The fluent API equivalent to [`Interactivity::capture_any_mouse_up`].
897    ///
898    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
899    fn capture_any_mouse_up(
900        mut self,
901        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
902    ) -> Self {
903        self.interactivity().capture_any_mouse_up(listener);
904        self
905    }
906
907    /// Bind the given callback to the mouse pressure event, during the bubble phase
908    /// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
909    ///
910    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
911    fn on_mouse_pressure(
912        mut self,
913        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
914    ) -> Self {
915        self.interactivity().on_mouse_pressure(listener);
916        self
917    }
918
919    /// Bind the given callback to the mouse pressure event, during the capture phase
920    /// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
921    ///
922    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
923    fn capture_mouse_pressure(
924        mut self,
925        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
926    ) -> Self {
927        self.interactivity().capture_mouse_pressure(listener);
928        self
929    }
930
931    /// Bind the given callback to the mouse down event, on any button, during the capture phase,
932    /// when the mouse is outside of the bounds of this element.
933    /// The fluent API equivalent to [`Interactivity::on_mouse_down_out`].
934    ///
935    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
936    fn on_mouse_down_out(
937        mut self,
938        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
939    ) -> Self {
940        self.interactivity().on_mouse_down_out(listener);
941        self
942    }
943
944    /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
945    /// when the mouse is outside of the bounds of this element.
946    /// The fluent API equivalent to [`Interactivity::on_mouse_up_out`].
947    ///
948    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
949    fn on_mouse_up_out(
950        mut self,
951        button: MouseButton,
952        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
953    ) -> Self {
954        self.interactivity().on_mouse_up_out(button, listener);
955        self
956    }
957
958    /// Bind the given callback to the mouse move event, during the bubble phase.
959    /// The fluent API equivalent to [`Interactivity::on_mouse_move`].
960    ///
961    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
962    fn on_mouse_move(
963        mut self,
964        listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
965    ) -> Self {
966        self.interactivity().on_mouse_move(listener);
967        self
968    }
969
970    /// Bind the given callback to the mouse exit event, during the bubble phase.
971    /// The fluent API equivalent to [`Interactivity::on_mouse_exit`].
972    ///
973    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
974    fn on_mouse_exit(
975        mut self,
976        listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
977    ) -> Self {
978        self.interactivity().on_mouse_exit(listener);
979        self
980    }
981
982    /// Bind the given callback to the mouse drag event of the given type. Note that this
983    /// will be called for all move events, inside or outside of this element, as long as the
984    /// drag was started with this element under the mouse. Useful for implementing draggable
985    /// UIs that don't conform to a drag and drop style interaction, like resizing.
986    /// The fluent API equivalent to [`Interactivity::on_drag_move`].
987    ///
988    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
989    fn on_drag_move<T: 'static>(
990        mut self,
991        listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
992    ) -> Self {
993        self.interactivity().on_drag_move(listener);
994        self
995    }
996
997    /// Bind the given callback to scroll wheel events during the bubble phase.
998    /// The fluent API equivalent to [`Interactivity::on_scroll_wheel`].
999    ///
1000    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1001    fn on_scroll_wheel(
1002        mut self,
1003        listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
1004    ) -> Self {
1005        self.interactivity().on_scroll_wheel(listener);
1006        self
1007    }
1008
1009    /// Bind the given callback to pinch gesture events during the bubble phase.
1010    /// The fluent API equivalent to [`Interactivity::on_pinch`].
1011    ///
1012    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1013    fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
1014        self.interactivity().on_pinch(listener);
1015        self
1016    }
1017
1018    /// Bind the given callback to pinch gesture events during the capture phase.
1019    /// The fluent API equivalent to [`Interactivity::capture_pinch`].
1020    ///
1021    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1022    fn capture_pinch(
1023        mut self,
1024        listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
1025    ) -> Self {
1026        self.interactivity().capture_pinch(listener);
1027        self
1028    }
1029    /// Capture the given action, before normal action dispatch can fire.
1030    /// The fluent API equivalent to [`Interactivity::capture_action`].
1031    ///
1032    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1033    fn capture_action<A: Action>(
1034        mut self,
1035        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1036    ) -> Self {
1037        self.interactivity().capture_action(listener);
1038        self
1039    }
1040
1041    /// Bind the given callback to an action dispatch during the bubble phase.
1042    /// The fluent API equivalent to [`Interactivity::on_action`].
1043    ///
1044    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1045    #[track_caller]
1046    fn on_action<A: Action>(
1047        mut self,
1048        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1049    ) -> Self {
1050        self.interactivity().on_action(listener);
1051        self
1052    }
1053
1054    /// Bind the given callback to an action dispatch, based on a dynamic action parameter
1055    /// instead of a type parameter. Useful for component libraries that want to expose
1056    /// action bindings to their users.
1057    /// The fluent API equivalent to [`Interactivity::on_boxed_action`].
1058    ///
1059    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1060    fn on_boxed_action(
1061        mut self,
1062        action: &dyn Action,
1063        listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1064    ) -> Self {
1065        self.interactivity().on_boxed_action(action, listener);
1066        self
1067    }
1068
1069    /// Bind the given callback to key down events during the bubble phase.
1070    /// The fluent API equivalent to [`Interactivity::on_key_down`].
1071    ///
1072    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1073    fn on_key_down(
1074        mut self,
1075        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1076    ) -> Self {
1077        self.interactivity().on_key_down(listener);
1078        self
1079    }
1080
1081    /// Bind the given callback to key down events during the capture phase.
1082    /// The fluent API equivalent to [`Interactivity::capture_key_down`].
1083    ///
1084    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1085    fn capture_key_down(
1086        mut self,
1087        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1088    ) -> Self {
1089        self.interactivity().capture_key_down(listener);
1090        self
1091    }
1092
1093    /// Bind the given callback to key up events during the bubble phase.
1094    /// The fluent API equivalent to [`Interactivity::on_key_up`].
1095    ///
1096    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1097    fn on_key_up(
1098        mut self,
1099        listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1100    ) -> Self {
1101        self.interactivity().on_key_up(listener);
1102        self
1103    }
1104
1105    /// Bind the given callback to key up events during the capture phase.
1106    /// The fluent API equivalent to [`Interactivity::capture_key_up`].
1107    ///
1108    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1109    fn capture_key_up(
1110        mut self,
1111        listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1112    ) -> Self {
1113        self.interactivity().capture_key_up(listener);
1114        self
1115    }
1116
1117    /// Bind the given callback to modifiers changing events.
1118    /// The fluent API equivalent to [`Interactivity::on_modifiers_changed`].
1119    ///
1120    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1121    fn on_modifiers_changed(
1122        mut self,
1123        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1124    ) -> Self {
1125        self.interactivity().on_modifiers_changed(listener);
1126        self
1127    }
1128
1129    /// Apply the given style when the given data type is dragged over this element
1130    fn drag_over<S: 'static>(
1131        mut self,
1132        f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1133    ) -> Self {
1134        self.interactivity().drag_over_styles.push((
1135            TypeId::of::<S>(),
1136            Box::new(move |currently_dragged: &dyn Any, window, cx| {
1137                f(
1138                    StyleRefinement::default(),
1139                    currently_dragged.downcast_ref::<S>().unwrap(),
1140                    window,
1141                    cx,
1142                )
1143            }),
1144        ));
1145        self
1146    }
1147
1148    /// Apply the given style when the given data type is dragged over this element's group
1149    fn group_drag_over<S: 'static>(
1150        mut self,
1151        group_name: impl Into<SharedString>,
1152        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1153    ) -> Self {
1154        self.interactivity().group_drag_over_styles.push((
1155            TypeId::of::<S>(),
1156            GroupStyle {
1157                group: group_name.into(),
1158                style: Box::new(f(StyleRefinement::default())),
1159            },
1160        ));
1161        self
1162    }
1163
1164    /// Bind the given callback to drop events of the given type, whether or not the drag started on this element.
1165    /// The fluent API equivalent to [`Interactivity::on_drop`].
1166    ///
1167    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1168    fn on_drop<T: 'static>(
1169        mut self,
1170        listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1171    ) -> Self {
1172        self.interactivity().on_drop(listener);
1173        self
1174    }
1175
1176    /// Use the given predicate to determine whether or not a drop event should be dispatched to this element.
1177    /// The fluent API equivalent to [`Interactivity::can_drop`].
1178    fn can_drop(
1179        mut self,
1180        predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1181    ) -> Self {
1182        self.interactivity().can_drop(predicate);
1183        self
1184    }
1185
1186    /// Block the mouse from all interactions with elements behind this element's hitbox. Typically
1187    /// `block_mouse_except_scroll` should be preferred.
1188    /// The fluent API equivalent to [`Interactivity::occlude_mouse`].
1189    fn occlude(mut self) -> Self {
1190        self.interactivity().occlude_mouse();
1191        self
1192    }
1193
1194    /// Set the bounds of this element as a window control area for the platform window.
1195    /// The fluent API equivalent to [`Interactivity::window_control_area`].
1196    fn window_control_area(mut self, area: WindowControlArea) -> Self {
1197        self.interactivity().window_control_area(area);
1198        self
1199    }
1200
1201    /// Block non-scroll mouse interactions with elements behind this element's hitbox.
1202    /// The fluent API equivalent to [`Interactivity::block_mouse_except_scroll`].
1203    ///
1204    /// See [`Hitbox::is_hovered`] for details.
1205    fn block_mouse_except_scroll(mut self) -> Self {
1206        self.interactivity().block_mouse_except_scroll();
1207        self
1208    }
1209
1210    /// Set the given styles to be applied when this element, specifically, is focused.
1211    /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1212    fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1213    where
1214        Self: Sized,
1215    {
1216        self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1217        self
1218    }
1219
1220    /// Set the given styles to be applied when this element is inside another element that is focused.
1221    /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1222    fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1223    where
1224        Self: Sized,
1225    {
1226        self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1227        self
1228    }
1229
1230    /// Set the given styles to be applied when this element is focused via keyboard navigation.
1231    /// This is similar to CSS's `:focus-visible` pseudo-class - it only applies when the element
1232    /// is focused AND the user is navigating via keyboard (not mouse clicks).
1233    /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1234    fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1235    where
1236        Self: Sized,
1237    {
1238        self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1239        self
1240    }
1241}
1242
1243/// A trait for elements that want to use the standard GPUI interactivity features
1244/// that require state.
1245pub trait StatefulInteractiveElement: InteractiveElement {
1246    /// Set the accessible role for this element.
1247    ///
1248    /// See the [accessibility guide](crate::_accessibility) for an overview.
1249    fn role(mut self, role: accesskit::Role) -> Self {
1250        debug_assert!(
1251            role != accesskit::Role::GenericContainer,
1252            "GenericContainer is filtered out of the a11y tree and has no effect"
1253        );
1254        self.interactivity().override_role = Some(role);
1255        self
1256    }
1257
1258    /// Set the accessible label for this element.
1259    fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1260        self.interactivity().aria.label = Some(label.into());
1261        self
1262    }
1263
1264    /// Set the accessible description for this element. Unlike the label (which
1265    /// names the element), the description provides supplementary information
1266    /// that assistive technology announces after the name, role, and value -
1267    /// for example a settings subtitle or a hint.
1268    fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
1269        self.interactivity().aria.description = Some(description.into());
1270        self
1271    }
1272
1273    /// Set the keyboard shortcut(s) that activate this element, announced by
1274    /// assistive technology (maps to AccessKit's `keyboard_shortcut`).
1275    ///
1276    /// Note that this does not create a keymap. It simply instructs assistive
1277    /// technology what the keymap is.
1278    fn aria_keyshortcuts(mut self, keyshortcuts: impl Into<SharedString>) -> Self {
1279        self.interactivity().aria.keyshortcuts = Some(keyshortcuts.into());
1280        self
1281    }
1282
1283    /// Report this element as the focused node in the accessibility tree,
1284    /// overriding the element that holds real keyboard focus — but only while
1285    /// one of its ancestors actually holds focus.
1286    ///
1287    /// This implements the `aria-activedescendant` pattern for composite
1288    /// widgets that keep keyboard focus on a container (e.g. a menu or
1289    /// listbox) while a child is "selected": set this on the selected child so
1290    /// assistive technology announces and highlights it as focused.
1291    ///
1292    /// The element must also have a [`role`][Self::role] (and an id) so it
1293    /// produces an accessibility node. Unlike the web's container-side
1294    /// `aria-activedescendant`, this is set on the descendant; GPUI honors it
1295    /// only when a focused ancestor is present in the tree, so it is safe to
1296    /// set unconditionally on the selected child — if the container isn't
1297    /// focused, the claim is ignored.
1298    fn aria_active_descendant(mut self) -> Self {
1299        self.interactivity().report_active_descendant_focus = true;
1300        self
1301    }
1302
1303    /// Contribute synthetic accessibility nodes — nodes that don't correspond
1304    /// to any element — as children of this element's a11y node. For example,
1305    /// text runs describing an editor's text content.
1306    ///
1307    /// The closure is called after this element is prepainted, and only if it
1308    /// contributed a node to the accessibility tree (i.e. it has an id and a
1309    /// [`role`][StatefulInteractiveElement::role]).
1310    ///
1311    /// See [`Element::a11y_synthetic_children`] for details.
1312    fn a11y_synthetic_children(
1313        mut self,
1314        f: impl FnOnce(&mut crate::A11ySubtreeBuilder) + 'static,
1315    ) -> Self {
1316        self.interactivity().a11y_synthetic_children = Some(Box::new(f));
1317        self
1318    }
1319
1320    /// Set the selected state for this element.
1321    fn aria_selected(mut self, selected: bool) -> Self {
1322        self.interactivity().aria.selected = Some(selected);
1323        self
1324    }
1325
1326    /// Set the expanded state for this element.
1327    fn aria_expanded(mut self, expanded: bool) -> Self {
1328        self.interactivity().aria.expanded = Some(expanded);
1329        self
1330    }
1331
1332    /// Set the toggled state for this element.
1333    fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1334        self.interactivity().aria.toggled = Some(toggled);
1335        self
1336    }
1337
1338    /// Set the numeric value for this element.
1339    fn aria_numeric_value(mut self, value: f64) -> Self {
1340        self.interactivity().aria.numeric_value = Some(value);
1341        self
1342    }
1343
1344    /// Set the step by which assistive technology should expect the numeric
1345    /// value of this element to change (e.g. when incrementing a spin button).
1346    fn aria_numeric_value_step(mut self, step: f64) -> Self {
1347        self.interactivity().aria.numeric_value_step = Some(step);
1348        self
1349    }
1350
1351    /// Set the string value of this element, e.g. the text content of a simple
1352    /// text input.
1353    fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
1354        self.interactivity().aria.value = Some(value.into());
1355        self
1356    }
1357
1358    /// Set the placeholder text reported to assistive technology for this
1359    /// element, shown when a text input is empty.
1360    fn aria_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1361        self.interactivity().aria.placeholder = Some(placeholder.into());
1362        self
1363    }
1364
1365    /// Set the minimum numeric value for this element.
1366    fn aria_min_numeric_value(mut self, value: f64) -> Self {
1367        self.interactivity().aria.min_numeric_value = Some(value);
1368        self
1369    }
1370
1371    /// Set the maximum numeric value for this element.
1372    fn aria_max_numeric_value(mut self, value: f64) -> Self {
1373        self.interactivity().aria.max_numeric_value = Some(value);
1374        self
1375    }
1376
1377    /// Set the orientation of this element.
1378    fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1379        self.interactivity().aria.orientation = Some(orientation);
1380        self
1381    }
1382
1383    /// Set the heading level of this element.
1384    fn aria_level(mut self, level: usize) -> Self {
1385        self.interactivity().aria.level = Some(level);
1386        self
1387    }
1388
1389    /// Set the position in set of this element.
1390    fn aria_position_in_set(mut self, position: usize) -> Self {
1391        self.interactivity().aria.position_in_set = Some(position);
1392        self
1393    }
1394
1395    /// Set the size of set for this element.
1396    fn aria_size_of_set(mut self, size: usize) -> Self {
1397        self.interactivity().aria.size_of_set = Some(size);
1398        self
1399    }
1400
1401    /// Set the row index for this element.
1402    fn aria_row_index(mut self, index: usize) -> Self {
1403        self.interactivity().aria.row_index = Some(index);
1404        self
1405    }
1406
1407    /// Set the column index for this element.
1408    fn aria_column_index(mut self, index: usize) -> Self {
1409        self.interactivity().aria.column_index = Some(index);
1410        self
1411    }
1412
1413    /// Set the row count for this element.
1414    fn aria_row_count(mut self, count: usize) -> Self {
1415        self.interactivity().aria.row_count = Some(count);
1416        self
1417    }
1418
1419    /// Set the column count for this element.
1420    fn aria_column_count(mut self, count: usize) -> Self {
1421        self.interactivity().aria.column_count = Some(count);
1422        self
1423    }
1424
1425    /// Register a handler for an accessibility action on this element.
1426    /// The handler is called when a screen reader requests the given action.
1427    ///
1428    /// See the [accessibility guide](crate::_accessibility) for an overview.
1429    fn on_a11y_action(
1430        mut self,
1431        action: accesskit::Action,
1432        listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1433        + 'static,
1434    ) -> Self {
1435        self.interactivity()
1436            .a11y_action_listeners
1437            .push((action, Box::new(listener)));
1438        self
1439    }
1440
1441    /// Set this element to focusable.
1442    fn focusable(mut self) -> Self {
1443        self.interactivity().focusable = true;
1444        self
1445    }
1446
1447    /// Set the overflow x and y to scroll.
1448    fn overflow_scroll(mut self) -> Self {
1449        self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1450        self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1451        self
1452    }
1453
1454    /// Set the overflow x to scroll.
1455    fn overflow_x_scroll(mut self) -> Self {
1456        self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1457        self
1458    }
1459
1460    /// Set the overflow y to scroll.
1461    fn overflow_y_scroll(mut self) -> Self {
1462        self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1463        self
1464    }
1465
1466    /// Restrict scrolling of this element to the axis of the input gesture.
1467    ///
1468    /// See [`Style::restrict_scroll_to_axis`](crate::Style::restrict_scroll_to_axis) for details.
1469    fn restrict_scroll_to_axis(mut self) -> Self {
1470        self.interactivity().base_style.restrict_scroll_to_axis = Some(true);
1471        self
1472    }
1473
1474    /// Track the scroll state of this element with the given handle.
1475    fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1476        self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1477        self
1478    }
1479
1480    /// Track the scroll state of this element with the given handle.
1481    fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1482        self.interactivity().scroll_anchor = scroll_anchor;
1483        self
1484    }
1485
1486    /// Set the given styles to be applied when this element is active.
1487    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1488    where
1489        Self: Sized,
1490    {
1491        self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1492        self
1493    }
1494
1495    /// Set the given styles to be applied when this element's group is active.
1496    fn group_active(
1497        mut self,
1498        group_name: impl Into<SharedString>,
1499        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1500    ) -> Self
1501    where
1502        Self: Sized,
1503    {
1504        self.interactivity().group_active_style = Some(GroupStyle {
1505            group: group_name.into(),
1506            style: Box::new(f(StyleRefinement::default())),
1507        });
1508        self
1509    }
1510
1511    /// Bind the given callback to click events of this element.
1512    /// The fluent API equivalent to [`Interactivity::on_click`].
1513    ///
1514    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1515    fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1516    where
1517        Self: Sized,
1518    {
1519        self.interactivity().on_click(listener);
1520        self
1521    }
1522
1523    /// Bind the given callback to non-primary click events of this element.
1524    /// The fluent API equivalent to [`Interactivity::on_aux_click`].
1525    ///
1526    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1527    fn on_aux_click(
1528        mut self,
1529        listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1530    ) -> Self
1531    where
1532        Self: Sized,
1533    {
1534        self.interactivity().on_aux_click(listener);
1535        self
1536    }
1537
1538    /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
1539    /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
1540    /// the [`InteractiveElement::on_drag_move`] API.
1541    /// The callback also has access to the offset of triggering click from the origin of parent element.
1542    /// The fluent API equivalent to [`Interactivity::on_drag`].
1543    ///
1544    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1545    fn on_drag<T, W>(
1546        mut self,
1547        value: T,
1548        constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1549    ) -> Self
1550    where
1551        Self: Sized,
1552        T: 'static,
1553        W: 'static + Render,
1554    {
1555        self.interactivity().on_drag(value, constructor);
1556        self
1557    }
1558
1559    /// Registers a callback resolving a payload to offer the platform if a drag started by this
1560    /// element leaves the window. It is invoked at most once per drag gesture, when the pointer
1561    /// exits the viewport. Must be called after [`Self::on_drag`], with the same dragged value
1562    /// type `T`.
1563    /// The fluent API equivalent to [`Interactivity::external_drag_payload`].
1564    fn external_drag_payload<T>(
1565        mut self,
1566        resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
1567    ) -> Self
1568    where
1569        Self: Sized,
1570        T: 'static,
1571    {
1572        self.interactivity().external_drag_payload(resolver);
1573        self
1574    }
1575
1576    /// Bind the given callback on the hover start and end events of this element. Note that the boolean
1577    /// passed to the callback is true when the hover starts and false when it ends.
1578    /// The fluent API equivalent to [`Interactivity::on_hover`].
1579    ///
1580    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1581    fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1582    where
1583        Self: Sized,
1584    {
1585        self.interactivity().on_hover(listener);
1586        self
1587    }
1588
1589    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
1590    /// The fluent API equivalent to [`Interactivity::tooltip`].
1591    fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1592    where
1593        Self: Sized,
1594    {
1595        self.interactivity().tooltip(build_tooltip);
1596        self
1597    }
1598
1599    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
1600    /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
1601    /// the tooltip. The fluent API equivalent to [`Interactivity::hoverable_tooltip`].
1602    fn hoverable_tooltip(
1603        mut self,
1604        build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1605    ) -> Self
1606    where
1607        Self: Sized,
1608    {
1609        self.interactivity().hoverable_tooltip(build_tooltip);
1610        self
1611    }
1612
1613    /// Set the delay before this element's tooltip is shown.
1614    /// The fluent API equivalent to [`Interactivity::tooltip_show_delay`].
1615    fn tooltip_show_delay(mut self, delay: Duration) -> Self
1616    where
1617        Self: Sized,
1618    {
1619        self.interactivity().tooltip_show_delay(delay);
1620        self
1621    }
1622}
1623
1624pub(crate) type MouseDownListener =
1625    Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1626pub(crate) type MouseUpListener =
1627    Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1628pub(crate) type MousePressureListener =
1629    Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1630pub(crate) type MouseMoveListener =
1631    Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1632pub(crate) type MouseExitListener =
1633    Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1634
1635pub(crate) type ScrollWheelListener =
1636    Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1637
1638pub(crate) type PinchListener =
1639    Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1640
1641pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1642
1643pub(crate) struct DragListener {
1644    value: Arc<dyn Any>,
1645    render: Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>,
1646    external_payload: Option<ExternalDragPayloadResolver>,
1647}
1648
1649type ExternalDragPayloadResolver =
1650    Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
1651
1652type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1653
1654type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1655
1656pub(crate) struct TooltipBuilder {
1657    build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1658    hoverable: bool,
1659}
1660
1661pub(crate) type KeyDownListener =
1662    Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1663
1664pub(crate) type KeyUpListener =
1665    Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1666
1667pub(crate) type ModifiersChangedListener =
1668    Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1669
1670pub(crate) type ActionListener =
1671    Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1672
1673/// Construct a new [`Div`] element
1674#[track_caller]
1675pub fn div() -> Div {
1676    Div {
1677        interactivity: Interactivity::new(),
1678        children: SmallVec::default(),
1679        prepaint_listener: None,
1680        image_cache: None,
1681        prepaint_order_fn: None,
1682    }
1683}
1684
1685/// A [`Div`] element, the all-in-one element for building complex UIs in GPUI
1686pub struct Div {
1687    interactivity: Interactivity,
1688    children: SmallVec<[StackSafe<AnyElement>; 2]>,
1689    prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1690    image_cache: Option<Box<dyn ImageCacheProvider>>,
1691    prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1692}
1693
1694impl Div {
1695    /// Add a listener to be called when the children of this `Div` are prepainted.
1696    /// This allows you to store the [`Bounds`] of the children for later use.
1697    pub fn on_children_prepainted(
1698        mut self,
1699        listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1700    ) -> Self {
1701        self.prepaint_listener = Some(Box::new(listener));
1702        self
1703    }
1704
1705    /// Add an image cache at the location of this div in the element tree.
1706    pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1707        self.image_cache = Some(Box::new(cache));
1708        self
1709    }
1710
1711    /// Specify a function that determines the order in which children are prepainted.
1712    ///
1713    /// The function is called at prepaint time and should return a vector of child indices
1714    /// in the desired prepaint order. Each index should appear exactly once.
1715    ///
1716    /// This is useful when the prepaint of one child affects state that another child reads.
1717    /// For example, in split editor views, the editor with an autoscroll request should
1718    /// be prepainted first so its scroll position update is visible to the other editor.
1719    pub fn with_dynamic_prepaint_order(
1720        mut self,
1721        order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1722    ) -> Self {
1723        self.prepaint_order_fn = Some(Box::new(order_fn));
1724        self
1725    }
1726}
1727
1728/// A frame state for a `Div` element, which contains layout IDs for its children.
1729///
1730/// This struct is used internally by the `Div` element to manage the layout state of its children
1731/// during the UI update cycle. It holds a small vector of `LayoutId` values, each corresponding to
1732/// a child element of the `Div`. These IDs are used to query the layout engine for the computed
1733/// bounds of the children after the layout phase is complete.
1734pub struct DivFrameState {
1735    child_layout_ids: SmallVec<[LayoutId; 2]>,
1736}
1737
1738/// Interactivity state displayed an manipulated in the inspector.
1739#[derive(Clone)]
1740pub struct DivInspectorState {
1741    /// The inspected element's base style. This is used for both inspecting and modifying the
1742    /// state. In the future it will make sense to separate the read and write, possibly tracking
1743    /// the modifications.
1744    #[cfg(any(feature = "inspector", debug_assertions))]
1745    pub base_style: Box<StyleRefinement>,
1746    /// Inspects the bounds of the element.
1747    pub bounds: Bounds<Pixels>,
1748    /// Size of the children of the element, or `bounds.size` if it has no children.
1749    pub content_size: Size<Pixels>,
1750}
1751
1752impl Styled for Div {
1753    fn style(&mut self) -> &mut StyleRefinement {
1754        &mut self.interactivity.base_style
1755    }
1756}
1757
1758impl InteractiveElement for Div {
1759    fn interactivity(&mut self) -> &mut Interactivity {
1760        &mut self.interactivity
1761    }
1762}
1763
1764impl ParentElement for Div {
1765    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1766        self.children
1767            .extend(elements.into_iter().map(StackSafe::new))
1768    }
1769}
1770
1771impl Element for Div {
1772    type RequestLayoutState = DivFrameState;
1773    type PrepaintState = Option<Hitbox>;
1774
1775    fn id(&self) -> Option<ElementId> {
1776        self.interactivity.element_id.clone()
1777    }
1778
1779    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1780        self.interactivity.source_location()
1781    }
1782
1783    fn a11y_role(&self) -> Option<accesskit::Role> {
1784        // Nodes with `GenericContainer` should never be reported to accesskit.
1785        // Equivalent to an HTML div with no role.
1786        self.interactivity
1787            .override_role
1788            .filter(|role| *role != accesskit::Role::GenericContainer)
1789    }
1790
1791    fn write_a11y_info(&self, node: &mut accesskit::Node) {
1792        self.interactivity.write_a11y_info(node);
1793    }
1794
1795    fn a11y_synthetic_children(
1796        &mut self,
1797        _prepaint: &mut Self::PrepaintState,
1798        builder: &mut crate::A11ySubtreeBuilder,
1799    ) {
1800        if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
1801            f(builder);
1802        }
1803    }
1804
1805    #[stacksafe]
1806    fn request_layout(
1807        &mut self,
1808        global_id: Option<&GlobalElementId>,
1809        inspector_id: Option<&InspectorElementId>,
1810        window: &mut Window,
1811        cx: &mut App,
1812    ) -> (LayoutId, Self::RequestLayoutState) {
1813        let mut child_layout_ids = SmallVec::new();
1814        let image_cache = self
1815            .image_cache
1816            .as_mut()
1817            .map(|provider| provider.provide(window, cx));
1818
1819        let layout_id = window.with_image_cache(image_cache, |window| {
1820            self.interactivity.request_layout(
1821                global_id,
1822                inspector_id,
1823                window,
1824                cx,
1825                |style, window, cx| {
1826                    window.with_text_style(style.text_style().cloned(), |window| {
1827                        child_layout_ids = self
1828                            .children
1829                            .iter_mut()
1830                            .map(|child| child.request_layout(window, cx))
1831                            .collect::<SmallVec<_>>();
1832                        window.request_layout(style, child_layout_ids.iter().copied(), cx)
1833                    })
1834                },
1835            )
1836        });
1837
1838        (layout_id, DivFrameState { child_layout_ids })
1839    }
1840
1841    #[stacksafe]
1842    fn prepaint(
1843        &mut self,
1844        global_id: Option<&GlobalElementId>,
1845        inspector_id: Option<&InspectorElementId>,
1846        bounds: Bounds<Pixels>,
1847        request_layout: &mut Self::RequestLayoutState,
1848        window: &mut Window,
1849        cx: &mut App,
1850    ) -> Option<Hitbox> {
1851        let image_cache = self
1852            .image_cache
1853            .as_mut()
1854            .map(|provider| provider.provide(window, cx));
1855
1856        let has_prepaint_listener = self.prepaint_listener.is_some();
1857        let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1858            request_layout.child_layout_ids.len()
1859        } else {
1860            0
1861        });
1862
1863        let mut child_min = point(Pixels::MAX, Pixels::MAX);
1864        let mut child_max = Point::default();
1865        if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1866            *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1867        }
1868        let content_size = if request_layout.child_layout_ids.is_empty() {
1869            bounds.size
1870        } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1871            let mut state = scroll_handle.0.borrow_mut();
1872            state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1873            for child_layout_id in &request_layout.child_layout_ids {
1874                let child_bounds = window.layout_bounds(*child_layout_id);
1875                child_min = child_min.min(&child_bounds.origin);
1876                child_max = child_max.max(&child_bounds.bottom_right());
1877                state.child_bounds.push(child_bounds);
1878            }
1879            (child_max - child_min).into()
1880        } else {
1881            for child_layout_id in &request_layout.child_layout_ids {
1882                let child_bounds = window.layout_bounds(*child_layout_id);
1883                child_min = child_min.min(&child_bounds.origin);
1884                child_max = child_max.max(&child_bounds.bottom_right());
1885
1886                if has_prepaint_listener {
1887                    children_bounds.push(child_bounds);
1888                }
1889            }
1890            (child_max - child_min).into()
1891        };
1892
1893        if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1894            scroll_handle.scroll_to_active_item();
1895        }
1896
1897        self.interactivity.prepaint(
1898            global_id,
1899            inspector_id,
1900            bounds,
1901            content_size,
1902            window,
1903            cx,
1904            |style, scroll_offset, hitbox, window, cx| {
1905                // skip children
1906                if style.display == Display::None {
1907                    return hitbox;
1908                }
1909
1910                window.with_image_cache(image_cache, |window| {
1911                    window.with_element_offset(scroll_offset, |window| {
1912                        if let Some(order_fn) = &self.prepaint_order_fn {
1913                            let order = order_fn(window, cx);
1914                            for idx in order {
1915                                if let Some(child) = self.children.get_mut(idx) {
1916                                    child.prepaint(window, cx);
1917                                }
1918                            }
1919                        } else {
1920                            for child in &mut self.children {
1921                                child.prepaint(window, cx);
1922                            }
1923                        }
1924                    });
1925
1926                    if let Some(listener) = self.prepaint_listener.as_ref() {
1927                        listener(children_bounds, window, cx);
1928                    }
1929                });
1930
1931                hitbox
1932            },
1933        )
1934    }
1935
1936    #[stacksafe]
1937    fn paint(
1938        &mut self,
1939        global_id: Option<&GlobalElementId>,
1940        inspector_id: Option<&InspectorElementId>,
1941        bounds: Bounds<Pixels>,
1942        _request_layout: &mut Self::RequestLayoutState,
1943        hitbox: &mut Option<Hitbox>,
1944        window: &mut Window,
1945        cx: &mut App,
1946    ) {
1947        let image_cache = self
1948            .image_cache
1949            .as_mut()
1950            .map(|provider| provider.provide(window, cx));
1951
1952        window.with_image_cache(image_cache, |window| {
1953            self.interactivity.paint(
1954                global_id,
1955                inspector_id,
1956                bounds,
1957                hitbox.as_ref(),
1958                window,
1959                cx,
1960                |style, window, cx| {
1961                    // skip children
1962                    if style.display == Display::None {
1963                        return;
1964                    }
1965
1966                    for child in &mut self.children {
1967                        child.paint(window, cx);
1968                    }
1969                },
1970            )
1971        });
1972    }
1973}
1974
1975impl IntoElement for Div {
1976    type Element = Self;
1977
1978    fn into_element(self) -> Self::Element {
1979        self
1980    }
1981}
1982
1983#[derive(Default)]
1984pub(crate) struct AriaProperties {
1985    pub(crate) label: Option<SharedString>,
1986    pub(crate) description: Option<SharedString>,
1987    pub(crate) keyshortcuts: Option<SharedString>,
1988    pub(crate) selected: Option<bool>,
1989    pub(crate) expanded: Option<bool>,
1990    pub(crate) toggled: Option<accesskit::Toggled>,
1991    pub(crate) numeric_value: Option<f64>,
1992    pub(crate) min_numeric_value: Option<f64>,
1993    pub(crate) max_numeric_value: Option<f64>,
1994    pub(crate) numeric_value_step: Option<f64>,
1995    pub(crate) value: Option<SharedString>,
1996    pub(crate) placeholder: Option<SharedString>,
1997    pub(crate) orientation: Option<accesskit::Orientation>,
1998    pub(crate) level: Option<usize>,
1999    pub(crate) position_in_set: Option<usize>,
2000    pub(crate) size_of_set: Option<usize>,
2001    pub(crate) row_index: Option<usize>,
2002    pub(crate) column_index: Option<usize>,
2003    pub(crate) row_count: Option<usize>,
2004    pub(crate) column_count: Option<usize>,
2005}
2006
2007/// The interactivity struct. Powers all of the general-purpose
2008/// interactivity in the `Div` element.
2009#[derive(Default)]
2010pub struct Interactivity {
2011    /// The element ID of the element. In id is required to support a stateful subset of the interactivity such as on_click.
2012    pub element_id: Option<ElementId>,
2013    /// Whether the element was clicked. This will only be present after layout.
2014    pub active: Option<bool>,
2015    /// Whether the element was hovered. This will only be present after paint if an hitbox
2016    /// was created for the interactive element.
2017    pub hovered: Option<bool>,
2018    pub(crate) tooltip_id: Option<TooltipId>,
2019    pub(crate) content_size: Size<Pixels>,
2020    pub(crate) key_context: Option<KeyContext>,
2021    pub(crate) focusable: bool,
2022    pub(crate) tracked_focus_handle: Option<FocusHandle>,
2023    pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2024    pub(crate) scroll_anchor: Option<ScrollAnchor>,
2025    pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2026    pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2027    pub(crate) group: Option<SharedString>,
2028    /// The base style of the element, before any modifications are applied
2029    /// by focus, active, etc.
2030    pub base_style: Box<StyleRefinement>,
2031    pub(crate) focus_style: Option<Box<StyleRefinement>>,
2032    pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2033    pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2034    pub(crate) hover_style: Option<Box<StyleRefinement>>,
2035    pub(crate) group_hover_style: Option<GroupStyle>,
2036    pub(crate) active_style: Option<Box<StyleRefinement>>,
2037    pub(crate) group_active_style: Option<GroupStyle>,
2038    pub(crate) drag_over_styles: Vec<(
2039        TypeId,
2040        Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2041    )>,
2042    pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
2043    pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
2044    pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
2045    pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
2046    pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
2047    pub(crate) mouse_exit_listeners: Vec<MouseExitListener>,
2048    pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
2049    pub(crate) pinch_listeners: Vec<PinchListener>,
2050    pub(crate) key_down_listeners: Vec<KeyDownListener>,
2051    pub(crate) key_up_listeners: Vec<KeyUpListener>,
2052    pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
2053    pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
2054    pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
2055    pub(crate) can_drop_predicate: Option<CanDropPredicate>,
2056    pub(crate) click_listeners: Vec<ClickListener>,
2057    pub(crate) aux_click_listeners: Vec<ClickListener>,
2058    pub(crate) drag_listener: Option<DragListener>,
2059    pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2060    pub(crate) tooltip_builder: Option<TooltipBuilder>,
2061    pub(crate) tooltip_show_delay: Option<Duration>,
2062    pub(crate) window_control: Option<WindowControlArea>,
2063    pub(crate) hitbox_behavior: HitboxBehavior,
2064    pub(crate) tab_index: Option<isize>,
2065    pub(crate) tab_group: bool,
2066    pub(crate) tab_stop: bool,
2067
2068    pub(crate) a11y_action_listeners:
2069        Vec<(accesskit::Action, crate::window::a11y::A11yActionListener)>,
2070    pub(crate) a11y_synthetic_children: Option<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2071    pub(crate) report_active_descendant_focus: bool,
2072    pub(crate) override_role: Option<accesskit::Role>,
2073    pub(crate) aria: AriaProperties,
2074
2075    #[cfg(any(feature = "inspector", debug_assertions))]
2076    pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2077
2078    #[cfg(any(test, feature = "test-support"))]
2079    pub(crate) debug_selector: Option<String>,
2080}
2081
2082impl Interactivity {
2083    /// Layout this element according to this interactivity state's configured styles
2084    pub fn request_layout(
2085        &mut self,
2086        global_id: Option<&GlobalElementId>,
2087        _inspector_id: Option<&InspectorElementId>,
2088        window: &mut Window,
2089        cx: &mut App,
2090        f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2091    ) -> LayoutId {
2092        #[cfg(any(feature = "inspector", debug_assertions))]
2093        window.with_inspector_state(
2094            _inspector_id,
2095            cx,
2096            |inspector_state: &mut Option<DivInspectorState>, _window| {
2097                if let Some(inspector_state) = inspector_state {
2098                    self.base_style = inspector_state.base_style.clone();
2099                } else {
2100                    *inspector_state = Some(DivInspectorState {
2101                        base_style: self.base_style.clone(),
2102                        bounds: Default::default(),
2103                        content_size: Default::default(),
2104                    })
2105                }
2106            },
2107        );
2108
2109        window.with_optional_element_state::<InteractiveElementState, _>(
2110            global_id,
2111            |element_state, window| {
2112                let mut element_state =
2113                    element_state.map(|element_state| element_state.unwrap_or_default());
2114
2115                if let Some(element_state) = element_state.as_ref()
2116                    && cx.has_active_drag()
2117                {
2118                    if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2119                        *pending_mouse_down.borrow_mut() = None;
2120                    }
2121                    if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2122                        *clicked_state.borrow_mut() = ElementClickedState::default();
2123                    }
2124                }
2125
2126                // Ensure we store a focus handle in our element state if we're focusable.
2127                // If there's an explicit focus handle we're tracking, use that. Otherwise
2128                // create a new handle and store it in the element state, which lives for as
2129                // as frames contain an element with this id.
2130                if self.focusable
2131                    && self.tracked_focus_handle.is_none()
2132                    && let Some(element_state) = element_state.as_mut()
2133                {
2134                    let mut handle = element_state
2135                        .focus_handle
2136                        .get_or_insert_with(|| cx.focus_handle())
2137                        .clone()
2138                        .tab_stop(self.tab_stop);
2139
2140                    if let Some(index) = self.tab_index {
2141                        handle = handle.tab_index(index);
2142                    }
2143
2144                    self.tracked_focus_handle = Some(handle);
2145                }
2146
2147                if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2148                    let scroll_handle_state = scroll_handle.0.borrow();
2149                    self.scroll_offset = Some(scroll_handle_state.offset.clone());
2150                    self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2151                } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2152                    || self.base_style.overflow.y == Some(Overflow::Scroll))
2153                    && let Some(element_state) = element_state.as_mut()
2154                {
2155                    self.scroll_offset = Some(
2156                        element_state
2157                            .scroll_offset
2158                            .get_or_insert_with(Rc::default)
2159                            .clone(),
2160                    );
2161                    self.ongoing_scroll = Some(
2162                        element_state
2163                            .ongoing_scroll
2164                            .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2165                            .clone(),
2166                    );
2167                }
2168
2169                let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2170                let layout_id = f(style, window, cx);
2171                (layout_id, element_state)
2172            },
2173        )
2174    }
2175
2176    /// Commit the bounds of this element according to this interactivity state's configured styles.
2177    pub fn prepaint<R>(
2178        &mut self,
2179        global_id: Option<&GlobalElementId>,
2180        _inspector_id: Option<&InspectorElementId>,
2181        bounds: Bounds<Pixels>,
2182        content_size: Size<Pixels>,
2183        window: &mut Window,
2184        cx: &mut App,
2185        f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2186    ) -> R {
2187        self.content_size = content_size;
2188
2189        #[cfg(any(feature = "inspector", debug_assertions))]
2190        window.with_inspector_state(
2191            _inspector_id,
2192            cx,
2193            |inspector_state: &mut Option<DivInspectorState>, _window| {
2194                if let Some(inspector_state) = inspector_state {
2195                    inspector_state.bounds = bounds;
2196                    inspector_state.content_size = content_size;
2197                }
2198            },
2199        );
2200
2201        if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2202            window.set_focus_handle(focus_handle, cx);
2203
2204            if window.a11y.is_active() {
2205                if let Some(global_id) = global_id {
2206                    let node_id = global_id.accesskit_node_id();
2207                    window.a11y.set_focusable(node_id, focus_handle.id);
2208                    if focus_handle.is_focused(window) {
2209                        window.a11y.set_focus(node_id);
2210                    }
2211                } else if focus_handle.is_focused(window) {
2212                    // Focusable, but with no element id it can't have an
2213                    // accessibility node, so screen readers fall back to the
2214                    // whole window.
2215                    window
2216                        .a11y
2217                        .note_focus_without_node(focus_handle.id, "it has no element id");
2218                }
2219            }
2220        }
2221
2222        if self.report_active_descendant_focus && window.a11y.is_active() {
2223            if let Some(global_id) = global_id {
2224                window
2225                    .a11y
2226                    .set_active_descendant(global_id.accesskit_node_id());
2227            }
2228        }
2229        window.with_optional_element_state::<InteractiveElementState, _>(
2230            global_id,
2231            |element_state, window| {
2232                let mut element_state =
2233                    element_state.map(|element_state| element_state.unwrap_or_default());
2234                let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2235
2236                if let Some(element_state) = element_state.as_mut() {
2237                    if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2238                        let clicked_state = clicked_state.borrow();
2239                        self.active = Some(clicked_state.element);
2240                    }
2241                    if self.hover_style.is_some() || self.group_hover_style.is_some() {
2242                        element_state
2243                            .hover_state
2244                            .get_or_insert_with(Default::default);
2245                    }
2246                    if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2247                        if self.tooltip_builder.is_some() {
2248                            self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2249                        } else {
2250                            // If there is no longer a tooltip builder, remove the active tooltip.
2251                            element_state.active_tooltip.take();
2252                        }
2253                    }
2254                }
2255
2256                window.with_text_style(style.text_style().cloned(), |window| {
2257                    window.with_content_mask(
2258                        style.overflow_mask(bounds, window.rem_size()),
2259                        |window| {
2260                            let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2261                                Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2262                            } else {
2263                                None
2264                            };
2265
2266                            let scroll_offset =
2267                                self.clamp_scroll_position(bounds, &style, window, cx);
2268                            let result = window.with_element_opacity(style.opacity, |window| {
2269                                f(&style, scroll_offset, hitbox, window, cx)
2270                            });
2271                            (result, element_state)
2272                        },
2273                    )
2274                })
2275            },
2276        )
2277    }
2278
2279    fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2280        self.hitbox_behavior != HitboxBehavior::Normal
2281            || self.window_control.is_some()
2282            || style.mouse_cursor.is_some()
2283            || self.group.is_some()
2284            || self.scroll_offset.is_some()
2285            || self.tracked_focus_handle.is_some()
2286            || self.hover_style.is_some()
2287            || self.group_hover_style.is_some()
2288            || self.hover_listener.is_some()
2289            || !self.mouse_up_listeners.is_empty()
2290            || !self.mouse_pressure_listeners.is_empty()
2291            || !self.mouse_down_listeners.is_empty()
2292            || !self.mouse_move_listeners.is_empty()
2293            || !self.mouse_exit_listeners.is_empty()
2294            || !self.click_listeners.is_empty()
2295            || !self.aux_click_listeners.is_empty()
2296            || !self.scroll_wheel_listeners.is_empty()
2297            || self.has_pinch_listeners()
2298            || self.drag_listener.is_some()
2299            || !self.drop_listeners.is_empty()
2300            || !self.drag_over_styles.is_empty()
2301            || self.tooltip_builder.is_some()
2302            || window.is_inspector_picking(cx)
2303    }
2304
2305    fn clamp_scroll_position(
2306        &self,
2307        bounds: Bounds<Pixels>,
2308        style: &Style,
2309        window: &mut Window,
2310        _cx: &mut App,
2311    ) -> Point<Pixels> {
2312        fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2313            const ROUNDING_FACTOR: f32 = 100.0;
2314            (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2315        }
2316
2317        if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2318            let mut scroll_to_bottom = false;
2319            let mut tracked_scroll_handle = self
2320                .tracked_scroll_handle
2321                .as_ref()
2322                .map(|handle| handle.0.borrow_mut());
2323            if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2324                scroll_handle_state.overflow = style.overflow;
2325                scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2326            }
2327
2328            let rem_size = window.rem_size();
2329            // Taffy lays the box out with the padding snapped to the device pixel
2330            // grid (`to_taffy`); recomputed unsnapped, e.g. py_1 at a fractional
2331            // rem size, it exceeds `bounds` and leaves the box scrollable by the
2332            // sub-pixel difference.
2333            let padding = style
2334                .padding
2335                .to_pixels(bounds.size.into(), rem_size)
2336                .map(|edge| window.pixel_snap(*edge));
2337            let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2338            // The floating point values produced by Taffy and ours often vary
2339            // slightly after ~5 decimal places. This can lead to cases where after
2340            // subtracting these, the container becomes scrollable for less than
2341            // 0.00000x pixels. As we generally don't benefit from a precision that
2342            // high for the maximum scroll, we round the scroll max to 2 decimal
2343            // places here.
2344            let padded_content_size = self.content_size + padding_size;
2345            let scroll_max = Point::from(padded_content_size - bounds.size)
2346                .map(round_to_two_decimals)
2347                .max(&Default::default());
2348            // Clamp scroll offset in case scroll max is smaller now (e.g., if children
2349            // were removed or the bounds became larger).
2350            let mut scroll_offset = scroll_offset.borrow_mut();
2351
2352            scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2353            if scroll_to_bottom {
2354                scroll_offset.y = -scroll_max.y;
2355            } else {
2356                scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2357            }
2358
2359            if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2360                scroll_handle_state.max_offset = scroll_max;
2361                scroll_handle_state.bounds = bounds;
2362            }
2363
2364            *scroll_offset
2365        } else {
2366            Point::default()
2367        }
2368    }
2369
2370    /// Paint this element according to this interactivity state's configured styles
2371    /// and bind the element's mouse and keyboard events.
2372    ///
2373    /// content_size is the size of the content of the element, which may be larger than the
2374    /// element's bounds if the element is scrollable.
2375    ///
2376    /// the final computed style will be passed to the provided function, along
2377    /// with the current scroll offset
2378    pub fn paint(
2379        &mut self,
2380        global_id: Option<&GlobalElementId>,
2381        _inspector_id: Option<&InspectorElementId>,
2382        bounds: Bounds<Pixels>,
2383        hitbox: Option<&Hitbox>,
2384        window: &mut Window,
2385        cx: &mut App,
2386        f: impl FnOnce(&Style, &mut Window, &mut App),
2387    ) {
2388        self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2389        window.with_optional_element_state::<InteractiveElementState, _>(
2390            global_id,
2391            |element_state, window| {
2392                let mut element_state =
2393                    element_state.map(|element_state| element_state.unwrap_or_default());
2394
2395                let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2396
2397                #[cfg(any(feature = "test-support", test))]
2398                if let Some(debug_selector) = &self.debug_selector {
2399                    window
2400                        .next_frame
2401                        .record_debug_bounds(debug_selector.clone(), bounds);
2402                }
2403
2404                self.paint_hover_group_handler(window, cx);
2405
2406                if style.visibility == Visibility::Hidden {
2407                    return ((), element_state);
2408                }
2409
2410                let mut tab_group = None;
2411                if self.tab_group {
2412                    tab_group = self.tab_index;
2413                }
2414
2415                window.with_element_opacity(style.opacity, |window| {
2416                    style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2417                        window.with_text_style(style.text_style().cloned(), |window| {
2418                            window.with_content_mask(
2419                                style.overflow_mask(bounds, window.rem_size()),
2420                                |window| {
2421                                    window.with_tab_group(tab_group, |window| {
2422                                        // Register the container's own focus handle *inside* its
2423                                        // tab group, so that focusing the container and then
2424                                        // calling `focus_next` descends into this group's first
2425                                        // item. Inserting it before `with_tab_group` would give the
2426                                        // container a shallower tab path than its children; with
2427                                        // sibling groups every container would then sort ahead of
2428                                        // every item, and `focus_next` from a container would jump
2429                                        // to the first item in the whole window instead of its own.
2430                                        if let Some(focus_handle) = &self.tracked_focus_handle {
2431                                            window.next_frame.tab_stops.insert(focus_handle);
2432                                        }
2433                                        if let Some(hitbox) = hitbox {
2434                                            #[cfg(debug_assertions)]
2435                                            self.paint_debug_info(
2436                                                global_id, hitbox, &style, window, cx,
2437                                            );
2438
2439                                            if let Some(drag) = cx.active_drag.as_ref() {
2440                                                if let Some(mouse_cursor) = drag.cursor_style {
2441                                                    window.set_window_cursor_style(mouse_cursor);
2442                                                }
2443                                            } else {
2444                                                if let Some(mouse_cursor) = style.mouse_cursor {
2445                                                    window.set_cursor_style(mouse_cursor, hitbox);
2446                                                }
2447                                            }
2448
2449                                            if let Some(group) = self.group.clone() {
2450                                                GroupHitboxes::push(group, hitbox.id, cx);
2451                                            }
2452
2453                                            if let Some(area) = self.window_control {
2454                                                window.insert_window_control_hitbox(
2455                                                    area,
2456                                                    hitbox.clone(),
2457                                                );
2458                                            }
2459
2460                                            self.paint_mouse_listeners(
2461                                                hitbox,
2462                                                element_state.as_mut(),
2463                                                window,
2464                                                cx,
2465                                            );
2466                                            self.paint_scroll_listener(hitbox, &style, window, cx);
2467                                        }
2468
2469                                        self.paint_keyboard_listeners(window, cx);
2470
2471                                        if window.a11y.is_active() {
2472                                            if let Some(global_id) = global_id {
2473                                                if !self.a11y_action_listeners.is_empty() {
2474                                                    let node_id = global_id.accesskit_node_id();
2475                                                    for (action, listener) in
2476                                                        self.a11y_action_listeners.drain(..)
2477                                                    {
2478                                                        window.on_a11y_action(
2479                                                            node_id, action, listener,
2480                                                        );
2481                                                    }
2482                                                }
2483                                            }
2484                                        }
2485
2486                                        f(&style, window, cx);
2487
2488                                        if let Some(_hitbox) = hitbox {
2489                                            #[cfg(any(feature = "inspector", debug_assertions))]
2490                                            window.insert_inspector_hitbox(
2491                                                _hitbox.id,
2492                                                _inspector_id,
2493                                                cx,
2494                                            );
2495
2496                                            if let Some(group) = self.group.as_ref() {
2497                                                GroupHitboxes::pop(group, cx);
2498                                            }
2499                                        }
2500                                    })
2501                                },
2502                            );
2503                        });
2504                    });
2505                });
2506
2507                ((), element_state)
2508            },
2509        );
2510    }
2511
2512    #[cfg(debug_assertions)]
2513    fn paint_debug_info(
2514        &self,
2515        global_id: Option<&GlobalElementId>,
2516        hitbox: &Hitbox,
2517        style: &Style,
2518        window: &mut Window,
2519        cx: &mut App,
2520    ) {
2521        use crate::{BorderStyle, TextAlign};
2522
2523        if let Some(global_id) = global_id
2524            && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2525            && hitbox.is_hovered(window)
2526        {
2527            const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2528            let element_id = format!("{global_id:?}");
2529            let str_len = element_id.len();
2530
2531            let render_debug_text = |window: &mut Window| {
2532                if let Some(text) = window
2533                    .text_system()
2534                    .shape_text(
2535                        element_id.into(),
2536                        FONT_SIZE,
2537                        &[window.text_style().to_run(str_len)],
2538                        None,
2539                        None,
2540                    )
2541                    .ok()
2542                    .and_then(|mut text| text.pop())
2543                {
2544                    text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2545                        .ok();
2546
2547                    let text_bounds = crate::Bounds {
2548                        origin: hitbox.origin,
2549                        size: text.size(FONT_SIZE),
2550                    };
2551                    if let Some(source_location) = self.source_location
2552                        && text_bounds.contains(&window.mouse_position())
2553                        && window.modifiers().secondary()
2554                    {
2555                        let secondary_held = window.modifiers().secondary();
2556                        window.on_key_event({
2557                            move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2558                                if e.modifiers.secondary() != secondary_held
2559                                    && text_bounds.contains(&window.mouse_position())
2560                                {
2561                                    window.refresh();
2562                                }
2563                            }
2564                        });
2565
2566                        let was_hovered = hitbox.is_hovered(window);
2567                        let current_view = window.current_view();
2568                        window.on_mouse_event({
2569                            let hitbox = hitbox.clone();
2570                            move |_: &MouseMoveEvent, phase, window, cx| {
2571                                if phase == DispatchPhase::Capture {
2572                                    let hovered = hitbox.is_hovered(window);
2573                                    if hovered != was_hovered {
2574                                        cx.notify(current_view)
2575                                    }
2576                                }
2577                            }
2578                        });
2579
2580                        window.on_mouse_event({
2581                            let hitbox = hitbox.clone();
2582                            move |e: &crate::MouseDownEvent, phase, window, cx| {
2583                                if text_bounds.contains(&e.position)
2584                                    && phase.capture()
2585                                    && hitbox.is_hovered(window)
2586                                {
2587                                    cx.stop_propagation();
2588                                    let Ok(dir) = std::env::current_dir() else {
2589                                        return;
2590                                    };
2591
2592                                    eprintln!(
2593                                        "This element was created at:\n{}:{}:{}",
2594                                        dir.join(source_location.file()).to_string_lossy(),
2595                                        source_location.line(),
2596                                        source_location.column()
2597                                    );
2598                                }
2599                            }
2600                        });
2601                        window.paint_quad(crate::outline(
2602                            crate::Bounds {
2603                                origin: hitbox.origin
2604                                    + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2605                                size: crate::Size {
2606                                    width: text_bounds.size.width,
2607                                    height: crate::px(1.),
2608                                },
2609                            },
2610                            crate::red(),
2611                            BorderStyle::default(),
2612                        ))
2613                    }
2614                }
2615            };
2616
2617            window.with_text_style(
2618                Some(crate::TextStyleRefinement {
2619                    color: Some(crate::red()),
2620                    line_height: Some(FONT_SIZE.into()),
2621                    background_color: Some(crate::white()),
2622                    ..Default::default()
2623                }),
2624                render_debug_text,
2625            )
2626        }
2627    }
2628
2629    fn paint_mouse_listeners(
2630        &mut self,
2631        hitbox: &Hitbox,
2632        element_state: Option<&mut InteractiveElementState>,
2633        window: &mut Window,
2634        cx: &mut App,
2635    ) {
2636        let is_focused = self
2637            .tracked_focus_handle
2638            .as_ref()
2639            .map(|handle| handle.is_focused(window))
2640            .unwrap_or(false);
2641
2642        // If this element can be focused, register a mouse down listener
2643        // that will automatically transfer focus when hitting the element.
2644        // This behavior can be suppressed by using `cx.prevent_default()`.
2645        if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2646            let hitbox = hitbox.clone();
2647            window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2648                if phase == DispatchPhase::Bubble
2649                    && hitbox.is_hovered(window)
2650                    && !window.default_prevented()
2651                {
2652                    window.focus(&focus_handle, cx);
2653                    // If there is a parent that is also focusable, prevent it
2654                    // from transferring focus because we already did so.
2655                    window.prevent_default();
2656                }
2657            });
2658        }
2659
2660        for listener in self.mouse_down_listeners.drain(..) {
2661            let hitbox = hitbox.clone();
2662            window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2663                listener(event, phase, &hitbox, window, cx);
2664            })
2665        }
2666
2667        for listener in self.mouse_up_listeners.drain(..) {
2668            let hitbox = hitbox.clone();
2669            window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2670                listener(event, phase, &hitbox, window, cx);
2671            })
2672        }
2673
2674        for listener in self.mouse_pressure_listeners.drain(..) {
2675            let hitbox = hitbox.clone();
2676            window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2677                listener(event, phase, &hitbox, window, cx);
2678            })
2679        }
2680
2681        for listener in self.mouse_move_listeners.drain(..) {
2682            let hitbox = hitbox.clone();
2683            window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2684                listener(event, phase, &hitbox, window, cx);
2685            })
2686        }
2687
2688        for listener in self.mouse_exit_listeners.drain(..) {
2689            let hitbox = hitbox.clone();
2690            window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2691                listener(event, phase, &hitbox, window, cx);
2692            })
2693        }
2694
2695        for listener in self.scroll_wheel_listeners.drain(..) {
2696            let hitbox = hitbox.clone();
2697            window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2698                listener(event, phase, &hitbox, window, cx);
2699            })
2700        }
2701
2702        for listener in self.pinch_listeners.drain(..) {
2703            let hitbox = hitbox.clone();
2704            window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2705                listener(event, phase, &hitbox, window, cx);
2706            })
2707        }
2708
2709        if self.hover_style.is_some()
2710            || self.base_style.mouse_cursor.is_some()
2711            || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2712        {
2713            let hitbox = hitbox.clone();
2714            let hover_state = self.hover_style.as_ref().and_then(|_| {
2715                element_state
2716                    .as_ref()
2717                    .and_then(|state| state.hover_state.as_ref())
2718                    .cloned()
2719            });
2720            let current_view = window.current_view();
2721
2722            window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2723                let hovered = hitbox.is_hovered(window);
2724                let was_hovered = hover_state
2725                    .as_ref()
2726                    .is_some_and(|state| state.borrow().element);
2727                if phase == DispatchPhase::Capture && hovered != was_hovered {
2728                    if let Some(hover_state) = &hover_state {
2729                        hover_state.borrow_mut().element = hovered;
2730                        cx.notify(current_view);
2731                    }
2732                }
2733            });
2734        }
2735
2736        if let Some(group_hover) = self.group_hover_style.as_ref() {
2737            if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2738                let hover_state = element_state
2739                    .as_ref()
2740                    .and_then(|element| element.hover_state.as_ref())
2741                    .cloned();
2742                let current_view = window.current_view();
2743
2744                window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2745                    let group_hovered = group_hitbox_id.is_hovered(window);
2746                    let was_group_hovered = hover_state
2747                        .as_ref()
2748                        .is_some_and(|state| state.borrow().group);
2749                    if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2750                        if let Some(hover_state) = &hover_state {
2751                            hover_state.borrow_mut().group = group_hovered;
2752                            cx.notify(current_view);
2753                        }
2754                    }
2755                });
2756            }
2757        }
2758
2759        let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2760
2761        let mut drag_listener = mem::take(&mut self.drag_listener);
2762        let drop_listeners = mem::take(&mut self.drop_listeners);
2763        let click_listeners = mem::take(&mut self.click_listeners);
2764        let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2765        let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2766
2767        if !drop_listeners.is_empty() {
2768            let hitbox = hitbox.clone();
2769            window.on_mouse_event({
2770                move |_: &MouseUpEvent, phase, window, cx| {
2771                    if let Some(drag) = &cx.active_drag
2772                        && phase == DispatchPhase::Bubble
2773                        && hitbox.is_hovered(window)
2774                    {
2775                        let drag_state_type = drag.value.as_ref().type_id();
2776                        for (drop_state_type, listener) in &drop_listeners {
2777                            if *drop_state_type == drag_state_type {
2778                                let drag = cx
2779                                    .active_drag
2780                                    .take()
2781                                    .expect("checked for type drag state type above");
2782
2783                                let mut can_drop = true;
2784                                if let Some(predicate) = &can_drop_predicate {
2785                                    can_drop = predicate(drag.value.as_ref(), window, cx);
2786                                }
2787
2788                                if can_drop {
2789                                    listener(drag.value.as_ref(), window, cx);
2790                                    window.refresh();
2791                                    cx.stop_propagation();
2792                                }
2793                            }
2794                        }
2795                    }
2796                }
2797            });
2798        }
2799
2800        if let Some(element_state) = element_state {
2801            if !click_listeners.is_empty()
2802                || !aux_click_listeners.is_empty()
2803                || drag_listener.is_some()
2804            {
2805                let pending_mouse_down = element_state
2806                    .pending_mouse_down
2807                    .get_or_insert_with(Default::default)
2808                    .clone();
2809
2810                let pending_keyboard_down = element_state
2811                    .pending_keyboard_down
2812                    .get_or_insert_with(Default::default)
2813                    .clone();
2814
2815                let clicked_state = element_state
2816                    .clicked_state
2817                    .get_or_insert_with(Default::default)
2818                    .clone();
2819
2820                window.on_mouse_event({
2821                    let pending_mouse_down = pending_mouse_down.clone();
2822                    let hitbox = hitbox.clone();
2823                    let has_aux_click_listeners = !aux_click_listeners.is_empty();
2824                    move |event: &MouseDownEvent, phase, window, _cx| {
2825                        if phase == DispatchPhase::Bubble
2826                            && (event.button == MouseButton::Left || has_aux_click_listeners)
2827                            && hitbox.is_hovered(window)
2828                        {
2829                            *pending_mouse_down.borrow_mut() = Some(event.clone());
2830                            window.refresh();
2831                        }
2832                    }
2833                });
2834
2835                window.on_mouse_event({
2836                    let pending_mouse_down = pending_mouse_down.clone();
2837                    let hitbox = hitbox.clone();
2838                    move |event: &MouseMoveEvent, phase, window, cx| {
2839                        if phase == DispatchPhase::Capture {
2840                            return;
2841                        }
2842
2843                        let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2844                        if let Some(mouse_down) = pending_mouse_down.clone()
2845                            && !cx.has_active_drag()
2846                            && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2847                            && let Some(listener) = drag_listener.take()
2848                            && mouse_down.button == MouseButton::Left
2849                        {
2850                            *clicked_state.borrow_mut() = ElementClickedState::default();
2851                            let cursor_offset = event.position - hitbox.origin;
2852                            let drag = (listener.render)(
2853                                listener.value.as_ref(),
2854                                cursor_offset,
2855                                window,
2856                                cx,
2857                            );
2858                            let external_payload_source =
2859                                listener.external_payload.map(|external_payload| {
2860                                    let value = listener.value.clone();
2861                                    Box::new(move |window: &mut Window, cx: &mut App| {
2862                                        external_payload(value.as_ref(), window, cx)
2863                                    })
2864                                        as ExternalDragPayloadSource
2865                                });
2866                            cx.active_drag = Some(AnyDrag {
2867                                view: drag,
2868                                value: listener.value,
2869                                cursor_offset,
2870                                cursor_style: drag_cursor_style,
2871                                external_payload_source,
2872                            });
2873                            pending_mouse_down.take();
2874                            window.refresh();
2875                            cx.stop_propagation();
2876                        }
2877                    }
2878                });
2879
2880                if is_focused {
2881                    // Record the focus generation at which an enter/space key
2882                    // down event happened on this element. The next key up
2883                    // event will be mapped to a click event if both of the
2884                    // following are true:
2885                    // - no other key events happen in between
2886                    // - the focus generation is the same (implying focus did not move)
2887                    //
2888                    // This design avoids an ABA problem that happens if you
2889                    // store the focus handle that registered the keypress.
2890                    window.on_key_event({
2891                        let pending_keyboard_down = pending_keyboard_down.clone();
2892                        move |event: &KeyDownEvent, phase, window, _cx| {
2893                            if phase.bubble() && !window.default_prevented() {
2894                                let stroke = &event.keystroke;
2895                                let is_activation_key = (stroke.key.eq("enter")
2896                                    || stroke.key.eq("space"))
2897                                    && !stroke.modifiers.modified();
2898                                *pending_keyboard_down.borrow_mut() =
2899                                    is_activation_key.then_some(window.focus_generation);
2900                            }
2901                        }
2902                    });
2903
2904                    // Press enter, space to trigger click, when the element is focused.
2905                    window.on_key_event({
2906                        let click_listeners = click_listeners.clone();
2907                        let hitbox = hitbox.clone();
2908                        move |event: &KeyUpEvent, phase, window, cx| {
2909                            if phase.bubble() && !window.default_prevented() {
2910                                let stroke = &event.keystroke;
2911                                let keyboard_button = if stroke.key.eq("enter") {
2912                                    Some(KeyboardButton::Enter)
2913                                } else if stroke.key.eq("space") {
2914                                    Some(KeyboardButton::Space)
2915                                } else {
2916                                    None
2917                                };
2918
2919                                if let Some(button) = keyboard_button
2920                                    && !stroke.modifiers.modified()
2921                                {
2922                                    let pending =
2923                                        std::mem::take(&mut *pending_keyboard_down.borrow_mut());
2924                                    if pending != Some(window.focus_generation) {
2925                                        return;
2926                                    }
2927
2928                                    let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2929                                        button,
2930                                        bounds: hitbox.bounds,
2931                                    });
2932
2933                                    for listener in &click_listeners {
2934                                        listener(&click_event, window, cx);
2935                                    }
2936                                } else {
2937                                    // Releasing any other key mid-press means
2938                                    // this isn't a clean activation, so cancel
2939                                    // the pending keydown.
2940                                    *pending_keyboard_down.borrow_mut() = None;
2941                                }
2942                            }
2943                        }
2944                    });
2945                }
2946
2947                window.on_mouse_event({
2948                    let mut captured_mouse_down = None;
2949                    let hitbox = hitbox.clone();
2950                    move |event: &MouseUpEvent, phase, window, cx| match phase {
2951                        // Clear the pending mouse down during the capture phase,
2952                        // so that it happens even if another event handler stops
2953                        // propagation.
2954                        DispatchPhase::Capture => {
2955                            let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2956                            if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2957                                captured_mouse_down = pending_mouse_down.take();
2958                                window.refresh();
2959                            } else if pending_mouse_down.is_some() {
2960                                // Clear the pending mouse down event (without firing click handlers)
2961                                // if the hitbox is not being hovered.
2962                                // This avoids dragging elements that changed their position
2963                                // immediately after being clicked.
2964                                // See https://github.com/zed-industries/zed/issues/24600 for more details
2965                                pending_mouse_down.take();
2966                                window.refresh();
2967                            }
2968                        }
2969                        // Fire click handlers during the bubble phase.
2970                        DispatchPhase::Bubble => {
2971                            if let Some(mouse_down) = captured_mouse_down.take() {
2972                                let btn = mouse_down.button;
2973
2974                                let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2975                                    down: mouse_down,
2976                                    up: event.clone(),
2977                                });
2978
2979                                match btn {
2980                                    MouseButton::Left => {
2981                                        for listener in &click_listeners {
2982                                            listener(&mouse_click, window, cx);
2983                                        }
2984                                    }
2985                                    _ => {
2986                                        for listener in &aux_click_listeners {
2987                                            listener(&mouse_click, window, cx);
2988                                        }
2989                                    }
2990                                }
2991                            }
2992                        }
2993                    }
2994                });
2995            }
2996
2997            if let Some(hover_listener) = self.hover_listener.take() {
2998                let was_hovered = element_state
2999                    .hover_listener_state
3000                    .get_or_insert_with(Default::default)
3001                    .clone();
3002                let has_mouse_down = element_state
3003                    .pending_mouse_down
3004                    .get_or_insert_with(Default::default)
3005                    .clone();
3006                let hover_listener = Rc::new(hover_listener);
3007                let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3008                    let mut was_hovered = was_hovered.borrow_mut();
3009                    if is_hovered != *was_hovered {
3010                        *was_hovered = is_hovered;
3011                        drop(was_hovered);
3012                        hover_listener(&is_hovered, window, cx);
3013                    }
3014                };
3015
3016                window.on_mouse_event({
3017                    let update_hover = update_hover.clone();
3018                    let hitbox = hitbox.clone();
3019                    move |_: &MouseMoveEvent, phase, window, cx| {
3020                        if phase == DispatchPhase::Bubble {
3021                            let is_hovered = has_mouse_down.borrow().is_none()
3022                                && !cx.has_active_drag()
3023                                && hitbox.is_hovered(window);
3024                            update_hover(is_hovered, window, cx);
3025                        }
3026                    }
3027                });
3028
3029                // The pointer can leave the window without a final MouseMove, so also
3030                // clear hover on MouseExited.
3031                window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3032                    if phase == DispatchPhase::Bubble {
3033                        update_hover(false, window, cx);
3034                    }
3035                });
3036            }
3037
3038            if let Some(tooltip_builder) = self.tooltip_builder.take() {
3039                let active_tooltip = element_state
3040                    .active_tooltip
3041                    .get_or_insert_with(Default::default)
3042                    .clone();
3043                let pending_mouse_down = element_state
3044                    .pending_mouse_down
3045                    .get_or_insert_with(Default::default)
3046                    .clone();
3047
3048                let tooltip_is_hoverable = tooltip_builder.hoverable;
3049                let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3050                    Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3051                });
3052                // Use bounds instead of testing hitbox since this is called during prepaint.
3053                let check_is_hovered_during_prepaint = Rc::new({
3054                    let pending_mouse_down = pending_mouse_down.clone();
3055                    let source_bounds = hitbox.bounds;
3056                    move |window: &Window| {
3057                        !window.last_input_was_keyboard()
3058                            && pending_mouse_down.borrow().is_none()
3059                            && source_bounds.contains(&window.mouse_position())
3060                    }
3061                });
3062                let check_is_hovered = Rc::new({
3063                    let hitbox = hitbox.clone();
3064                    move |window: &Window| {
3065                        pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3066                    }
3067                });
3068                register_tooltip_mouse_handlers(
3069                    &active_tooltip,
3070                    self.tooltip_id,
3071                    build_tooltip,
3072                    check_is_hovered,
3073                    check_is_hovered_during_prepaint,
3074                    self.tooltip_show_delay,
3075                    window,
3076                );
3077            }
3078
3079            // We unconditionally bind both the mouse up and mouse down active state handlers
3080            // Because we might not get a chance to render a frame before the mouse up event arrives.
3081            let active_state = element_state
3082                .clicked_state
3083                .get_or_insert_with(Default::default)
3084                .clone();
3085
3086            {
3087                let active_state = active_state.clone();
3088                window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3089                    if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3090                        *active_state.borrow_mut() = ElementClickedState::default();
3091                        window.refresh();
3092                    }
3093                });
3094            }
3095
3096            {
3097                let active_group_hitbox = self
3098                    .group_active_style
3099                    .as_ref()
3100                    .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3101                let hitbox = hitbox.clone();
3102                window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3103                    if phase == DispatchPhase::Bubble && !window.default_prevented() {
3104                        let group_hovered = active_group_hitbox
3105                            .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3106                        let element_hovered = hitbox.is_hovered(window);
3107                        if group_hovered || element_hovered {
3108                            *active_state.borrow_mut() = ElementClickedState {
3109                                group: group_hovered,
3110                                element: element_hovered,
3111                            };
3112                            window.refresh();
3113                        }
3114                    }
3115                });
3116            }
3117        }
3118    }
3119
3120    fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3121        let key_down_listeners = mem::take(&mut self.key_down_listeners);
3122        let key_up_listeners = mem::take(&mut self.key_up_listeners);
3123        let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3124        let action_listeners = mem::take(&mut self.action_listeners);
3125        if let Some(context) = self.key_context.clone() {
3126            window.set_key_context(context);
3127        }
3128
3129        for listener in key_down_listeners {
3130            window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3131                listener(event, phase, window, cx);
3132            })
3133        }
3134
3135        for listener in key_up_listeners {
3136            window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3137                listener(event, phase, window, cx);
3138            })
3139        }
3140
3141        for listener in modifiers_changed_listeners {
3142            window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3143                listener(event, window, cx);
3144            })
3145        }
3146
3147        for (action_type, listener) in action_listeners {
3148            window.on_action(action_type, listener)
3149        }
3150    }
3151
3152    fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3153        let group_hitbox = self
3154            .group_hover_style
3155            .as_ref()
3156            .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3157
3158        if let Some(group_hitbox) = group_hitbox {
3159            let was_hovered = group_hitbox.is_hovered(window);
3160            let current_view = window.current_view();
3161            window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3162                let hovered = group_hitbox.is_hovered(window);
3163                if phase == DispatchPhase::Capture && hovered != was_hovered {
3164                    cx.notify(current_view);
3165                }
3166            });
3167        }
3168    }
3169
3170    fn paint_scroll_listener(
3171        &self,
3172        hitbox: &Hitbox,
3173        style: &Style,
3174        window: &mut Window,
3175        _cx: &mut App,
3176    ) {
3177        if let Some(scroll_offset) = self.scroll_offset.clone() {
3178            let ongoing_scroll = self.ongoing_scroll.clone();
3179            let overflow = style.overflow;
3180            let allow_concurrent_scroll = style.allow_concurrent_scroll;
3181            let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3182            let line_height = window.line_height();
3183            let hitbox = hitbox.clone();
3184            let current_view = window.current_view();
3185            window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
3186                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3187                    let mut scroll_offset = scroll_offset.borrow_mut();
3188                    let old_scroll_offset = *scroll_offset;
3189                    let mut delta = event.delta.pixel_delta(line_height);
3190
3191                    if restrict_scroll_to_axis
3192                        && event.delta.precise()
3193                        && let Some(ongoing_scroll) = &ongoing_scroll
3194                    {
3195                        ongoing_scroll
3196                            .borrow_mut()
3197                            .filter(&mut delta, event.touch_phase);
3198                    }
3199
3200                    let mut delta_x = match overflow.x {
3201                        Overflow::Scroll if !delta.x.is_zero() => delta.x,
3202                        Overflow::Scroll
3203                            if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3204                        {
3205                            delta.y
3206                        }
3207                        _ => Pixels::ZERO,
3208                    };
3209                    let mut delta_y = match overflow.y {
3210                        Overflow::Scroll if !delta.y.is_zero() => delta.y,
3211                        Overflow::Scroll
3212                            if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3213                        {
3214                            delta.x
3215                        }
3216                        _ => Pixels::ZERO,
3217                    };
3218                    if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3219                        if delta_x.abs() > delta_y.abs() {
3220                            delta_y = Pixels::ZERO;
3221                        } else {
3222                            delta_x = Pixels::ZERO;
3223                        }
3224                    }
3225                    scroll_offset.y += delta_y;
3226                    scroll_offset.x += delta_x;
3227                    if *scroll_offset != old_scroll_offset {
3228                        cx.notify(current_view);
3229                    }
3230                }
3231            });
3232        }
3233    }
3234
3235    /// Compute the visual style for this element, based on the current bounds and the element's state.
3236    pub fn compute_style(
3237        &self,
3238        global_id: Option<&GlobalElementId>,
3239        hitbox: Option<&Hitbox>,
3240        window: &mut Window,
3241        cx: &mut App,
3242    ) -> Style {
3243        window.with_optional_element_state(global_id, |element_state, window| {
3244            let mut element_state =
3245                element_state.map(|element_state| element_state.unwrap_or_default());
3246            let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3247            (style, element_state)
3248        })
3249    }
3250
3251    /// Called from internal methods that have already called with_element_state.
3252    fn compute_style_internal(
3253        &self,
3254        hitbox: Option<&Hitbox>,
3255        element_state: Option<&mut InteractiveElementState>,
3256        window: &mut Window,
3257        cx: &mut App,
3258    ) -> Style {
3259        let mut style = Style::default();
3260        style.refine(&self.base_style);
3261
3262        if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3263            if let Some(in_focus_style) = self.in_focus_style.as_ref()
3264                && focus_handle.within_focused(window, cx)
3265            {
3266                style.refine(in_focus_style);
3267            }
3268
3269            if let Some(focus_style) = self.focus_style.as_ref()
3270                && focus_handle.is_focused(window)
3271            {
3272                style.refine(focus_style);
3273            }
3274
3275            if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3276                && focus_handle.is_focused(window)
3277                && window.last_input_was_keyboard()
3278            {
3279                style.refine(focus_visible_style);
3280            }
3281        }
3282
3283        if !cx.has_active_drag() {
3284            if let Some(group_hover) = self.group_hover_style.as_ref() {
3285                let is_group_hovered =
3286                    if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3287                        group_hitbox_id.is_hovered(window)
3288                    } else if let Some(element_state) = element_state.as_ref() {
3289                        element_state
3290                            .hover_state
3291                            .as_ref()
3292                            .map(|state| state.borrow().group)
3293                            .unwrap_or(false)
3294                    } else {
3295                        false
3296                    };
3297
3298                if is_group_hovered {
3299                    style.refine(&group_hover.style);
3300                }
3301            }
3302
3303            if let Some(hover_style) = self.hover_style.as_ref() {
3304                let is_hovered = if let Some(hitbox) = hitbox {
3305                    hitbox.is_hovered(window)
3306                } else if let Some(element_state) = element_state.as_ref() {
3307                    element_state
3308                        .hover_state
3309                        .as_ref()
3310                        .map(|state| state.borrow().element)
3311                        .unwrap_or(false)
3312                } else {
3313                    false
3314                };
3315
3316                if is_hovered {
3317                    style.refine(hover_style);
3318                }
3319            }
3320        }
3321
3322        if let Some(hitbox) = hitbox {
3323            if let Some(drag) = cx.active_drag.take() {
3324                let mut can_drop = true;
3325                if let Some(can_drop_predicate) = &self.can_drop_predicate {
3326                    can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3327                }
3328
3329                if can_drop {
3330                    for (state_type, group_drag_style) in &self.group_drag_over_styles {
3331                        if let Some(group_hitbox_id) =
3332                            GroupHitboxes::get(&group_drag_style.group, cx)
3333                            && *state_type == drag.value.as_ref().type_id()
3334                            && group_hitbox_id.is_hovered(window)
3335                        {
3336                            style.refine(&group_drag_style.style);
3337                        }
3338                    }
3339
3340                    for (state_type, build_drag_over_style) in &self.drag_over_styles {
3341                        if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3342                        {
3343                            style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3344                        }
3345                    }
3346                }
3347
3348                style.mouse_cursor = drag.cursor_style;
3349                cx.active_drag = Some(drag);
3350            }
3351        }
3352
3353        if let Some(element_state) = element_state {
3354            let clicked_state = element_state
3355                .clicked_state
3356                .get_or_insert_with(Default::default)
3357                .borrow();
3358            if clicked_state.group
3359                && let Some(group) = self.group_active_style.as_ref()
3360            {
3361                style.refine(&group.style)
3362            }
3363
3364            if let Some(active_style) = self.active_style.as_ref()
3365                && clicked_state.element
3366            {
3367                style.refine(active_style)
3368            }
3369        }
3370
3371        style
3372    }
3373
3374    pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3375        if let Some(label) = &self.aria.label {
3376            node.set_label(label.to_string());
3377        }
3378        if let Some(description) = &self.aria.description {
3379            node.set_description(description.to_string());
3380        }
3381        if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3382            node.set_keyboard_shortcut(keyshortcuts.to_string());
3383        }
3384        if let Some(selected) = self.aria.selected {
3385            node.set_selected(selected);
3386        }
3387        if let Some(expanded) = self.aria.expanded {
3388            node.set_expanded(expanded);
3389        }
3390        if let Some(toggled) = self.aria.toggled {
3391            node.set_toggled(toggled);
3392        }
3393        if let Some(value) = self.aria.numeric_value {
3394            node.set_numeric_value(value);
3395        }
3396        if let Some(value) = self.aria.min_numeric_value {
3397            node.set_min_numeric_value(value);
3398        }
3399        if let Some(value) = self.aria.max_numeric_value {
3400            node.set_max_numeric_value(value);
3401        }
3402        if let Some(step) = self.aria.numeric_value_step {
3403            node.set_numeric_value_step(step);
3404        }
3405        if let Some(value) = &self.aria.value {
3406            node.set_value(value.to_string());
3407        }
3408        if let Some(placeholder) = &self.aria.placeholder {
3409            node.set_placeholder(placeholder.to_string());
3410        }
3411        if let Some(orientation) = self.aria.orientation {
3412            node.set_orientation(orientation);
3413        }
3414        if let Some(level) = self.aria.level {
3415            node.set_level(level);
3416        }
3417        if let Some(position) = self.aria.position_in_set {
3418            node.set_position_in_set(position);
3419        }
3420        if let Some(size) = self.aria.size_of_set {
3421            node.set_size_of_set(size);
3422        }
3423        if let Some(index) = self.aria.row_index {
3424            node.set_row_index(index);
3425        }
3426        if let Some(index) = self.aria.column_index {
3427            node.set_column_index(index);
3428        }
3429        if let Some(count) = self.aria.row_count {
3430            node.set_row_count(count);
3431        }
3432        if let Some(count) = self.aria.column_count {
3433            node.set_column_count(count);
3434        }
3435        if !self.click_listeners.is_empty() {
3436            node.add_action(accesskit::Action::Click);
3437        }
3438        if self.tracked_focus_handle.is_some() || self.focusable {
3439            node.add_action(accesskit::Action::Focus);
3440        }
3441        for (action, _) in &self.a11y_action_listeners {
3442            node.add_action(*action);
3443        }
3444    }
3445}
3446
3447/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks
3448/// and scroll offsets.
3449#[derive(Default)]
3450pub struct InteractiveElementState {
3451    pub(crate) focus_handle: Option<FocusHandle>,
3452    pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3453    pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3454    pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3455    pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3456    /// Set to the window's [`focus_generation`](crate::Window::focus_generation)
3457    /// when an Enter/Space keydown is received while this element is focused,
3458    /// recording that we are waiting for the matching keyup to fire a keyboard
3459    /// click. On keyup the click only fires if the stored generation still
3460    /// matches the window's current one, i.e. focus never moved during the
3461    /// press (mirroring the browser clearing a control's pressed state on
3462    /// blur). `None` means no activation key is pending.
3463    pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3464    pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3465    ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3466    pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3467}
3468
3469/// Whether or not the element or a group that contains it is clicked by the mouse.
3470#[derive(Copy, Clone, Default, Eq, PartialEq)]
3471pub struct ElementClickedState {
3472    /// True if this element's group has been clicked, false otherwise
3473    pub group: bool,
3474
3475    /// True if this element has been clicked, false otherwise
3476    pub element: bool,
3477}
3478
3479impl ElementClickedState {
3480    fn is_clicked(&self) -> bool {
3481        self.group || self.element
3482    }
3483}
3484
3485/// Whether or not the element or a group that contains it is hovered.
3486#[derive(Copy, Clone, Default, Eq, PartialEq)]
3487pub struct ElementHoverState {
3488    /// True if this element's group is hovered, false otherwise
3489    pub group: bool,
3490
3491    /// True if this element is hovered, false otherwise
3492    pub element: bool,
3493}
3494
3495pub(crate) enum ActiveTooltip {
3496    /// Currently delaying before showing the tooltip.
3497    WaitingForShow { _task: Task<()> },
3498    /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
3499    Visible {
3500        tooltip: AnyTooltip,
3501        is_hoverable: bool,
3502    },
3503    /// Tooltip is visible and hoverable, but the mouse is no longer hovering. Currently delaying
3504    /// before hiding it.
3505    WaitingForHide {
3506        tooltip: AnyTooltip,
3507        _task: Task<()>,
3508    },
3509}
3510
3511pub(crate) fn clear_active_tooltip(
3512    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3513    window: &mut Window,
3514) {
3515    match active_tooltip.borrow_mut().take() {
3516        None => {}
3517        Some(ActiveTooltip::WaitingForShow { .. }) => {}
3518        Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3519        Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3520    }
3521}
3522
3523pub(crate) fn clear_active_tooltip_if_not_hoverable(
3524    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3525    window: &mut Window,
3526) {
3527    let should_clear = match active_tooltip.borrow().as_ref() {
3528        None => false,
3529        Some(ActiveTooltip::WaitingForShow { .. }) => false,
3530        Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3531        Some(ActiveTooltip::WaitingForHide { .. }) => false,
3532    };
3533    if should_clear {
3534        active_tooltip.borrow_mut().take();
3535        window.refresh();
3536    }
3537}
3538
3539pub(crate) fn set_tooltip_on_window(
3540    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3541    window: &mut Window,
3542) -> Option<TooltipId> {
3543    let tooltip = match active_tooltip.borrow().as_ref() {
3544        None => return None,
3545        Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3546        Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3547        Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3548    };
3549    Some(window.set_tooltip(tooltip))
3550}
3551
3552pub(crate) fn register_tooltip_mouse_handlers(
3553    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3554    tooltip_id: Option<TooltipId>,
3555    build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3556    check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3557    check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3558    show_delay: Option<Duration>,
3559    window: &mut Window,
3560) {
3561    let current_view = window.current_view();
3562    let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3563
3564    window.on_mouse_event({
3565        let active_tooltip = active_tooltip.clone();
3566        let build_tooltip = build_tooltip.clone();
3567        let check_is_hovered = check_is_hovered.clone();
3568        move |_: &MouseMoveEvent, phase, window, cx| {
3569            handle_tooltip_mouse_move(
3570                &active_tooltip,
3571                &build_tooltip,
3572                &check_is_hovered,
3573                &check_is_hovered_during_prepaint,
3574                tooltip_id,
3575                current_view,
3576                phase,
3577                show_delay,
3578                window,
3579                cx,
3580            )
3581        }
3582    });
3583
3584    window.on_mouse_event({
3585        let active_tooltip = active_tooltip.clone();
3586        move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3587            if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3588                clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3589            }
3590        }
3591    });
3592
3593    window.on_mouse_event({
3594        let active_tooltip = active_tooltip.clone();
3595        move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
3596            if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3597                clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3598            }
3599        }
3600    });
3601}
3602
3603/// Handles displaying tooltips when an element is hovered.
3604///
3605/// The mouse hovering logic also relies on being called from window prepaint in order to handle the
3606/// case where the element the tooltip is on is not rendered - in that case its mouse listeners are
3607/// also not registered. During window prepaint, the hitbox information is not available, so
3608/// `check_is_hovered_during_prepaint` is used which bases the check off of the absolute bounds of
3609/// the element.
3610///
3611/// TODO: There's a minor bug due to the use of absolute bounds while checking during prepaint - it
3612/// does not know if the hitbox is occluded. In the case where a tooltip gets displayed and then
3613/// gets occluded after display, it will stick around until the mouse exits the hover bounds.
3614fn handle_tooltip_mouse_move(
3615    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3616    build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3617    check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3618    check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3619    tooltip_id: Option<TooltipId>,
3620    current_view: EntityId,
3621    phase: DispatchPhase,
3622    show_delay: Duration,
3623    window: &mut Window,
3624    cx: &mut App,
3625) {
3626    // Separates logic for what mutation should occur from applying it, to avoid overlapping
3627    // RefCell borrows.
3628    enum Action {
3629        None,
3630        CancelShow,
3631        ScheduleShow,
3632        CheckVisible,
3633    }
3634
3635    let action = match active_tooltip.borrow().as_ref() {
3636        None => {
3637            let is_hovered = check_is_hovered(window);
3638            if is_hovered && phase.bubble() {
3639                Action::ScheduleShow
3640            } else {
3641                Action::None
3642            }
3643        }
3644        Some(ActiveTooltip::WaitingForShow { .. }) => {
3645            let is_hovered = check_is_hovered(window);
3646            if is_hovered {
3647                Action::None
3648            } else {
3649                Action::CancelShow
3650            }
3651        }
3652        Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3653            if phase.capture()
3654                && !check_is_hovered(window)
3655                && (!*is_hoverable
3656                    || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3657            {
3658                Action::CheckVisible
3659            } else {
3660                Action::None
3661            }
3662        }
3663        Some(ActiveTooltip::WaitingForHide { .. }) => {
3664            if phase.capture()
3665                && (check_is_hovered(window)
3666                    || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3667            {
3668                Action::CheckVisible
3669            } else {
3670                Action::None
3671            }
3672        }
3673    };
3674
3675    match action {
3676        Action::None => {}
3677        Action::CancelShow => {
3678            // Cancel waiting to show tooltip when it is no longer hovered.
3679            active_tooltip.borrow_mut().take();
3680        }
3681        Action::ScheduleShow => {
3682            let delayed_show_task = window.spawn(cx, {
3683                let weak_active_tooltip = Rc::downgrade(active_tooltip);
3684                let build_tooltip = build_tooltip.clone();
3685                let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3686                async move |cx| {
3687                    cx.background_executor().timer(show_delay).await;
3688                    let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3689                        return;
3690                    };
3691                    cx.update(|window, cx| {
3692                        let new_tooltip =
3693                            build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3694                                let weak_active_tooltip = Rc::downgrade(&active_tooltip);
3695                                ActiveTooltip::Visible {
3696                                    tooltip: AnyTooltip {
3697                                        view,
3698                                        mouse_position: window.mouse_position(),
3699                                        check_visible_and_update: Rc::new(
3700                                            move |tooltip_bounds, window, cx| {
3701                                                let Some(active_tooltip) =
3702                                                    weak_active_tooltip.upgrade()
3703                                                else {
3704                                                    return false;
3705                                                };
3706                                                handle_tooltip_check_visible_and_update(
3707                                                    &active_tooltip,
3708                                                    tooltip_is_hoverable,
3709                                                    &check_is_hovered_during_prepaint,
3710                                                    tooltip_bounds,
3711                                                    window,
3712                                                    cx,
3713                                                )
3714                                            },
3715                                        ),
3716                                    },
3717                                    is_hoverable: tooltip_is_hoverable,
3718                                }
3719                            });
3720                        *active_tooltip.borrow_mut() = new_tooltip;
3721                        window.refresh();
3722                    })
3723                    .ok();
3724                }
3725            });
3726            active_tooltip
3727                .borrow_mut()
3728                .replace(ActiveTooltip::WaitingForShow {
3729                    _task: delayed_show_task,
3730                });
3731        }
3732        Action::CheckVisible => cx.notify(current_view),
3733    }
3734}
3735
3736/// Returns a callback which will be called by window prepaint to update tooltip visibility. The
3737/// purpose of doing this logic here instead of the mouse move handler is that the mouse move
3738/// handler won't get called when the element is not painted (e.g. via use of `visible_on_hover`).
3739fn handle_tooltip_check_visible_and_update(
3740    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3741    tooltip_is_hoverable: bool,
3742    check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3743    tooltip_bounds: Bounds<Pixels>,
3744    window: &mut Window,
3745    cx: &mut App,
3746) -> bool {
3747    // Separates logic for what mutation should occur from applying it, to avoid overlapping RefCell
3748    // borrows.
3749    enum Action {
3750        None,
3751        Hide,
3752        ScheduleHide(AnyTooltip),
3753        CancelHide(AnyTooltip),
3754    }
3755
3756    let is_hovered = check_is_hovered(window)
3757        || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
3758    let action = match active_tooltip.borrow().as_ref() {
3759        Some(ActiveTooltip::Visible { tooltip, .. }) => {
3760            if is_hovered {
3761                Action::None
3762            } else {
3763                if tooltip_is_hoverable {
3764                    Action::ScheduleHide(tooltip.clone())
3765                } else {
3766                    Action::Hide
3767                }
3768            }
3769        }
3770        Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
3771            if is_hovered {
3772                Action::CancelHide(tooltip.clone())
3773            } else {
3774                Action::None
3775            }
3776        }
3777        None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
3778    };
3779
3780    match action {
3781        Action::None => {}
3782        Action::Hide => clear_active_tooltip(active_tooltip, window),
3783        Action::ScheduleHide(tooltip) => {
3784            let delayed_hide_task = window.spawn(cx, {
3785                let weak_active_tooltip = Rc::downgrade(active_tooltip);
3786                async move |cx| {
3787                    cx.background_executor()
3788                        .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
3789                        .await;
3790                    let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3791                        return;
3792                    };
3793                    if active_tooltip.borrow_mut().take().is_some() {
3794                        cx.update(|window, _cx| window.refresh()).ok();
3795                    }
3796                }
3797            });
3798            active_tooltip
3799                .borrow_mut()
3800                .replace(ActiveTooltip::WaitingForHide {
3801                    tooltip,
3802                    _task: delayed_hide_task,
3803                });
3804        }
3805        Action::CancelHide(tooltip) => {
3806            // Cancel waiting to hide tooltip when it becomes hovered.
3807            active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
3808                tooltip,
3809                is_hoverable: true,
3810            });
3811        }
3812    }
3813
3814    active_tooltip.borrow().is_some()
3815}
3816
3817#[derive(Default)]
3818pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
3819
3820impl Global for GroupHitboxes {}
3821
3822impl GroupHitboxes {
3823    pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
3824        cx.default_global::<Self>()
3825            .0
3826            .get(name)
3827            .and_then(|bounds_stack| bounds_stack.last())
3828            .cloned()
3829    }
3830
3831    pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
3832        cx.default_global::<Self>()
3833            .0
3834            .entry(name)
3835            .or_default()
3836            .push(hitbox_id);
3837    }
3838
3839    pub fn pop(name: &SharedString, cx: &mut App) {
3840        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
3841    }
3842}
3843
3844/// A wrapper around an element that can store state, produced after assigning an ElementId.
3845pub struct Stateful<E> {
3846    pub(crate) element: E,
3847}
3848
3849impl<E> Styled for Stateful<E>
3850where
3851    E: Styled,
3852{
3853    fn style(&mut self) -> &mut StyleRefinement {
3854        self.element.style()
3855    }
3856}
3857
3858impl<E> StatefulInteractiveElement for Stateful<E>
3859where
3860    E: Element,
3861    Self: InteractiveElement,
3862{
3863}
3864
3865impl<E> InteractiveElement for Stateful<E>
3866where
3867    E: InteractiveElement,
3868{
3869    fn interactivity(&mut self) -> &mut Interactivity {
3870        self.element.interactivity()
3871    }
3872}
3873
3874impl<E> Element for Stateful<E>
3875where
3876    E: Element,
3877{
3878    type RequestLayoutState = E::RequestLayoutState;
3879    type PrepaintState = E::PrepaintState;
3880
3881    fn id(&self) -> Option<ElementId> {
3882        self.element.id()
3883    }
3884
3885    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3886        self.element.source_location()
3887    }
3888
3889    fn a11y_role(&self) -> Option<accesskit::Role> {
3890        self.element.a11y_role()
3891    }
3892
3893    fn write_a11y_info(&self, node: &mut accesskit::Node) {
3894        self.element.write_a11y_info(node);
3895    }
3896
3897    fn a11y_synthetic_children(
3898        &mut self,
3899        prepaint: &mut Self::PrepaintState,
3900        builder: &mut crate::A11ySubtreeBuilder,
3901    ) {
3902        self.element.a11y_synthetic_children(prepaint, builder);
3903    }
3904
3905    fn request_layout(
3906        &mut self,
3907        id: Option<&GlobalElementId>,
3908        inspector_id: Option<&InspectorElementId>,
3909        window: &mut Window,
3910        cx: &mut App,
3911    ) -> (LayoutId, Self::RequestLayoutState) {
3912        self.element.request_layout(id, inspector_id, window, cx)
3913    }
3914
3915    fn prepaint(
3916        &mut self,
3917        id: Option<&GlobalElementId>,
3918        inspector_id: Option<&InspectorElementId>,
3919        bounds: Bounds<Pixels>,
3920        state: &mut Self::RequestLayoutState,
3921        window: &mut Window,
3922        cx: &mut App,
3923    ) -> E::PrepaintState {
3924        self.element
3925            .prepaint(id, inspector_id, bounds, state, window, cx)
3926    }
3927
3928    fn paint(
3929        &mut self,
3930        id: Option<&GlobalElementId>,
3931        inspector_id: Option<&InspectorElementId>,
3932        bounds: Bounds<Pixels>,
3933        request_layout: &mut Self::RequestLayoutState,
3934        prepaint: &mut Self::PrepaintState,
3935        window: &mut Window,
3936        cx: &mut App,
3937    ) {
3938        self.element.paint(
3939            id,
3940            inspector_id,
3941            bounds,
3942            request_layout,
3943            prepaint,
3944            window,
3945            cx,
3946        );
3947    }
3948}
3949
3950impl<E> IntoElement for Stateful<E>
3951where
3952    E: Element,
3953{
3954    type Element = Self;
3955
3956    fn into_element(self) -> Self::Element {
3957        self
3958    }
3959}
3960
3961impl<E> ParentElement for Stateful<E>
3962where
3963    E: ParentElement,
3964{
3965    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
3966        self.element.extend(elements)
3967    }
3968}
3969
3970/// Represents an element that can be scrolled *to* in its parent element.
3971/// Contrary to [ScrollHandle::scroll_to_active_item], an anchored element does not have to be an immediate child of the parent.
3972#[derive(Clone)]
3973pub struct ScrollAnchor {
3974    handle: ScrollHandle,
3975    last_origin: Rc<RefCell<Point<Pixels>>>,
3976}
3977
3978impl ScrollAnchor {
3979    /// Creates a [ScrollAnchor] associated with a given [ScrollHandle].
3980    pub fn for_handle(handle: ScrollHandle) -> Self {
3981        Self {
3982            handle,
3983            last_origin: Default::default(),
3984        }
3985    }
3986    /// Request scroll to this item on the next frame.
3987    pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
3988        let this = self.clone();
3989
3990        window.on_next_frame(move |_, _| {
3991            let viewport_bounds = this.handle.bounds();
3992            let self_bounds = *this.last_origin.borrow();
3993            this.handle.set_offset(viewport_bounds.origin - self_bounds);
3994        });
3995    }
3996}
3997
3998#[derive(Default, Debug)]
3999struct ScrollHandleState {
4000    offset: Rc<RefCell<Point<Pixels>>>,
4001    ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4002    bounds: Bounds<Pixels>,
4003    max_offset: Point<Pixels>,
4004    child_bounds: Vec<Bounds<Pixels>>,
4005    scroll_to_bottom: bool,
4006    overflow: Point<Overflow>,
4007    active_item: Option<ScrollActiveItem>,
4008}
4009
4010#[derive(Default, Debug, Clone, Copy)]
4011struct ScrollActiveItem {
4012    index: usize,
4013    strategy: ScrollStrategy,
4014}
4015
4016#[derive(Default, Debug, Clone, Copy)]
4017enum ScrollStrategy {
4018    #[default]
4019    FirstVisible,
4020    Top,
4021}
4022
4023/// A handle to the scrollable aspects of an element.
4024/// Used for accessing scroll state, like the current scroll offset,
4025/// and for mutating the scroll state, like scrolling to a specific child.
4026#[derive(Clone, Debug)]
4027pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4028
4029impl Default for ScrollHandle {
4030    fn default() -> Self {
4031        Self::new()
4032    }
4033}
4034
4035impl ScrollHandle {
4036    /// Construct a new scroll handle.
4037    pub fn new() -> Self {
4038        Self(Rc::default())
4039    }
4040
4041    /// Get the current scroll offset.
4042    pub fn offset(&self) -> Point<Pixels> {
4043        *self.0.borrow().offset.borrow()
4044    }
4045
4046    /// Get the maximum scroll offset.
4047    pub fn max_offset(&self) -> Point<Pixels> {
4048        self.0.borrow().max_offset
4049    }
4050
4051    /// Get the top child that's scrolled into view.
4052    pub fn top_item(&self) -> usize {
4053        let state = self.0.borrow();
4054        let top = state.bounds.top() - state.offset.borrow().y;
4055
4056        match state.child_bounds.binary_search_by(|bounds| {
4057            if top < bounds.top() {
4058                Ordering::Greater
4059            } else if top > bounds.bottom() {
4060                Ordering::Less
4061            } else {
4062                Ordering::Equal
4063            }
4064        }) {
4065            Ok(ix) => ix,
4066            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4067        }
4068    }
4069
4070    /// Get the bottom child that's scrolled into view.
4071    pub fn bottom_item(&self) -> usize {
4072        let state = self.0.borrow();
4073        let bottom = state.bounds.bottom() - state.offset.borrow().y;
4074
4075        match state.child_bounds.binary_search_by(|bounds| {
4076            if bottom < bounds.top() {
4077                Ordering::Greater
4078            } else if bottom > bounds.bottom() {
4079                Ordering::Less
4080            } else {
4081                Ordering::Equal
4082            }
4083        }) {
4084            Ok(ix) => ix,
4085            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4086        }
4087    }
4088
4089    /// Return the bounds into which this child is painted
4090    pub fn bounds(&self) -> Bounds<Pixels> {
4091        self.0.borrow().bounds
4092    }
4093
4094    /// Get the bounds for a specific child.
4095    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4096        self.0.borrow().child_bounds.get(ix).cloned()
4097    }
4098
4099    /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
4100    pub fn scroll_to_item(&self, ix: usize) {
4101        let mut state = self.0.borrow_mut();
4102        state.active_item = Some(ScrollActiveItem {
4103            index: ix,
4104            strategy: ScrollStrategy::default(),
4105        });
4106    }
4107
4108    /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
4109    /// This scrolls the minimal amount to ensure that the child is the first visible element
4110    pub fn scroll_to_top_of_item(&self, ix: usize) {
4111        let mut state = self.0.borrow_mut();
4112        state.active_item = Some(ScrollActiveItem {
4113            index: ix,
4114            strategy: ScrollStrategy::Top,
4115        });
4116    }
4117
4118    /// Scrolls the minimal amount to either ensure that the child is
4119    /// fully visible or the top element of the view depends on the
4120    /// scroll strategy
4121    fn scroll_to_active_item(&self) {
4122        let mut state = self.0.borrow_mut();
4123
4124        let Some(active_item) = state.active_item else {
4125            return;
4126        };
4127
4128        let active_item = match state.child_bounds.get(active_item.index) {
4129            Some(bounds) => {
4130                let mut scroll_offset = state.offset.borrow_mut();
4131
4132                match active_item.strategy {
4133                    ScrollStrategy::FirstVisible => {
4134                        if state.overflow.y == Overflow::Scroll {
4135                            let child_height = bounds.size.height;
4136                            let viewport_height = state.bounds.size.height;
4137                            if child_height > viewport_height {
4138                                scroll_offset.y = state.bounds.top() - bounds.top();
4139                            } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4140                                scroll_offset.y = state.bounds.top() - bounds.top();
4141                            } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4142                                scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4143                            }
4144                        }
4145                    }
4146                    ScrollStrategy::Top => {
4147                        scroll_offset.y = state.bounds.top() - bounds.top();
4148                    }
4149                }
4150
4151                if state.overflow.x == Overflow::Scroll {
4152                    let child_width = bounds.size.width;
4153                    let viewport_width = state.bounds.size.width;
4154                    if child_width > viewport_width {
4155                        scroll_offset.x = state.bounds.left() - bounds.left();
4156                    } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4157                        scroll_offset.x = state.bounds.left() - bounds.left();
4158                    } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4159                        scroll_offset.x = state.bounds.right() - bounds.right();
4160                    }
4161                }
4162                None
4163            }
4164            None => Some(active_item),
4165        };
4166        state.active_item = active_item;
4167    }
4168
4169    /// Scrolls to the bottom.
4170    pub fn scroll_to_bottom(&self) {
4171        let mut state = self.0.borrow_mut();
4172        state.scroll_to_bottom = true;
4173    }
4174
4175    /// Set the offset explicitly. The offset is the distance from the top left of the
4176    /// parent container to the top left of the first child.
4177    /// As you scroll further down the offset becomes more negative.
4178    pub fn set_offset(&self, mut position: Point<Pixels>) {
4179        let state = self.0.borrow();
4180        *state.offset.borrow_mut() = position;
4181    }
4182
4183    /// Get the logical scroll top, based on a child index and a pixel offset.
4184    pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4185        let ix = self.top_item();
4186        let state = self.0.borrow();
4187
4188        if let Some(child_bounds) = state.child_bounds.get(ix) {
4189            (
4190                ix,
4191                child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4192            )
4193        } else {
4194            (ix, px(0.))
4195        }
4196    }
4197
4198    /// Get the logical scroll bottom, based on a child index and a pixel offset.
4199    pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4200        let ix = self.bottom_item();
4201        let state = self.0.borrow();
4202
4203        if let Some(child_bounds) = state.child_bounds.get(ix) {
4204            (
4205                ix,
4206                child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4207            )
4208        } else {
4209            (ix, px(0.))
4210        }
4211    }
4212
4213    /// Get the count of children for scrollable item.
4214    pub fn children_count(&self) -> usize {
4215        self.0.borrow().child_bounds.len()
4216    }
4217}
4218
4219#[cfg(test)]
4220mod tests {
4221    use super::*;
4222    use crate::{
4223        AnyWindowHandle, AppContext as _, Context, InputEvent, Keystroke, MouseMoveEvent,
4224        TestAppContext, canvas, util::FluentBuilder as _,
4225    };
4226    use std::{cell::Cell, rc::Weak};
4227
4228    struct GroupHoverTestView {
4229        render_count: Rc<Cell<usize>>,
4230        anonymous_paint_count: Rc<Cell<usize>>,
4231        stateful_width: Rc<Cell<Pixels>>,
4232    }
4233
4234    impl Render for GroupHoverTestView {
4235        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4236            self.render_count.set(self.render_count.get() + 1);
4237            let anonymous_paint_count = self.anonymous_paint_count.clone();
4238            let stateful_width = self.stateful_width.clone();
4239            div().size_full().child(
4240                div()
4241                    .ml(px(20.))
4242                    .mt(px(20.))
4243                    .size(px(50.))
4244                    .relative()
4245                    .group("hover-group")
4246                    .child(
4247                        div()
4248                            .absolute()
4249                            .size_full()
4250                            .invisible()
4251                            .group_hover("hover-group", |style| style.visible())
4252                            .child(canvas(
4253                                |_, _, _| {},
4254                                move |_, _, _, _| {
4255                                    anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4256                                },
4257                            )),
4258                    )
4259                    .child(
4260                        div()
4261                            .id("stateful-group-hover-target")
4262                            .absolute()
4263                            .top_0()
4264                            .left_0()
4265                            .size(px(10.))
4266                            .group_hover("hover-group", |style| style.size(px(20.)))
4267                            .child(canvas(
4268                                move |bounds, _, _| stateful_width.set(bounds.size.width),
4269                                |_, _, _, _| {},
4270                            )),
4271                    ),
4272            )
4273        }
4274    }
4275
4276    #[gpui::test]
4277    fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4278        let render_count = Rc::new(Cell::new(0));
4279        let anonymous_paint_count = Rc::new(Cell::new(0));
4280        let stateful_width = Rc::new(Cell::new(px(0.)));
4281        let window = cx.add_window({
4282            let render_count = render_count.clone();
4283            let anonymous_paint_count = anonymous_paint_count.clone();
4284            let stateful_width = stateful_width.clone();
4285            move |_, _| GroupHoverTestView {
4286                render_count,
4287                anonymous_paint_count,
4288                stateful_width,
4289            }
4290        });
4291        let window = AnyWindowHandle::from(window);
4292
4293        cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4294            .unwrap();
4295        assert_eq!(anonymous_paint_count.get(), 0);
4296        assert_eq!(stateful_width.get(), px(10.));
4297
4298        let move_mouse = |cx: &mut TestAppContext, position| {
4299            cx.update_window(window, |_, window, cx| {
4300                window.simulate_mouse_move(position, cx)
4301            })
4302            .unwrap();
4303        };
4304
4305        let initial_render_count = render_count.get();
4306        move_mouse(cx, point(px(25.), px(25.)));
4307        assert_eq!(render_count.get(), initial_render_count + 1);
4308        assert_eq!(anonymous_paint_count.get(), 1);
4309        assert_eq!(stateful_width.get(), px(20.));
4310
4311        move_mouse(cx, point(px(30.), px(30.)));
4312        assert_eq!(render_count.get(), initial_render_count + 1);
4313        assert_eq!(anonymous_paint_count.get(), 1);
4314        assert_eq!(stateful_width.get(), px(20.));
4315
4316        move_mouse(cx, point(px(5.), px(5.)));
4317        assert_eq!(render_count.get(), initial_render_count + 2);
4318        assert_eq!(anonymous_paint_count.get(), 1);
4319        assert_eq!(stateful_width.get(), px(10.));
4320
4321        move_mouse(cx, point(px(10.), px(10.)));
4322        assert_eq!(render_count.get(), initial_render_count + 2);
4323        assert_eq!(anonymous_paint_count.get(), 1);
4324        assert_eq!(stateful_width.get(), px(10.));
4325    }
4326
4327    struct TestTooltipView;
4328
4329    impl Render for TestTooltipView {
4330        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4331            div().w(px(20.)).h(px(20.)).child("tooltip")
4332        }
4333    }
4334
4335    type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4336
4337    struct TooltipCaptureElement {
4338        child: AnyElement,
4339        captured_active_tooltip: CapturedActiveTooltip,
4340    }
4341
4342    impl IntoElement for TooltipCaptureElement {
4343        type Element = Self;
4344
4345        fn into_element(self) -> Self::Element {
4346            self
4347        }
4348    }
4349
4350    impl Element for TooltipCaptureElement {
4351        type RequestLayoutState = ();
4352        type PrepaintState = ();
4353
4354        fn id(&self) -> Option<ElementId> {
4355            None
4356        }
4357
4358        fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4359            None
4360        }
4361
4362        fn request_layout(
4363            &mut self,
4364            _id: Option<&GlobalElementId>,
4365            _inspector_id: Option<&InspectorElementId>,
4366            window: &mut Window,
4367            cx: &mut App,
4368        ) -> (LayoutId, Self::RequestLayoutState) {
4369            (self.child.request_layout(window, cx), ())
4370        }
4371
4372        fn prepaint(
4373            &mut self,
4374            _id: Option<&GlobalElementId>,
4375            _inspector_id: Option<&InspectorElementId>,
4376            _bounds: Bounds<Pixels>,
4377            _request_layout: &mut Self::RequestLayoutState,
4378            window: &mut Window,
4379            cx: &mut App,
4380        ) -> Self::PrepaintState {
4381            self.child.prepaint(window, cx);
4382        }
4383
4384        fn paint(
4385            &mut self,
4386            _id: Option<&GlobalElementId>,
4387            _inspector_id: Option<&InspectorElementId>,
4388            _bounds: Bounds<Pixels>,
4389            _request_layout: &mut Self::RequestLayoutState,
4390            _prepaint: &mut Self::PrepaintState,
4391            window: &mut Window,
4392            cx: &mut App,
4393        ) {
4394            self.child.paint(window, cx);
4395            window.with_global_id("target".into(), |global_id, window| {
4396                window.with_element_state::<InteractiveElementState, _>(
4397                    global_id,
4398                    |state, _window| {
4399                        let state = state.unwrap();
4400                        *self.captured_active_tooltip.borrow_mut() =
4401                            state.active_tooltip.as_ref().map(Rc::downgrade);
4402                        ((), state)
4403                    },
4404                )
4405            });
4406        }
4407    }
4408
4409    struct TooltipOwner {
4410        captured_active_tooltip: CapturedActiveTooltip,
4411        show_delay_override: Option<Duration>,
4412    }
4413
4414    impl Render for TooltipOwner {
4415        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4416            TooltipCaptureElement {
4417                child: div()
4418                    .size_full()
4419                    .child(
4420                        div()
4421                            .id("target")
4422                            .w(px(50.))
4423                            .h(px(50.))
4424                            .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4425                            .when_some(self.show_delay_override, |this, delay| {
4426                                this.tooltip_show_delay(delay)
4427                            }),
4428                    )
4429                    .into_any_element(),
4430                captured_active_tooltip: self.captured_active_tooltip.clone(),
4431            }
4432        }
4433    }
4434
4435    #[test]
4436    fn scroll_handle_aligns_wide_children_to_left_edge() {
4437        let handle = ScrollHandle::new();
4438        {
4439            let mut state = handle.0.borrow_mut();
4440            state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4441            state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4442            state.overflow.x = Overflow::Scroll;
4443            state.active_item = Some(ScrollActiveItem {
4444                index: 0,
4445                strategy: ScrollStrategy::default(),
4446            });
4447        }
4448
4449        handle.scroll_to_active_item();
4450
4451        assert_eq!(handle.offset().x, px(-25.));
4452    }
4453
4454    #[test]
4455    fn scroll_handle_aligns_tall_children_to_top_edge() {
4456        let handle = ScrollHandle::new();
4457        {
4458            let mut state = handle.0.borrow_mut();
4459            state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4460            state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4461            state.overflow.y = Overflow::Scroll;
4462            state.active_item = Some(ScrollActiveItem {
4463                index: 0,
4464                strategy: ScrollStrategy::default(),
4465            });
4466        }
4467
4468        handle.scroll_to_active_item();
4469
4470        assert_eq!(handle.offset().y, px(-25.));
4471    }
4472
4473    fn setup_tooltip_owner_test(
4474        show_delay_override: Option<Duration>,
4475    ) -> (
4476        TestAppContext,
4477        crate::AnyWindowHandle,
4478        CapturedActiveTooltip,
4479    ) {
4480        let mut test_app = TestAppContext::single();
4481        let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
4482        let window = test_app.add_window({
4483            let captured_active_tooltip = captured_active_tooltip.clone();
4484            move |_, _| TooltipOwner {
4485                captured_active_tooltip,
4486                show_delay_override,
4487            }
4488        });
4489        let any_window = window.into();
4490
4491        test_app
4492            .update_window(any_window, |_, window, cx| {
4493                window.draw(cx).clear(cx);
4494            })
4495            .unwrap();
4496
4497        test_app
4498            .update_window(any_window, |_, window, cx| {
4499                window.dispatch_event(
4500                    MouseMoveEvent {
4501                        position: point(px(10.), px(10.)),
4502                        modifiers: Default::default(),
4503                        pressed_button: None,
4504                    }
4505                    .to_platform_input(),
4506                    cx,
4507                );
4508            })
4509            .unwrap();
4510
4511        test_app
4512            .update_window(any_window, |_, window, cx| {
4513                window.draw(cx).clear(cx);
4514            })
4515            .unwrap();
4516
4517        (test_app, any_window, captured_active_tooltip)
4518    }
4519
4520    #[test]
4521    fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
4522        let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4523
4524        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4525        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4526        assert!(matches!(
4527            active_tooltip.borrow().as_ref(),
4528            Some(ActiveTooltip::WaitingForShow { .. })
4529        ));
4530
4531        test_app
4532            .update_window(any_window, |_, window, _| {
4533                window.remove_window();
4534            })
4535            .unwrap();
4536        test_app.run_until_parked();
4537        drop(active_tooltip);
4538
4539        assert!(weak_active_tooltip.upgrade().is_none());
4540    }
4541
4542    #[test]
4543    fn tooltip_respects_custom_show_delay() {
4544        let extra_delay = Duration::from_secs(1);
4545        let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
4546        let (mut test_app, _any_window, captured_active_tooltip) =
4547            setup_tooltip_owner_test(Some(show_delay_override));
4548
4549        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4550        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4551
4552        test_app
4553            .dispatcher
4554            .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4555        test_app.run_until_parked();
4556
4557        assert!(matches!(
4558            active_tooltip.borrow().as_ref(),
4559            Some(ActiveTooltip::WaitingForShow { .. })
4560        ));
4561
4562        test_app.dispatcher.advance_clock(extra_delay);
4563        test_app.run_until_parked();
4564
4565        assert!(matches!(
4566            active_tooltip.borrow().as_ref(),
4567            Some(ActiveTooltip::Visible { .. })
4568        ));
4569    }
4570
4571    #[test]
4572    fn tooltip_is_released_when_its_owner_disappears() {
4573        let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4574
4575        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4576        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4577
4578        test_app
4579            .dispatcher
4580            .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4581        test_app.run_until_parked();
4582
4583        assert!(matches!(
4584            active_tooltip.borrow().as_ref(),
4585            Some(ActiveTooltip::Visible { .. })
4586        ));
4587
4588        test_app
4589            .update_window(any_window, |_, window, _| {
4590                window.remove_window();
4591            })
4592            .unwrap();
4593        test_app.run_until_parked();
4594        drop(active_tooltip);
4595
4596        assert!(weak_active_tooltip.upgrade().is_none());
4597    }
4598
4599    #[test]
4600    fn tooltip_hides_after_mouse_leaves_origin() {
4601        let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4602
4603        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4604        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4605
4606        test_app
4607            .dispatcher
4608            .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4609        test_app.run_until_parked();
4610
4611        assert!(matches!(
4612            active_tooltip.borrow().as_ref(),
4613            Some(ActiveTooltip::Visible { .. })
4614        ));
4615
4616        test_app
4617            .update_window(any_window, |_, window, cx| {
4618                window.dispatch_event(
4619                    MouseMoveEvent {
4620                        position: point(px(75.), px(75.)),
4621                        modifiers: Default::default(),
4622                        pressed_button: None,
4623                    }
4624                    .to_platform_input(),
4625                    cx,
4626                );
4627            })
4628            .unwrap();
4629
4630        assert!(active_tooltip.borrow().is_none());
4631    }
4632
4633    struct MouseDownOutOwner {
4634        mouse_down_out_count: Rc<RefCell<usize>>,
4635    }
4636
4637    impl Render for MouseDownOutOwner {
4638        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4639            let mouse_down_out_count = self.mouse_down_out_count.clone();
4640            div()
4641                .size_full()
4642                .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
4643                    move |_, _, _| {
4644                        *mouse_down_out_count.borrow_mut() += 1;
4645                    },
4646                ))
4647        }
4648    }
4649
4650    #[test]
4651    fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
4652        let mut test_app = TestAppContext::single();
4653        let mouse_down_out_count = Rc::new(RefCell::new(0));
4654        let window = test_app.add_window({
4655            let mouse_down_out_count = mouse_down_out_count.clone();
4656            move |_, _| MouseDownOutOwner {
4657                mouse_down_out_count,
4658            }
4659        });
4660        let any_window: AnyWindowHandle = window.into();
4661
4662        fn dispatch_mouse_down_outside_target(
4663            test_app: &mut TestAppContext,
4664            any_window: AnyWindowHandle,
4665        ) {
4666            test_app
4667                .update_window(any_window, |_, window, cx| {
4668                    window.dispatch_event(
4669                        MouseDownEvent {
4670                            position: point(px(75.), px(75.)),
4671                            button: MouseButton::Left,
4672                            modifiers: Default::default(),
4673                            click_count: 1,
4674                            first_mouse: false,
4675                        }
4676                        .to_platform_input(),
4677                        cx,
4678                    );
4679                })
4680                .unwrap();
4681        }
4682
4683        test_app
4684            .update_window(any_window, |_, window, cx| {
4685                window.draw(cx).clear(cx);
4686            })
4687            .unwrap();
4688
4689        dispatch_mouse_down_outside_target(&mut test_app, any_window);
4690        assert_eq!(
4691            *mouse_down_out_count.borrow(),
4692            1,
4693            "mouse down outside the element should fire mouse-down-out listeners"
4694        );
4695
4696        test_app
4697            .update_window(any_window, |_, window, cx| {
4698                cx.set_prompt_builder(crate::fallback_prompt_renderer);
4699                let _receiver =
4700                    window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
4701                assert!(window.has_active_prompt());
4702                window.draw(cx).clear(cx);
4703            })
4704            .unwrap();
4705
4706        dispatch_mouse_down_outside_target(&mut test_app, any_window);
4707        assert_eq!(
4708            *mouse_down_out_count.borrow(),
4709            1,
4710            "mouse down over an active prompt should not fire mouse-down-out listeners"
4711        );
4712    }
4713
4714    #[test]
4715    fn test_write_a11y_info_string_and_numeric_properties() {
4716        let mut interactivity = Interactivity::default();
4717        interactivity.aria.label = Some("Buffer Font Size".into());
4718        interactivity.aria.value = Some("15".into());
4719        interactivity.aria.placeholder = Some("Search".into());
4720        interactivity.aria.numeric_value = Some(15.0);
4721        interactivity.aria.min_numeric_value = Some(6.0);
4722        interactivity.aria.max_numeric_value = Some(72.0);
4723        interactivity.aria.numeric_value_step = Some(1.0);
4724
4725        let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
4726        interactivity.write_a11y_info(&mut node);
4727
4728        assert_eq!(node.label(), Some("Buffer Font Size"));
4729        assert_eq!(node.value(), Some("15"));
4730        assert_eq!(node.placeholder(), Some("Search"));
4731        assert_eq!(node.numeric_value(), Some(15.0));
4732        assert_eq!(node.min_numeric_value(), Some(6.0));
4733        assert_eq!(node.max_numeric_value(), Some(72.0));
4734        assert_eq!(node.numeric_value_step(), Some(1.0));
4735    }
4736
4737    /// Two focusable, clickable elements ("a" and "b") used to exercise the
4738    /// Enter/Space -> synthesized click press/release pairing.
4739    struct KeyboardActivationTest {
4740        focus_a: FocusHandle,
4741        focus_b: FocusHandle,
4742        clicks: Rc<RefCell<Vec<&'static str>>>,
4743    }
4744
4745    impl Render for KeyboardActivationTest {
4746        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4747            let clicks_a = self.clicks.clone();
4748            let clicks_b = self.clicks.clone();
4749            div()
4750                .size_full()
4751                .child(
4752                    div()
4753                        .id("a")
4754                        .w(px(50.))
4755                        .h(px(50.))
4756                        .track_focus(&self.focus_a)
4757                        .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
4758                )
4759                .child(
4760                    div()
4761                        .id("b")
4762                        .w(px(50.))
4763                        .h(px(50.))
4764                        .track_focus(&self.focus_b)
4765                        .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
4766                )
4767        }
4768    }
4769
4770    fn setup_keyboard_activation_test() -> (
4771        TestAppContext,
4772        AnyWindowHandle,
4773        Rc<RefCell<Vec<&'static str>>>,
4774        FocusHandle,
4775        FocusHandle,
4776    ) {
4777        let mut cx = TestAppContext::single();
4778        let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
4779        let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
4780        let window = cx.add_window({
4781            let focus_a = focus_a.clone();
4782            let focus_b = focus_b.clone();
4783            let clicks = clicks.clone();
4784            move |_, _| KeyboardActivationTest {
4785                focus_a,
4786                focus_b,
4787                clicks,
4788            }
4789        });
4790        (cx, window.into(), clicks, focus_a, focus_b)
4791    }
4792
4793    /// Move focus to `handle`, flush effects, then paint so the newly focused
4794    /// element registers its key handlers for the next dispatched event.
4795    fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
4796        cx.update_window(window, |_, window, cx| window.focus(handle, cx))
4797            .unwrap();
4798        cx.run_until_parked();
4799        cx.update_window(window, |_, window, cx| {
4800            window.draw(cx).clear(cx);
4801        })
4802        .unwrap();
4803    }
4804
4805    fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4806        let keystroke = Keystroke::parse(key).unwrap();
4807        cx.update_window(window, |_, window, cx| {
4808            window.dispatch_event(
4809                KeyDownEvent {
4810                    keystroke,
4811                    is_held: false,
4812                    prefer_character_input: false,
4813                }
4814                .to_platform_input(),
4815                cx,
4816            );
4817        })
4818        .unwrap();
4819    }
4820
4821    fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4822        let keystroke = Keystroke::parse(key).unwrap();
4823        cx.update_window(window, |_, window, cx| {
4824            window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
4825        })
4826        .unwrap();
4827    }
4828
4829    /// Pressing and releasing Enter on the same focused element fires a click.
4830    #[test]
4831    fn keyboard_activation_fires_click_on_same_element() {
4832        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4833
4834        focus_and_draw(&mut cx, window, &focus_a);
4835        key_down(&mut cx, window, "enter");
4836        key_up(&mut cx, window, "enter");
4837
4838        assert_eq!(*clicks.borrow(), vec!["a"]);
4839    }
4840
4841    /// A key-down whose key-up lands on a *different* element (because focus
4842    /// moved in between) must not leak a synthesized click onto the newly
4843    /// focused element. This is the core regression: previously the key-up
4844    /// handler fired unconditionally on whatever was focused at key-up time.
4845    #[test]
4846    fn keyboard_activation_does_not_leak_across_focus_change() {
4847        let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
4848
4849        // Enter pressed while "a" is focused...
4850        focus_and_draw(&mut cx, window, &focus_a);
4851        key_down(&mut cx, window, "enter");
4852
4853        // ...focus moves to "b" before the release (as a confirm action would)...
4854        focus_and_draw(&mut cx, window, &focus_b);
4855        key_up(&mut cx, window, "enter");
4856
4857        // ...so neither element is clicked: "a" never saw the up, and "b"
4858        // never saw the down.
4859        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4860    }
4861
4862    /// A keydown whose flag is left pending because focus moved away before
4863    /// the keyup must not fire a click when focus later *returns* to the same
4864    /// element (the menu trigger reopening case). The stamped focus generation
4865    /// no longer matches, so the stale pending state is ignored.
4866    #[test]
4867    fn keyboard_activation_does_not_leak_when_focus_returns() {
4868        let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
4869
4870        // Enter pressed on "a"...
4871        focus_and_draw(&mut cx, window, &focus_a);
4872        key_down(&mut cx, window, "enter");
4873
4874        // ...focus leaves "a" before its keyup (so the pending state is never
4875        // consumed), then comes back to "a"...
4876        focus_and_draw(&mut cx, window, &focus_b);
4877        focus_and_draw(&mut cx, window, &focus_a);
4878        key_up(&mut cx, window, "enter");
4879
4880        // ...and the now-stale pending keydown must not fire a click.
4881        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4882    }
4883
4884    /// A non-activation key *released* during the press must cancel the pending
4885    /// activation. For the sequence escape-down, space-down, escape-up,
4886    /// space-up the space forms a clean down/up pair, but the intervening
4887    /// escape-up means this isn't a plain space activation, so no click fires.
4888    #[test]
4889    fn keyboard_activation_cleared_by_intervening_key_release() {
4890        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4891
4892        focus_and_draw(&mut cx, window, &focus_a);
4893        key_down(&mut cx, window, "escape");
4894        key_down(&mut cx, window, "space");
4895        key_up(&mut cx, window, "escape");
4896        key_up(&mut cx, window, "space");
4897
4898        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4899    }
4900
4901    /// The flag is a single activation marker, not keyed by which activation
4902    /// key was used, so a Space down paired with an Enter up on the same
4903    /// element still fires a click.
4904    #[test]
4905    fn keyboard_activation_does_not_distinguish_space_and_enter() {
4906        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4907
4908        focus_and_draw(&mut cx, window, &focus_a);
4909        key_down(&mut cx, window, "space");
4910        key_up(&mut cx, window, "enter");
4911
4912        assert_eq!(*clicks.borrow(), vec!["a"]);
4913    }
4914
4915    /// A non-activation key pressed between the activation down and up clears
4916    /// the pending flag, suppressing the click.
4917    #[test]
4918    fn keyboard_activation_cleared_by_intervening_keydown() {
4919        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4920
4921        focus_and_draw(&mut cx, window, &focus_a);
4922        key_down(&mut cx, window, "enter");
4923        key_down(&mut cx, window, "a");
4924        key_up(&mut cx, window, "enter");
4925
4926        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4927    }
4928
4929    /// A modified Enter (e.g. cmd-enter) is not treated as an activation key,
4930    /// so it neither sets the pending flag nor fires a click on release.
4931    #[test]
4932    fn keyboard_activation_ignores_modified_keys() {
4933        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4934
4935        focus_and_draw(&mut cx, window, &focus_a);
4936        key_down(&mut cx, window, "cmd-enter");
4937        key_up(&mut cx, window, "cmd-enter");
4938
4939        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4940    }
4941
4942    /// Two sibling tab groups, each a focusable container that is *not* itself a
4943    /// tab stop and holds a single tab stop. Mirrors how the title bar and
4944    /// status bar expose their controls as ARIA toolbars.
4945    struct TabGroupFocus {
4946        group_a: FocusHandle,
4947        item_a: FocusHandle,
4948        group_b: FocusHandle,
4949        item_b: FocusHandle,
4950    }
4951
4952    impl Render for TabGroupFocus {
4953        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4954            fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
4955                div()
4956                    .track_focus(container)
4957                    .tab_group()
4958                    .child(div().track_focus(item))
4959            }
4960            div()
4961                .child(group(&self.group_a, &self.item_a))
4962                .child(group(&self.group_b, &self.item_b))
4963        }
4964    }
4965
4966    /// Focusing a tab-group container and pressing Tab (`focus_next`) must move
4967    /// focus to the first tab stop *inside that container*, as documented on
4968    /// [`InteractiveElement::tab_stop`].
4969    #[test]
4970    fn focus_next_from_tab_group_container_enters_that_group() {
4971        let mut cx = TestAppContext::single();
4972        let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
4973            (
4974                cx.focus_handle(),
4975                cx.focus_handle().tab_stop(true),
4976                cx.focus_handle(),
4977                cx.focus_handle().tab_stop(true),
4978            )
4979        });
4980        let window: AnyWindowHandle = cx
4981            .add_window({
4982                let (group_a, item_a, group_b, item_b) =
4983                    (group_a, item_a, group_b.clone(), item_b.clone());
4984                move |_, _| TabGroupFocus {
4985                    group_a,
4986                    item_a,
4987                    group_b,
4988                    item_b,
4989                }
4990            })
4991            .into();
4992        cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4993            .unwrap();
4994
4995        // Focus the *second* group's container, then advance like Tab would.
4996        let focused = cx
4997            .update_window(window, |_, window, cx| {
4998                window.focus(&group_b, cx);
4999                window.focus_next(cx);
5000                window.focused(cx).map(|handle| handle.id)
5001            })
5002            .unwrap();
5003
5004        assert_eq!(focused, Some(item_b.id));
5005    }
5006
5007    #[gpui::test]
5008    fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5009        cx: &mut TestAppContext,
5010    ) {
5011        struct PaddedContainer {
5012            scroll_handle: ScrollHandle,
5013        }
5014
5015        impl Render for PaddedContainer {
5016            fn render(
5017                &mut self,
5018                _window: &mut Window,
5019                _cx: &mut Context<Self>,
5020            ) -> impl IntoElement {
5021                // 4.25px of padding snaps to 4px in layout, so a 42px child
5022                // fits the 50px box exactly.
5023                div().size_full().child(
5024                    div()
5025                        .id("container")
5026                        .h(px(50.))
5027                        .w(px(100.))
5028                        .py(px(4.25))
5029                        .overflow_y_scroll()
5030                        .track_scroll(&self.scroll_handle)
5031                        .child(div().w_full().h(px(42.))),
5032                )
5033            }
5034        }
5035
5036        let scroll_handle = ScrollHandle::new();
5037        let window: AnyWindowHandle = cx
5038            .add_window({
5039                let scroll_handle = scroll_handle.clone();
5040                move |_, _| PaddedContainer { scroll_handle }
5041            })
5042            .into();
5043        cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5044            .unwrap();
5045
5046        assert_eq!(scroll_handle.max_offset().y, px(0.));
5047    }
5048}