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 = f(&style, scroll_offset, hitbox, window, cx);
2269                            (result, element_state)
2270                        },
2271                    )
2272                })
2273            },
2274        )
2275    }
2276
2277    fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2278        self.hitbox_behavior != HitboxBehavior::Normal
2279            || self.window_control.is_some()
2280            || style.mouse_cursor.is_some()
2281            || self.group.is_some()
2282            || self.scroll_offset.is_some()
2283            || self.tracked_focus_handle.is_some()
2284            || self.hover_style.is_some()
2285            || self.group_hover_style.is_some()
2286            || self.hover_listener.is_some()
2287            || !self.mouse_up_listeners.is_empty()
2288            || !self.mouse_pressure_listeners.is_empty()
2289            || !self.mouse_down_listeners.is_empty()
2290            || !self.mouse_move_listeners.is_empty()
2291            || !self.mouse_exit_listeners.is_empty()
2292            || !self.click_listeners.is_empty()
2293            || !self.aux_click_listeners.is_empty()
2294            || !self.scroll_wheel_listeners.is_empty()
2295            || self.has_pinch_listeners()
2296            || self.drag_listener.is_some()
2297            || !self.drop_listeners.is_empty()
2298            || !self.drag_over_styles.is_empty()
2299            || self.tooltip_builder.is_some()
2300            || window.is_inspector_picking(cx)
2301    }
2302
2303    fn clamp_scroll_position(
2304        &self,
2305        bounds: Bounds<Pixels>,
2306        style: &Style,
2307        window: &mut Window,
2308        _cx: &mut App,
2309    ) -> Point<Pixels> {
2310        fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2311            const ROUNDING_FACTOR: f32 = 100.0;
2312            (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2313        }
2314
2315        if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2316            let mut scroll_to_bottom = false;
2317            let mut tracked_scroll_handle = self
2318                .tracked_scroll_handle
2319                .as_ref()
2320                .map(|handle| handle.0.borrow_mut());
2321            if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2322                scroll_handle_state.overflow = style.overflow;
2323                scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2324            }
2325
2326            let rem_size = window.rem_size();
2327            // Taffy lays the box out with the padding snapped to the device pixel
2328            // grid (`to_taffy`); recomputed unsnapped, e.g. py_1 at a fractional
2329            // rem size, it exceeds `bounds` and leaves the box scrollable by the
2330            // sub-pixel difference.
2331            let padding = style
2332                .padding
2333                .to_pixels(bounds.size.into(), rem_size)
2334                .map(|edge| window.pixel_snap(*edge));
2335            let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2336            // The floating point values produced by Taffy and ours often vary
2337            // slightly after ~5 decimal places. This can lead to cases where after
2338            // subtracting these, the container becomes scrollable for less than
2339            // 0.00000x pixels. As we generally don't benefit from a precision that
2340            // high for the maximum scroll, we round the scroll max to 2 decimal
2341            // places here.
2342            let padded_content_size = self.content_size + padding_size;
2343            let scroll_max = Point::from(padded_content_size - bounds.size)
2344                .map(round_to_two_decimals)
2345                .max(&Default::default());
2346            // Clamp scroll offset in case scroll max is smaller now (e.g., if children
2347            // were removed or the bounds became larger).
2348            let mut scroll_offset = scroll_offset.borrow_mut();
2349
2350            scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2351            if scroll_to_bottom {
2352                scroll_offset.y = -scroll_max.y;
2353            } else {
2354                scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2355            }
2356
2357            if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2358                scroll_handle_state.max_offset = scroll_max;
2359                scroll_handle_state.bounds = bounds;
2360            }
2361
2362            *scroll_offset
2363        } else {
2364            Point::default()
2365        }
2366    }
2367
2368    /// Paint this element according to this interactivity state's configured styles
2369    /// and bind the element's mouse and keyboard events.
2370    ///
2371    /// content_size is the size of the content of the element, which may be larger than the
2372    /// element's bounds if the element is scrollable.
2373    ///
2374    /// the final computed style will be passed to the provided function, along
2375    /// with the current scroll offset
2376    pub fn paint(
2377        &mut self,
2378        global_id: Option<&GlobalElementId>,
2379        _inspector_id: Option<&InspectorElementId>,
2380        bounds: Bounds<Pixels>,
2381        hitbox: Option<&Hitbox>,
2382        window: &mut Window,
2383        cx: &mut App,
2384        f: impl FnOnce(&Style, &mut Window, &mut App),
2385    ) {
2386        self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2387        window.with_optional_element_state::<InteractiveElementState, _>(
2388            global_id,
2389            |element_state, window| {
2390                let mut element_state =
2391                    element_state.map(|element_state| element_state.unwrap_or_default());
2392
2393                let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2394
2395                #[cfg(any(feature = "test-support", test))]
2396                if let Some(debug_selector) = &self.debug_selector {
2397                    window
2398                        .next_frame
2399                        .record_debug_bounds(debug_selector.clone(), bounds);
2400                }
2401
2402                self.paint_hover_group_handler(window, cx);
2403
2404                if style.visibility == Visibility::Hidden {
2405                    return ((), element_state);
2406                }
2407
2408                let mut tab_group = None;
2409                if self.tab_group {
2410                    tab_group = self.tab_index;
2411                }
2412
2413                window.with_element_opacity(style.opacity, |window| {
2414                    style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2415                        window.with_text_style(style.text_style().cloned(), |window| {
2416                            window.with_content_mask(
2417                                style.overflow_mask(bounds, window.rem_size()),
2418                                |window| {
2419                                    window.with_tab_group(tab_group, |window| {
2420                                        // Register the container's own focus handle *inside* its
2421                                        // tab group, so that focusing the container and then
2422                                        // calling `focus_next` descends into this group's first
2423                                        // item. Inserting it before `with_tab_group` would give the
2424                                        // container a shallower tab path than its children; with
2425                                        // sibling groups every container would then sort ahead of
2426                                        // every item, and `focus_next` from a container would jump
2427                                        // to the first item in the whole window instead of its own.
2428                                        if let Some(focus_handle) = &self.tracked_focus_handle {
2429                                            window.next_frame.tab_stops.insert(focus_handle);
2430                                        }
2431                                        if let Some(hitbox) = hitbox {
2432                                            #[cfg(debug_assertions)]
2433                                            self.paint_debug_info(
2434                                                global_id, hitbox, &style, window, cx,
2435                                            );
2436
2437                                            if let Some(drag) = cx.active_drag.as_ref() {
2438                                                if let Some(mouse_cursor) = drag.cursor_style {
2439                                                    window.set_window_cursor_style(mouse_cursor);
2440                                                }
2441                                            } else {
2442                                                if let Some(mouse_cursor) = style.mouse_cursor {
2443                                                    window.set_cursor_style(mouse_cursor, hitbox);
2444                                                }
2445                                            }
2446
2447                                            if let Some(group) = self.group.clone() {
2448                                                GroupHitboxes::push(group, hitbox.id, cx);
2449                                            }
2450
2451                                            if let Some(area) = self.window_control {
2452                                                window.insert_window_control_hitbox(
2453                                                    area,
2454                                                    hitbox.clone(),
2455                                                );
2456                                            }
2457
2458                                            self.paint_mouse_listeners(
2459                                                hitbox,
2460                                                element_state.as_mut(),
2461                                                window,
2462                                                cx,
2463                                            );
2464                                            self.paint_scroll_listener(hitbox, &style, window, cx);
2465                                        }
2466
2467                                        self.paint_keyboard_listeners(window, cx);
2468
2469                                        if window.a11y.is_active() {
2470                                            if let Some(global_id) = global_id {
2471                                                if !self.a11y_action_listeners.is_empty() {
2472                                                    let node_id = global_id.accesskit_node_id();
2473                                                    for (action, listener) in
2474                                                        self.a11y_action_listeners.drain(..)
2475                                                    {
2476                                                        window.on_a11y_action(
2477                                                            node_id, action, listener,
2478                                                        );
2479                                                    }
2480                                                }
2481                                            }
2482                                        }
2483
2484                                        f(&style, window, cx);
2485
2486                                        if let Some(_hitbox) = hitbox {
2487                                            #[cfg(any(feature = "inspector", debug_assertions))]
2488                                            window.insert_inspector_hitbox(
2489                                                _hitbox.id,
2490                                                _inspector_id,
2491                                                cx,
2492                                            );
2493
2494                                            if let Some(group) = self.group.as_ref() {
2495                                                GroupHitboxes::pop(group, cx);
2496                                            }
2497                                        }
2498                                    })
2499                                },
2500                            );
2501                        });
2502                    });
2503                });
2504
2505                ((), element_state)
2506            },
2507        );
2508    }
2509
2510    #[cfg(debug_assertions)]
2511    fn paint_debug_info(
2512        &self,
2513        global_id: Option<&GlobalElementId>,
2514        hitbox: &Hitbox,
2515        style: &Style,
2516        window: &mut Window,
2517        cx: &mut App,
2518    ) {
2519        use crate::{BorderStyle, TextAlign};
2520
2521        if let Some(global_id) = global_id
2522            && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2523            && hitbox.is_hovered(window)
2524        {
2525            const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2526            let element_id = format!("{global_id:?}");
2527            let str_len = element_id.len();
2528
2529            let render_debug_text = |window: &mut Window| {
2530                if let Some(text) = window
2531                    .text_system()
2532                    .shape_text(
2533                        element_id.into(),
2534                        FONT_SIZE,
2535                        &[window.text_style().to_run(str_len)],
2536                        None,
2537                        None,
2538                    )
2539                    .ok()
2540                    .and_then(|mut text| text.pop())
2541                {
2542                    text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2543                        .ok();
2544
2545                    let text_bounds = crate::Bounds {
2546                        origin: hitbox.origin,
2547                        size: text.size(FONT_SIZE),
2548                    };
2549                    if let Some(source_location) = self.source_location
2550                        && text_bounds.contains(&window.mouse_position())
2551                        && window.modifiers().secondary()
2552                    {
2553                        let secondary_held = window.modifiers().secondary();
2554                        window.on_key_event({
2555                            move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2556                                if e.modifiers.secondary() != secondary_held
2557                                    && text_bounds.contains(&window.mouse_position())
2558                                {
2559                                    window.refresh();
2560                                }
2561                            }
2562                        });
2563
2564                        let was_hovered = hitbox.is_hovered(window);
2565                        let current_view = window.current_view();
2566                        window.on_mouse_event({
2567                            let hitbox = hitbox.clone();
2568                            move |_: &MouseMoveEvent, phase, window, cx| {
2569                                if phase == DispatchPhase::Capture {
2570                                    let hovered = hitbox.is_hovered(window);
2571                                    if hovered != was_hovered {
2572                                        cx.notify(current_view)
2573                                    }
2574                                }
2575                            }
2576                        });
2577
2578                        window.on_mouse_event({
2579                            let hitbox = hitbox.clone();
2580                            move |e: &crate::MouseDownEvent, phase, window, cx| {
2581                                if text_bounds.contains(&e.position)
2582                                    && phase.capture()
2583                                    && hitbox.is_hovered(window)
2584                                {
2585                                    cx.stop_propagation();
2586                                    let Ok(dir) = std::env::current_dir() else {
2587                                        return;
2588                                    };
2589
2590                                    eprintln!(
2591                                        "This element was created at:\n{}:{}:{}",
2592                                        dir.join(source_location.file()).to_string_lossy(),
2593                                        source_location.line(),
2594                                        source_location.column()
2595                                    );
2596                                }
2597                            }
2598                        });
2599                        window.paint_quad(crate::outline(
2600                            crate::Bounds {
2601                                origin: hitbox.origin
2602                                    + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2603                                size: crate::Size {
2604                                    width: text_bounds.size.width,
2605                                    height: crate::px(1.),
2606                                },
2607                            },
2608                            crate::red(),
2609                            BorderStyle::default(),
2610                        ))
2611                    }
2612                }
2613            };
2614
2615            window.with_text_style(
2616                Some(crate::TextStyleRefinement {
2617                    color: Some(crate::red()),
2618                    line_height: Some(FONT_SIZE.into()),
2619                    background_color: Some(crate::white()),
2620                    ..Default::default()
2621                }),
2622                render_debug_text,
2623            )
2624        }
2625    }
2626
2627    fn paint_mouse_listeners(
2628        &mut self,
2629        hitbox: &Hitbox,
2630        element_state: Option<&mut InteractiveElementState>,
2631        window: &mut Window,
2632        cx: &mut App,
2633    ) {
2634        let is_focused = self
2635            .tracked_focus_handle
2636            .as_ref()
2637            .map(|handle| handle.is_focused(window))
2638            .unwrap_or(false);
2639
2640        // If this element can be focused, register a mouse down listener
2641        // that will automatically transfer focus when hitting the element.
2642        // This behavior can be suppressed by using `cx.prevent_default()`.
2643        if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2644            let hitbox = hitbox.clone();
2645            window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2646                if phase == DispatchPhase::Bubble
2647                    && hitbox.is_hovered(window)
2648                    && !window.default_prevented()
2649                {
2650                    window.focus(&focus_handle, cx);
2651                    // If there is a parent that is also focusable, prevent it
2652                    // from transferring focus because we already did so.
2653                    window.prevent_default();
2654                }
2655            });
2656        }
2657
2658        for listener in self.mouse_down_listeners.drain(..) {
2659            let hitbox = hitbox.clone();
2660            window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2661                listener(event, phase, &hitbox, window, cx);
2662            })
2663        }
2664
2665        for listener in self.mouse_up_listeners.drain(..) {
2666            let hitbox = hitbox.clone();
2667            window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2668                listener(event, phase, &hitbox, window, cx);
2669            })
2670        }
2671
2672        for listener in self.mouse_pressure_listeners.drain(..) {
2673            let hitbox = hitbox.clone();
2674            window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2675                listener(event, phase, &hitbox, window, cx);
2676            })
2677        }
2678
2679        for listener in self.mouse_move_listeners.drain(..) {
2680            let hitbox = hitbox.clone();
2681            window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2682                listener(event, phase, &hitbox, window, cx);
2683            })
2684        }
2685
2686        for listener in self.mouse_exit_listeners.drain(..) {
2687            let hitbox = hitbox.clone();
2688            window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2689                listener(event, phase, &hitbox, window, cx);
2690            })
2691        }
2692
2693        for listener in self.scroll_wheel_listeners.drain(..) {
2694            let hitbox = hitbox.clone();
2695            window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2696                listener(event, phase, &hitbox, window, cx);
2697            })
2698        }
2699
2700        for listener in self.pinch_listeners.drain(..) {
2701            let hitbox = hitbox.clone();
2702            window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2703                listener(event, phase, &hitbox, window, cx);
2704            })
2705        }
2706
2707        if self.hover_style.is_some()
2708            || self.base_style.mouse_cursor.is_some()
2709            || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2710        {
2711            let hitbox = hitbox.clone();
2712            let hover_state = self.hover_style.as_ref().and_then(|_| {
2713                element_state
2714                    .as_ref()
2715                    .and_then(|state| state.hover_state.as_ref())
2716                    .cloned()
2717            });
2718            let current_view = window.current_view();
2719
2720            window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2721                let hovered = hitbox.is_hovered(window);
2722                let was_hovered = hover_state
2723                    .as_ref()
2724                    .is_some_and(|state| state.borrow().element);
2725                if phase == DispatchPhase::Capture && hovered != was_hovered {
2726                    if let Some(hover_state) = &hover_state {
2727                        hover_state.borrow_mut().element = hovered;
2728                        cx.notify(current_view);
2729                    }
2730                }
2731            });
2732        }
2733
2734        if let Some(group_hover) = self.group_hover_style.as_ref() {
2735            if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2736                let hover_state = element_state
2737                    .as_ref()
2738                    .and_then(|element| element.hover_state.as_ref())
2739                    .cloned();
2740                let current_view = window.current_view();
2741
2742                window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2743                    let group_hovered = group_hitbox_id.is_hovered(window);
2744                    let was_group_hovered = hover_state
2745                        .as_ref()
2746                        .is_some_and(|state| state.borrow().group);
2747                    if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2748                        if let Some(hover_state) = &hover_state {
2749                            hover_state.borrow_mut().group = group_hovered;
2750                            cx.notify(current_view);
2751                        }
2752                    }
2753                });
2754            }
2755        }
2756
2757        let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2758
2759        let mut drag_listener = mem::take(&mut self.drag_listener);
2760        let drop_listeners = mem::take(&mut self.drop_listeners);
2761        let click_listeners = mem::take(&mut self.click_listeners);
2762        let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2763        let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2764
2765        if !drop_listeners.is_empty() {
2766            let hitbox = hitbox.clone();
2767            window.on_mouse_event({
2768                move |_: &MouseUpEvent, phase, window, cx| {
2769                    if let Some(drag) = &cx.active_drag
2770                        && phase == DispatchPhase::Bubble
2771                        && hitbox.is_hovered(window)
2772                    {
2773                        let drag_state_type = drag.value.as_ref().type_id();
2774                        for (drop_state_type, listener) in &drop_listeners {
2775                            if *drop_state_type == drag_state_type {
2776                                let drag = cx
2777                                    .active_drag
2778                                    .take()
2779                                    .expect("checked for type drag state type above");
2780
2781                                let mut can_drop = true;
2782                                if let Some(predicate) = &can_drop_predicate {
2783                                    can_drop = predicate(drag.value.as_ref(), window, cx);
2784                                }
2785
2786                                if can_drop {
2787                                    listener(drag.value.as_ref(), window, cx);
2788                                    window.refresh();
2789                                    cx.stop_propagation();
2790                                }
2791                            }
2792                        }
2793                    }
2794                }
2795            });
2796        }
2797
2798        if let Some(element_state) = element_state {
2799            if !click_listeners.is_empty()
2800                || !aux_click_listeners.is_empty()
2801                || drag_listener.is_some()
2802            {
2803                let pending_mouse_down = element_state
2804                    .pending_mouse_down
2805                    .get_or_insert_with(Default::default)
2806                    .clone();
2807
2808                let pending_keyboard_down = element_state
2809                    .pending_keyboard_down
2810                    .get_or_insert_with(Default::default)
2811                    .clone();
2812
2813                let clicked_state = element_state
2814                    .clicked_state
2815                    .get_or_insert_with(Default::default)
2816                    .clone();
2817
2818                window.on_mouse_event({
2819                    let pending_mouse_down = pending_mouse_down.clone();
2820                    let hitbox = hitbox.clone();
2821                    let has_aux_click_listeners = !aux_click_listeners.is_empty();
2822                    move |event: &MouseDownEvent, phase, window, _cx| {
2823                        if phase == DispatchPhase::Bubble
2824                            && (event.button == MouseButton::Left || has_aux_click_listeners)
2825                            && hitbox.is_hovered(window)
2826                        {
2827                            *pending_mouse_down.borrow_mut() = Some(event.clone());
2828                            window.refresh();
2829                        }
2830                    }
2831                });
2832
2833                window.on_mouse_event({
2834                    let pending_mouse_down = pending_mouse_down.clone();
2835                    let hitbox = hitbox.clone();
2836                    move |event: &MouseMoveEvent, phase, window, cx| {
2837                        if phase == DispatchPhase::Capture {
2838                            return;
2839                        }
2840
2841                        let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2842                        if let Some(mouse_down) = pending_mouse_down.clone()
2843                            && !cx.has_active_drag()
2844                            && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2845                            && let Some(listener) = drag_listener.take()
2846                            && mouse_down.button == MouseButton::Left
2847                        {
2848                            *clicked_state.borrow_mut() = ElementClickedState::default();
2849                            let cursor_offset = event.position - hitbox.origin;
2850                            let drag = (listener.render)(
2851                                listener.value.as_ref(),
2852                                cursor_offset,
2853                                window,
2854                                cx,
2855                            );
2856                            let external_payload_source =
2857                                listener.external_payload.map(|external_payload| {
2858                                    let value = listener.value.clone();
2859                                    Box::new(move |window: &mut Window, cx: &mut App| {
2860                                        external_payload(value.as_ref(), window, cx)
2861                                    })
2862                                        as ExternalDragPayloadSource
2863                                });
2864                            cx.active_drag = Some(AnyDrag {
2865                                view: drag,
2866                                value: listener.value,
2867                                cursor_offset,
2868                                cursor_style: drag_cursor_style,
2869                                external_payload_source,
2870                            });
2871                            pending_mouse_down.take();
2872                            window.refresh();
2873                            cx.stop_propagation();
2874                        }
2875                    }
2876                });
2877
2878                if is_focused {
2879                    // Record the focus generation at which an enter/space key
2880                    // down event happened on this element. The next key up
2881                    // event will be mapped to a click event if both of the
2882                    // following are true:
2883                    // - no other key events happen in between
2884                    // - the focus generation is the same (implying focus did not move)
2885                    //
2886                    // This design avoids an ABA problem that happens if you
2887                    // store the focus handle that registered the keypress.
2888                    window.on_key_event({
2889                        let pending_keyboard_down = pending_keyboard_down.clone();
2890                        move |event: &KeyDownEvent, phase, window, _cx| {
2891                            if phase.bubble() && !window.default_prevented() {
2892                                let stroke = &event.keystroke;
2893                                let is_activation_key = (stroke.key.eq("enter")
2894                                    || stroke.key.eq("space"))
2895                                    && !stroke.modifiers.modified();
2896                                *pending_keyboard_down.borrow_mut() =
2897                                    is_activation_key.then_some(window.focus_generation);
2898                            }
2899                        }
2900                    });
2901
2902                    // Press enter, space to trigger click, when the element is focused.
2903                    window.on_key_event({
2904                        let click_listeners = click_listeners.clone();
2905                        let hitbox = hitbox.clone();
2906                        move |event: &KeyUpEvent, phase, window, cx| {
2907                            if phase.bubble() && !window.default_prevented() {
2908                                let stroke = &event.keystroke;
2909                                let keyboard_button = if stroke.key.eq("enter") {
2910                                    Some(KeyboardButton::Enter)
2911                                } else if stroke.key.eq("space") {
2912                                    Some(KeyboardButton::Space)
2913                                } else {
2914                                    None
2915                                };
2916
2917                                if let Some(button) = keyboard_button
2918                                    && !stroke.modifiers.modified()
2919                                {
2920                                    let pending =
2921                                        std::mem::take(&mut *pending_keyboard_down.borrow_mut());
2922                                    if pending != Some(window.focus_generation) {
2923                                        return;
2924                                    }
2925
2926                                    let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2927                                        button,
2928                                        bounds: hitbox.bounds,
2929                                    });
2930
2931                                    for listener in &click_listeners {
2932                                        listener(&click_event, window, cx);
2933                                    }
2934                                } else {
2935                                    // Releasing any other key mid-press means
2936                                    // this isn't a clean activation, so cancel
2937                                    // the pending keydown.
2938                                    *pending_keyboard_down.borrow_mut() = None;
2939                                }
2940                            }
2941                        }
2942                    });
2943                }
2944
2945                window.on_mouse_event({
2946                    let mut captured_mouse_down = None;
2947                    let hitbox = hitbox.clone();
2948                    move |event: &MouseUpEvent, phase, window, cx| match phase {
2949                        // Clear the pending mouse down during the capture phase,
2950                        // so that it happens even if another event handler stops
2951                        // propagation.
2952                        DispatchPhase::Capture => {
2953                            let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2954                            if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2955                                captured_mouse_down = pending_mouse_down.take();
2956                                window.refresh();
2957                            } else if pending_mouse_down.is_some() {
2958                                // Clear the pending mouse down event (without firing click handlers)
2959                                // if the hitbox is not being hovered.
2960                                // This avoids dragging elements that changed their position
2961                                // immediately after being clicked.
2962                                // See https://github.com/zed-industries/zed/issues/24600 for more details
2963                                pending_mouse_down.take();
2964                                window.refresh();
2965                            }
2966                        }
2967                        // Fire click handlers during the bubble phase.
2968                        DispatchPhase::Bubble => {
2969                            if let Some(mouse_down) = captured_mouse_down.take() {
2970                                let btn = mouse_down.button;
2971
2972                                let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2973                                    down: mouse_down,
2974                                    up: event.clone(),
2975                                });
2976
2977                                match btn {
2978                                    MouseButton::Left => {
2979                                        for listener in &click_listeners {
2980                                            listener(&mouse_click, window, cx);
2981                                        }
2982                                    }
2983                                    _ => {
2984                                        for listener in &aux_click_listeners {
2985                                            listener(&mouse_click, window, cx);
2986                                        }
2987                                    }
2988                                }
2989                            }
2990                        }
2991                    }
2992                });
2993            }
2994
2995            if let Some(hover_listener) = self.hover_listener.take() {
2996                let was_hovered = element_state
2997                    .hover_listener_state
2998                    .get_or_insert_with(Default::default)
2999                    .clone();
3000                let has_mouse_down = element_state
3001                    .pending_mouse_down
3002                    .get_or_insert_with(Default::default)
3003                    .clone();
3004                let hover_listener = Rc::new(hover_listener);
3005                let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3006                    let mut was_hovered = was_hovered.borrow_mut();
3007                    if is_hovered != *was_hovered {
3008                        *was_hovered = is_hovered;
3009                        drop(was_hovered);
3010                        hover_listener(&is_hovered, window, cx);
3011                    }
3012                };
3013
3014                window.on_mouse_event({
3015                    let update_hover = update_hover.clone();
3016                    let hitbox = hitbox.clone();
3017                    move |_: &MouseMoveEvent, phase, window, cx| {
3018                        if phase == DispatchPhase::Bubble {
3019                            let is_hovered = has_mouse_down.borrow().is_none()
3020                                && !cx.has_active_drag()
3021                                && hitbox.is_hovered(window);
3022                            update_hover(is_hovered, window, cx);
3023                        }
3024                    }
3025                });
3026
3027                // The pointer can leave the window without a final MouseMove, so also
3028                // clear hover on MouseExited.
3029                window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3030                    if phase == DispatchPhase::Bubble {
3031                        update_hover(false, window, cx);
3032                    }
3033                });
3034            }
3035
3036            if let Some(tooltip_builder) = self.tooltip_builder.take() {
3037                let active_tooltip = element_state
3038                    .active_tooltip
3039                    .get_or_insert_with(Default::default)
3040                    .clone();
3041                let pending_mouse_down = element_state
3042                    .pending_mouse_down
3043                    .get_or_insert_with(Default::default)
3044                    .clone();
3045
3046                let tooltip_is_hoverable = tooltip_builder.hoverable;
3047                let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3048                    Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3049                });
3050                // Use bounds instead of testing hitbox since this is called during prepaint.
3051                let check_is_hovered_during_prepaint = Rc::new({
3052                    let pending_mouse_down = pending_mouse_down.clone();
3053                    let source_bounds = hitbox.bounds;
3054                    move |window: &Window| {
3055                        !window.last_input_was_keyboard()
3056                            && pending_mouse_down.borrow().is_none()
3057                            && source_bounds.contains(&window.mouse_position())
3058                    }
3059                });
3060                let check_is_hovered = Rc::new({
3061                    let hitbox = hitbox.clone();
3062                    move |window: &Window| {
3063                        pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3064                    }
3065                });
3066                register_tooltip_mouse_handlers(
3067                    &active_tooltip,
3068                    self.tooltip_id,
3069                    build_tooltip,
3070                    check_is_hovered,
3071                    check_is_hovered_during_prepaint,
3072                    self.tooltip_show_delay,
3073                    window,
3074                );
3075            }
3076
3077            // We unconditionally bind both the mouse up and mouse down active state handlers
3078            // Because we might not get a chance to render a frame before the mouse up event arrives.
3079            let active_state = element_state
3080                .clicked_state
3081                .get_or_insert_with(Default::default)
3082                .clone();
3083
3084            {
3085                let active_state = active_state.clone();
3086                window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3087                    if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3088                        *active_state.borrow_mut() = ElementClickedState::default();
3089                        window.refresh();
3090                    }
3091                });
3092            }
3093
3094            {
3095                let active_group_hitbox = self
3096                    .group_active_style
3097                    .as_ref()
3098                    .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3099                let hitbox = hitbox.clone();
3100                window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3101                    if phase == DispatchPhase::Bubble && !window.default_prevented() {
3102                        let group_hovered = active_group_hitbox
3103                            .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3104                        let element_hovered = hitbox.is_hovered(window);
3105                        if group_hovered || element_hovered {
3106                            *active_state.borrow_mut() = ElementClickedState {
3107                                group: group_hovered,
3108                                element: element_hovered,
3109                            };
3110                            window.refresh();
3111                        }
3112                    }
3113                });
3114            }
3115        }
3116    }
3117
3118    fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3119        let key_down_listeners = mem::take(&mut self.key_down_listeners);
3120        let key_up_listeners = mem::take(&mut self.key_up_listeners);
3121        let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3122        let action_listeners = mem::take(&mut self.action_listeners);
3123        if let Some(context) = self.key_context.clone() {
3124            window.set_key_context(context);
3125        }
3126
3127        for listener in key_down_listeners {
3128            window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3129                listener(event, phase, window, cx);
3130            })
3131        }
3132
3133        for listener in key_up_listeners {
3134            window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3135                listener(event, phase, window, cx);
3136            })
3137        }
3138
3139        for listener in modifiers_changed_listeners {
3140            window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3141                listener(event, window, cx);
3142            })
3143        }
3144
3145        for (action_type, listener) in action_listeners {
3146            window.on_action(action_type, listener)
3147        }
3148    }
3149
3150    fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3151        let group_hitbox = self
3152            .group_hover_style
3153            .as_ref()
3154            .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3155
3156        if let Some(group_hitbox) = group_hitbox {
3157            let was_hovered = group_hitbox.is_hovered(window);
3158            let current_view = window.current_view();
3159            window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3160                let hovered = group_hitbox.is_hovered(window);
3161                if phase == DispatchPhase::Capture && hovered != was_hovered {
3162                    cx.notify(current_view);
3163                }
3164            });
3165        }
3166    }
3167
3168    fn paint_scroll_listener(
3169        &self,
3170        hitbox: &Hitbox,
3171        style: &Style,
3172        window: &mut Window,
3173        _cx: &mut App,
3174    ) {
3175        if let Some(scroll_offset) = self.scroll_offset.clone() {
3176            let ongoing_scroll = self.ongoing_scroll.clone();
3177            let overflow = style.overflow;
3178            let allow_concurrent_scroll = style.allow_concurrent_scroll;
3179            let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3180            let line_height = window.line_height();
3181            let hitbox = hitbox.clone();
3182            let current_view = window.current_view();
3183            window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
3184                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3185                    let mut scroll_offset = scroll_offset.borrow_mut();
3186                    let old_scroll_offset = *scroll_offset;
3187                    let mut delta = event.delta.pixel_delta(line_height);
3188
3189                    if restrict_scroll_to_axis
3190                        && event.delta.precise()
3191                        && let Some(ongoing_scroll) = &ongoing_scroll
3192                    {
3193                        ongoing_scroll
3194                            .borrow_mut()
3195                            .filter(&mut delta, event.touch_phase);
3196                    }
3197
3198                    let mut delta_x = match overflow.x {
3199                        Overflow::Scroll if !delta.x.is_zero() => delta.x,
3200                        Overflow::Scroll
3201                            if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3202                        {
3203                            delta.y
3204                        }
3205                        _ => Pixels::ZERO,
3206                    };
3207                    let mut delta_y = match overflow.y {
3208                        Overflow::Scroll if !delta.y.is_zero() => delta.y,
3209                        Overflow::Scroll
3210                            if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3211                        {
3212                            delta.x
3213                        }
3214                        _ => Pixels::ZERO,
3215                    };
3216                    if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3217                        if delta_x.abs() > delta_y.abs() {
3218                            delta_y = Pixels::ZERO;
3219                        } else {
3220                            delta_x = Pixels::ZERO;
3221                        }
3222                    }
3223                    scroll_offset.y += delta_y;
3224                    scroll_offset.x += delta_x;
3225                    if *scroll_offset != old_scroll_offset {
3226                        cx.notify(current_view);
3227                    }
3228                }
3229            });
3230        }
3231    }
3232
3233    /// Compute the visual style for this element, based on the current bounds and the element's state.
3234    pub fn compute_style(
3235        &self,
3236        global_id: Option<&GlobalElementId>,
3237        hitbox: Option<&Hitbox>,
3238        window: &mut Window,
3239        cx: &mut App,
3240    ) -> Style {
3241        window.with_optional_element_state(global_id, |element_state, window| {
3242            let mut element_state =
3243                element_state.map(|element_state| element_state.unwrap_or_default());
3244            let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3245            (style, element_state)
3246        })
3247    }
3248
3249    /// Called from internal methods that have already called with_element_state.
3250    fn compute_style_internal(
3251        &self,
3252        hitbox: Option<&Hitbox>,
3253        element_state: Option<&mut InteractiveElementState>,
3254        window: &mut Window,
3255        cx: &mut App,
3256    ) -> Style {
3257        let mut style = Style::default();
3258        style.refine(&self.base_style);
3259
3260        if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3261            if let Some(in_focus_style) = self.in_focus_style.as_ref()
3262                && focus_handle.within_focused(window, cx)
3263            {
3264                style.refine(in_focus_style);
3265            }
3266
3267            if let Some(focus_style) = self.focus_style.as_ref()
3268                && focus_handle.is_focused(window)
3269            {
3270                style.refine(focus_style);
3271            }
3272
3273            if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3274                && focus_handle.is_focused(window)
3275                && window.last_input_was_keyboard()
3276            {
3277                style.refine(focus_visible_style);
3278            }
3279        }
3280
3281        if !cx.has_active_drag() {
3282            if let Some(group_hover) = self.group_hover_style.as_ref() {
3283                let is_group_hovered =
3284                    if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3285                        group_hitbox_id.is_hovered(window)
3286                    } else if let Some(element_state) = element_state.as_ref() {
3287                        element_state
3288                            .hover_state
3289                            .as_ref()
3290                            .map(|state| state.borrow().group)
3291                            .unwrap_or(false)
3292                    } else {
3293                        false
3294                    };
3295
3296                if is_group_hovered {
3297                    style.refine(&group_hover.style);
3298                }
3299            }
3300
3301            if let Some(hover_style) = self.hover_style.as_ref() {
3302                let is_hovered = if let Some(hitbox) = hitbox {
3303                    hitbox.is_hovered(window)
3304                } else if let Some(element_state) = element_state.as_ref() {
3305                    element_state
3306                        .hover_state
3307                        .as_ref()
3308                        .map(|state| state.borrow().element)
3309                        .unwrap_or(false)
3310                } else {
3311                    false
3312                };
3313
3314                if is_hovered {
3315                    style.refine(hover_style);
3316                }
3317            }
3318        }
3319
3320        if let Some(hitbox) = hitbox {
3321            if let Some(drag) = cx.active_drag.take() {
3322                let mut can_drop = true;
3323                if let Some(can_drop_predicate) = &self.can_drop_predicate {
3324                    can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3325                }
3326
3327                if can_drop {
3328                    for (state_type, group_drag_style) in &self.group_drag_over_styles {
3329                        if let Some(group_hitbox_id) =
3330                            GroupHitboxes::get(&group_drag_style.group, cx)
3331                            && *state_type == drag.value.as_ref().type_id()
3332                            && group_hitbox_id.is_hovered(window)
3333                        {
3334                            style.refine(&group_drag_style.style);
3335                        }
3336                    }
3337
3338                    for (state_type, build_drag_over_style) in &self.drag_over_styles {
3339                        if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3340                        {
3341                            style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3342                        }
3343                    }
3344                }
3345
3346                style.mouse_cursor = drag.cursor_style;
3347                cx.active_drag = Some(drag);
3348            }
3349        }
3350
3351        if let Some(element_state) = element_state {
3352            let clicked_state = element_state
3353                .clicked_state
3354                .get_or_insert_with(Default::default)
3355                .borrow();
3356            if clicked_state.group
3357                && let Some(group) = self.group_active_style.as_ref()
3358            {
3359                style.refine(&group.style)
3360            }
3361
3362            if let Some(active_style) = self.active_style.as_ref()
3363                && clicked_state.element
3364            {
3365                style.refine(active_style)
3366            }
3367        }
3368
3369        style
3370    }
3371
3372    pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3373        if let Some(label) = &self.aria.label {
3374            node.set_label(label.to_string());
3375        }
3376        if let Some(description) = &self.aria.description {
3377            node.set_description(description.to_string());
3378        }
3379        if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3380            node.set_keyboard_shortcut(keyshortcuts.to_string());
3381        }
3382        if let Some(selected) = self.aria.selected {
3383            node.set_selected(selected);
3384        }
3385        if let Some(expanded) = self.aria.expanded {
3386            node.set_expanded(expanded);
3387        }
3388        if let Some(toggled) = self.aria.toggled {
3389            node.set_toggled(toggled);
3390        }
3391        if let Some(value) = self.aria.numeric_value {
3392            node.set_numeric_value(value);
3393        }
3394        if let Some(value) = self.aria.min_numeric_value {
3395            node.set_min_numeric_value(value);
3396        }
3397        if let Some(value) = self.aria.max_numeric_value {
3398            node.set_max_numeric_value(value);
3399        }
3400        if let Some(step) = self.aria.numeric_value_step {
3401            node.set_numeric_value_step(step);
3402        }
3403        if let Some(value) = &self.aria.value {
3404            node.set_value(value.to_string());
3405        }
3406        if let Some(placeholder) = &self.aria.placeholder {
3407            node.set_placeholder(placeholder.to_string());
3408        }
3409        if let Some(orientation) = self.aria.orientation {
3410            node.set_orientation(orientation);
3411        }
3412        if let Some(level) = self.aria.level {
3413            node.set_level(level);
3414        }
3415        if let Some(position) = self.aria.position_in_set {
3416            node.set_position_in_set(position);
3417        }
3418        if let Some(size) = self.aria.size_of_set {
3419            node.set_size_of_set(size);
3420        }
3421        if let Some(index) = self.aria.row_index {
3422            node.set_row_index(index);
3423        }
3424        if let Some(index) = self.aria.column_index {
3425            node.set_column_index(index);
3426        }
3427        if let Some(count) = self.aria.row_count {
3428            node.set_row_count(count);
3429        }
3430        if let Some(count) = self.aria.column_count {
3431            node.set_column_count(count);
3432        }
3433        if !self.click_listeners.is_empty() {
3434            node.add_action(accesskit::Action::Click);
3435        }
3436        if self.tracked_focus_handle.is_some() || self.focusable {
3437            node.add_action(accesskit::Action::Focus);
3438        }
3439        for (action, _) in &self.a11y_action_listeners {
3440            node.add_action(*action);
3441        }
3442    }
3443}
3444
3445/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks
3446/// and scroll offsets.
3447#[derive(Default)]
3448pub struct InteractiveElementState {
3449    pub(crate) focus_handle: Option<FocusHandle>,
3450    pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3451    pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3452    pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3453    pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3454    /// Set to the window's [`focus_generation`](crate::Window::focus_generation)
3455    /// when an Enter/Space keydown is received while this element is focused,
3456    /// recording that we are waiting for the matching keyup to fire a keyboard
3457    /// click. On keyup the click only fires if the stored generation still
3458    /// matches the window's current one, i.e. focus never moved during the
3459    /// press (mirroring the browser clearing a control's pressed state on
3460    /// blur). `None` means no activation key is pending.
3461    pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3462    pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3463    ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3464    pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3465}
3466
3467/// Whether or not the element or a group that contains it is clicked by the mouse.
3468#[derive(Copy, Clone, Default, Eq, PartialEq)]
3469pub struct ElementClickedState {
3470    /// True if this element's group has been clicked, false otherwise
3471    pub group: bool,
3472
3473    /// True if this element has been clicked, false otherwise
3474    pub element: bool,
3475}
3476
3477impl ElementClickedState {
3478    fn is_clicked(&self) -> bool {
3479        self.group || self.element
3480    }
3481}
3482
3483/// Whether or not the element or a group that contains it is hovered.
3484#[derive(Copy, Clone, Default, Eq, PartialEq)]
3485pub struct ElementHoverState {
3486    /// True if this element's group is hovered, false otherwise
3487    pub group: bool,
3488
3489    /// True if this element is hovered, false otherwise
3490    pub element: bool,
3491}
3492
3493pub(crate) enum ActiveTooltip {
3494    /// Currently delaying before showing the tooltip.
3495    WaitingForShow { _task: Task<()> },
3496    /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
3497    Visible {
3498        tooltip: AnyTooltip,
3499        is_hoverable: bool,
3500    },
3501    /// Tooltip is visible and hoverable, but the mouse is no longer hovering. Currently delaying
3502    /// before hiding it.
3503    WaitingForHide {
3504        tooltip: AnyTooltip,
3505        _task: Task<()>,
3506    },
3507}
3508
3509pub(crate) fn clear_active_tooltip(
3510    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3511    window: &mut Window,
3512) {
3513    match active_tooltip.borrow_mut().take() {
3514        None => {}
3515        Some(ActiveTooltip::WaitingForShow { .. }) => {}
3516        Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3517        Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3518    }
3519}
3520
3521pub(crate) fn clear_active_tooltip_if_not_hoverable(
3522    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3523    window: &mut Window,
3524) {
3525    let should_clear = match active_tooltip.borrow().as_ref() {
3526        None => false,
3527        Some(ActiveTooltip::WaitingForShow { .. }) => false,
3528        Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3529        Some(ActiveTooltip::WaitingForHide { .. }) => false,
3530    };
3531    if should_clear {
3532        active_tooltip.borrow_mut().take();
3533        window.refresh();
3534    }
3535}
3536
3537pub(crate) fn set_tooltip_on_window(
3538    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3539    window: &mut Window,
3540) -> Option<TooltipId> {
3541    let tooltip = match active_tooltip.borrow().as_ref() {
3542        None => return None,
3543        Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3544        Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3545        Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3546    };
3547    Some(window.set_tooltip(tooltip))
3548}
3549
3550pub(crate) fn register_tooltip_mouse_handlers(
3551    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3552    tooltip_id: Option<TooltipId>,
3553    build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3554    check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3555    check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3556    show_delay: Option<Duration>,
3557    window: &mut Window,
3558) {
3559    let current_view = window.current_view();
3560    let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3561
3562    window.on_mouse_event({
3563        let active_tooltip = active_tooltip.clone();
3564        let build_tooltip = build_tooltip.clone();
3565        let check_is_hovered = check_is_hovered.clone();
3566        move |_: &MouseMoveEvent, phase, window, cx| {
3567            handle_tooltip_mouse_move(
3568                &active_tooltip,
3569                &build_tooltip,
3570                &check_is_hovered,
3571                &check_is_hovered_during_prepaint,
3572                tooltip_id,
3573                current_view,
3574                phase,
3575                show_delay,
3576                window,
3577                cx,
3578            )
3579        }
3580    });
3581
3582    window.on_mouse_event({
3583        let active_tooltip = active_tooltip.clone();
3584        move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3585            if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3586                clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3587            }
3588        }
3589    });
3590
3591    window.on_mouse_event({
3592        let active_tooltip = active_tooltip.clone();
3593        move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
3594            if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3595                clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3596            }
3597        }
3598    });
3599}
3600
3601/// Handles displaying tooltips when an element is hovered.
3602///
3603/// The mouse hovering logic also relies on being called from window prepaint in order to handle the
3604/// case where the element the tooltip is on is not rendered - in that case its mouse listeners are
3605/// also not registered. During window prepaint, the hitbox information is not available, so
3606/// `check_is_hovered_during_prepaint` is used which bases the check off of the absolute bounds of
3607/// the element.
3608///
3609/// TODO: There's a minor bug due to the use of absolute bounds while checking during prepaint - it
3610/// does not know if the hitbox is occluded. In the case where a tooltip gets displayed and then
3611/// gets occluded after display, it will stick around until the mouse exits the hover bounds.
3612fn handle_tooltip_mouse_move(
3613    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3614    build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3615    check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3616    check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3617    tooltip_id: Option<TooltipId>,
3618    current_view: EntityId,
3619    phase: DispatchPhase,
3620    show_delay: Duration,
3621    window: &mut Window,
3622    cx: &mut App,
3623) {
3624    // Separates logic for what mutation should occur from applying it, to avoid overlapping
3625    // RefCell borrows.
3626    enum Action {
3627        None,
3628        CancelShow,
3629        ScheduleShow,
3630        CheckVisible,
3631    }
3632
3633    let action = match active_tooltip.borrow().as_ref() {
3634        None => {
3635            let is_hovered = check_is_hovered(window);
3636            if is_hovered && phase.bubble() {
3637                Action::ScheduleShow
3638            } else {
3639                Action::None
3640            }
3641        }
3642        Some(ActiveTooltip::WaitingForShow { .. }) => {
3643            let is_hovered = check_is_hovered(window);
3644            if is_hovered {
3645                Action::None
3646            } else {
3647                Action::CancelShow
3648            }
3649        }
3650        Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3651            if phase.capture()
3652                && !check_is_hovered(window)
3653                && (!*is_hoverable
3654                    || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3655            {
3656                Action::CheckVisible
3657            } else {
3658                Action::None
3659            }
3660        }
3661        Some(ActiveTooltip::WaitingForHide { .. }) => {
3662            if phase.capture()
3663                && (check_is_hovered(window)
3664                    || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3665            {
3666                Action::CheckVisible
3667            } else {
3668                Action::None
3669            }
3670        }
3671    };
3672
3673    match action {
3674        Action::None => {}
3675        Action::CancelShow => {
3676            // Cancel waiting to show tooltip when it is no longer hovered.
3677            active_tooltip.borrow_mut().take();
3678        }
3679        Action::ScheduleShow => {
3680            let delayed_show_task = window.spawn(cx, {
3681                let weak_active_tooltip = Rc::downgrade(active_tooltip);
3682                let build_tooltip = build_tooltip.clone();
3683                let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3684                async move |cx| {
3685                    cx.background_executor().timer(show_delay).await;
3686                    let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3687                        return;
3688                    };
3689                    cx.update(|window, cx| {
3690                        let new_tooltip =
3691                            build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3692                                let weak_active_tooltip = Rc::downgrade(&active_tooltip);
3693                                ActiveTooltip::Visible {
3694                                    tooltip: AnyTooltip {
3695                                        view,
3696                                        mouse_position: window.mouse_position(),
3697                                        check_visible_and_update: Rc::new(
3698                                            move |tooltip_bounds, window, cx| {
3699                                                let Some(active_tooltip) =
3700                                                    weak_active_tooltip.upgrade()
3701                                                else {
3702                                                    return false;
3703                                                };
3704                                                handle_tooltip_check_visible_and_update(
3705                                                    &active_tooltip,
3706                                                    tooltip_is_hoverable,
3707                                                    &check_is_hovered_during_prepaint,
3708                                                    tooltip_bounds,
3709                                                    window,
3710                                                    cx,
3711                                                )
3712                                            },
3713                                        ),
3714                                    },
3715                                    is_hoverable: tooltip_is_hoverable,
3716                                }
3717                            });
3718                        *active_tooltip.borrow_mut() = new_tooltip;
3719                        window.refresh();
3720                    })
3721                    .ok();
3722                }
3723            });
3724            active_tooltip
3725                .borrow_mut()
3726                .replace(ActiveTooltip::WaitingForShow {
3727                    _task: delayed_show_task,
3728                });
3729        }
3730        Action::CheckVisible => cx.notify(current_view),
3731    }
3732}
3733
3734/// Returns a callback which will be called by window prepaint to update tooltip visibility. The
3735/// purpose of doing this logic here instead of the mouse move handler is that the mouse move
3736/// handler won't get called when the element is not painted (e.g. via use of `visible_on_hover`).
3737fn handle_tooltip_check_visible_and_update(
3738    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3739    tooltip_is_hoverable: bool,
3740    check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3741    tooltip_bounds: Bounds<Pixels>,
3742    window: &mut Window,
3743    cx: &mut App,
3744) -> bool {
3745    // Separates logic for what mutation should occur from applying it, to avoid overlapping RefCell
3746    // borrows.
3747    enum Action {
3748        None,
3749        Hide,
3750        ScheduleHide(AnyTooltip),
3751        CancelHide(AnyTooltip),
3752    }
3753
3754    let is_hovered = check_is_hovered(window)
3755        || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
3756    let action = match active_tooltip.borrow().as_ref() {
3757        Some(ActiveTooltip::Visible { tooltip, .. }) => {
3758            if is_hovered {
3759                Action::None
3760            } else {
3761                if tooltip_is_hoverable {
3762                    Action::ScheduleHide(tooltip.clone())
3763                } else {
3764                    Action::Hide
3765                }
3766            }
3767        }
3768        Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
3769            if is_hovered {
3770                Action::CancelHide(tooltip.clone())
3771            } else {
3772                Action::None
3773            }
3774        }
3775        None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
3776    };
3777
3778    match action {
3779        Action::None => {}
3780        Action::Hide => clear_active_tooltip(active_tooltip, window),
3781        Action::ScheduleHide(tooltip) => {
3782            let delayed_hide_task = window.spawn(cx, {
3783                let weak_active_tooltip = Rc::downgrade(active_tooltip);
3784                async move |cx| {
3785                    cx.background_executor()
3786                        .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
3787                        .await;
3788                    let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3789                        return;
3790                    };
3791                    if active_tooltip.borrow_mut().take().is_some() {
3792                        cx.update(|window, _cx| window.refresh()).ok();
3793                    }
3794                }
3795            });
3796            active_tooltip
3797                .borrow_mut()
3798                .replace(ActiveTooltip::WaitingForHide {
3799                    tooltip,
3800                    _task: delayed_hide_task,
3801                });
3802        }
3803        Action::CancelHide(tooltip) => {
3804            // Cancel waiting to hide tooltip when it becomes hovered.
3805            active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
3806                tooltip,
3807                is_hoverable: true,
3808            });
3809        }
3810    }
3811
3812    active_tooltip.borrow().is_some()
3813}
3814
3815#[derive(Default)]
3816pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
3817
3818impl Global for GroupHitboxes {}
3819
3820impl GroupHitboxes {
3821    pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
3822        cx.default_global::<Self>()
3823            .0
3824            .get(name)
3825            .and_then(|bounds_stack| bounds_stack.last())
3826            .cloned()
3827    }
3828
3829    pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
3830        cx.default_global::<Self>()
3831            .0
3832            .entry(name)
3833            .or_default()
3834            .push(hitbox_id);
3835    }
3836
3837    pub fn pop(name: &SharedString, cx: &mut App) {
3838        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
3839    }
3840}
3841
3842/// A wrapper around an element that can store state, produced after assigning an ElementId.
3843pub struct Stateful<E> {
3844    pub(crate) element: E,
3845}
3846
3847impl<E> Styled for Stateful<E>
3848where
3849    E: Styled,
3850{
3851    fn style(&mut self) -> &mut StyleRefinement {
3852        self.element.style()
3853    }
3854}
3855
3856impl<E> StatefulInteractiveElement for Stateful<E>
3857where
3858    E: Element,
3859    Self: InteractiveElement,
3860{
3861}
3862
3863impl<E> InteractiveElement for Stateful<E>
3864where
3865    E: InteractiveElement,
3866{
3867    fn interactivity(&mut self) -> &mut Interactivity {
3868        self.element.interactivity()
3869    }
3870}
3871
3872impl<E> Element for Stateful<E>
3873where
3874    E: Element,
3875{
3876    type RequestLayoutState = E::RequestLayoutState;
3877    type PrepaintState = E::PrepaintState;
3878
3879    fn id(&self) -> Option<ElementId> {
3880        self.element.id()
3881    }
3882
3883    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3884        self.element.source_location()
3885    }
3886
3887    fn a11y_role(&self) -> Option<accesskit::Role> {
3888        self.element.a11y_role()
3889    }
3890
3891    fn write_a11y_info(&self, node: &mut accesskit::Node) {
3892        self.element.write_a11y_info(node);
3893    }
3894
3895    fn a11y_synthetic_children(
3896        &mut self,
3897        prepaint: &mut Self::PrepaintState,
3898        builder: &mut crate::A11ySubtreeBuilder,
3899    ) {
3900        self.element.a11y_synthetic_children(prepaint, builder);
3901    }
3902
3903    fn request_layout(
3904        &mut self,
3905        id: Option<&GlobalElementId>,
3906        inspector_id: Option<&InspectorElementId>,
3907        window: &mut Window,
3908        cx: &mut App,
3909    ) -> (LayoutId, Self::RequestLayoutState) {
3910        self.element.request_layout(id, inspector_id, window, cx)
3911    }
3912
3913    fn prepaint(
3914        &mut self,
3915        id: Option<&GlobalElementId>,
3916        inspector_id: Option<&InspectorElementId>,
3917        bounds: Bounds<Pixels>,
3918        state: &mut Self::RequestLayoutState,
3919        window: &mut Window,
3920        cx: &mut App,
3921    ) -> E::PrepaintState {
3922        self.element
3923            .prepaint(id, inspector_id, bounds, state, window, cx)
3924    }
3925
3926    fn paint(
3927        &mut self,
3928        id: Option<&GlobalElementId>,
3929        inspector_id: Option<&InspectorElementId>,
3930        bounds: Bounds<Pixels>,
3931        request_layout: &mut Self::RequestLayoutState,
3932        prepaint: &mut Self::PrepaintState,
3933        window: &mut Window,
3934        cx: &mut App,
3935    ) {
3936        self.element.paint(
3937            id,
3938            inspector_id,
3939            bounds,
3940            request_layout,
3941            prepaint,
3942            window,
3943            cx,
3944        );
3945    }
3946}
3947
3948impl<E> IntoElement for Stateful<E>
3949where
3950    E: Element,
3951{
3952    type Element = Self;
3953
3954    fn into_element(self) -> Self::Element {
3955        self
3956    }
3957}
3958
3959impl<E> ParentElement for Stateful<E>
3960where
3961    E: ParentElement,
3962{
3963    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
3964        self.element.extend(elements)
3965    }
3966}
3967
3968/// Represents an element that can be scrolled *to* in its parent element.
3969/// Contrary to [ScrollHandle::scroll_to_active_item], an anchored element does not have to be an immediate child of the parent.
3970#[derive(Clone)]
3971pub struct ScrollAnchor {
3972    handle: ScrollHandle,
3973    last_origin: Rc<RefCell<Point<Pixels>>>,
3974}
3975
3976impl ScrollAnchor {
3977    /// Creates a [ScrollAnchor] associated with a given [ScrollHandle].
3978    pub fn for_handle(handle: ScrollHandle) -> Self {
3979        Self {
3980            handle,
3981            last_origin: Default::default(),
3982        }
3983    }
3984    /// Request scroll to this item on the next frame.
3985    pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
3986        let this = self.clone();
3987
3988        window.on_next_frame(move |_, _| {
3989            let viewport_bounds = this.handle.bounds();
3990            let self_bounds = *this.last_origin.borrow();
3991            this.handle.set_offset(viewport_bounds.origin - self_bounds);
3992        });
3993    }
3994}
3995
3996#[derive(Default, Debug)]
3997struct ScrollHandleState {
3998    offset: Rc<RefCell<Point<Pixels>>>,
3999    ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4000    bounds: Bounds<Pixels>,
4001    max_offset: Point<Pixels>,
4002    child_bounds: Vec<Bounds<Pixels>>,
4003    scroll_to_bottom: bool,
4004    overflow: Point<Overflow>,
4005    active_item: Option<ScrollActiveItem>,
4006}
4007
4008#[derive(Default, Debug, Clone, Copy)]
4009struct ScrollActiveItem {
4010    index: usize,
4011    strategy: ScrollStrategy,
4012}
4013
4014#[derive(Default, Debug, Clone, Copy)]
4015enum ScrollStrategy {
4016    #[default]
4017    FirstVisible,
4018    Top,
4019}
4020
4021/// A handle to the scrollable aspects of an element.
4022/// Used for accessing scroll state, like the current scroll offset,
4023/// and for mutating the scroll state, like scrolling to a specific child.
4024#[derive(Clone, Debug)]
4025pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4026
4027impl Default for ScrollHandle {
4028    fn default() -> Self {
4029        Self::new()
4030    }
4031}
4032
4033impl ScrollHandle {
4034    /// Construct a new scroll handle.
4035    pub fn new() -> Self {
4036        Self(Rc::default())
4037    }
4038
4039    /// Get the current scroll offset.
4040    pub fn offset(&self) -> Point<Pixels> {
4041        *self.0.borrow().offset.borrow()
4042    }
4043
4044    /// Get the maximum scroll offset.
4045    pub fn max_offset(&self) -> Point<Pixels> {
4046        self.0.borrow().max_offset
4047    }
4048
4049    /// Get the top child that's scrolled into view.
4050    pub fn top_item(&self) -> usize {
4051        let state = self.0.borrow();
4052        let top = state.bounds.top() - state.offset.borrow().y;
4053
4054        match state.child_bounds.binary_search_by(|bounds| {
4055            if top < bounds.top() {
4056                Ordering::Greater
4057            } else if top > bounds.bottom() {
4058                Ordering::Less
4059            } else {
4060                Ordering::Equal
4061            }
4062        }) {
4063            Ok(ix) => ix,
4064            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4065        }
4066    }
4067
4068    /// Get the bottom child that's scrolled into view.
4069    pub fn bottom_item(&self) -> usize {
4070        let state = self.0.borrow();
4071        let bottom = state.bounds.bottom() - state.offset.borrow().y;
4072
4073        match state.child_bounds.binary_search_by(|bounds| {
4074            if bottom < bounds.top() {
4075                Ordering::Greater
4076            } else if bottom > bounds.bottom() {
4077                Ordering::Less
4078            } else {
4079                Ordering::Equal
4080            }
4081        }) {
4082            Ok(ix) => ix,
4083            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4084        }
4085    }
4086
4087    /// Return the bounds into which this child is painted
4088    pub fn bounds(&self) -> Bounds<Pixels> {
4089        self.0.borrow().bounds
4090    }
4091
4092    /// Get the bounds for a specific child.
4093    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4094        self.0.borrow().child_bounds.get(ix).cloned()
4095    }
4096
4097    /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
4098    pub fn scroll_to_item(&self, ix: usize) {
4099        let mut state = self.0.borrow_mut();
4100        state.active_item = Some(ScrollActiveItem {
4101            index: ix,
4102            strategy: ScrollStrategy::default(),
4103        });
4104    }
4105
4106    /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
4107    /// This scrolls the minimal amount to ensure that the child is the first visible element
4108    pub fn scroll_to_top_of_item(&self, ix: usize) {
4109        let mut state = self.0.borrow_mut();
4110        state.active_item = Some(ScrollActiveItem {
4111            index: ix,
4112            strategy: ScrollStrategy::Top,
4113        });
4114    }
4115
4116    /// Scrolls the minimal amount to either ensure that the child is
4117    /// fully visible or the top element of the view depends on the
4118    /// scroll strategy
4119    fn scroll_to_active_item(&self) {
4120        let mut state = self.0.borrow_mut();
4121
4122        let Some(active_item) = state.active_item else {
4123            return;
4124        };
4125
4126        let active_item = match state.child_bounds.get(active_item.index) {
4127            Some(bounds) => {
4128                let mut scroll_offset = state.offset.borrow_mut();
4129
4130                match active_item.strategy {
4131                    ScrollStrategy::FirstVisible => {
4132                        if state.overflow.y == Overflow::Scroll {
4133                            let child_height = bounds.size.height;
4134                            let viewport_height = state.bounds.size.height;
4135                            if child_height > viewport_height {
4136                                scroll_offset.y = state.bounds.top() - bounds.top();
4137                            } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4138                                scroll_offset.y = state.bounds.top() - bounds.top();
4139                            } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4140                                scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4141                            }
4142                        }
4143                    }
4144                    ScrollStrategy::Top => {
4145                        scroll_offset.y = state.bounds.top() - bounds.top();
4146                    }
4147                }
4148
4149                if state.overflow.x == Overflow::Scroll {
4150                    let child_width = bounds.size.width;
4151                    let viewport_width = state.bounds.size.width;
4152                    if child_width > viewport_width {
4153                        scroll_offset.x = state.bounds.left() - bounds.left();
4154                    } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4155                        scroll_offset.x = state.bounds.left() - bounds.left();
4156                    } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4157                        scroll_offset.x = state.bounds.right() - bounds.right();
4158                    }
4159                }
4160                None
4161            }
4162            None => Some(active_item),
4163        };
4164        state.active_item = active_item;
4165    }
4166
4167    /// Scrolls to the bottom.
4168    pub fn scroll_to_bottom(&self) {
4169        let mut state = self.0.borrow_mut();
4170        state.scroll_to_bottom = true;
4171    }
4172
4173    /// Set the offset explicitly. The offset is the distance from the top left of the
4174    /// parent container to the top left of the first child.
4175    /// As you scroll further down the offset becomes more negative.
4176    pub fn set_offset(&self, mut position: Point<Pixels>) {
4177        let state = self.0.borrow();
4178        *state.offset.borrow_mut() = position;
4179    }
4180
4181    /// Get the logical scroll top, based on a child index and a pixel offset.
4182    pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4183        let ix = self.top_item();
4184        let state = self.0.borrow();
4185
4186        if let Some(child_bounds) = state.child_bounds.get(ix) {
4187            (
4188                ix,
4189                child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4190            )
4191        } else {
4192            (ix, px(0.))
4193        }
4194    }
4195
4196    /// Get the logical scroll bottom, based on a child index and a pixel offset.
4197    pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4198        let ix = self.bottom_item();
4199        let state = self.0.borrow();
4200
4201        if let Some(child_bounds) = state.child_bounds.get(ix) {
4202            (
4203                ix,
4204                child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4205            )
4206        } else {
4207            (ix, px(0.))
4208        }
4209    }
4210
4211    /// Get the count of children for scrollable item.
4212    pub fn children_count(&self) -> usize {
4213        self.0.borrow().child_bounds.len()
4214    }
4215}
4216
4217#[cfg(test)]
4218mod tests {
4219    use super::*;
4220    use crate::{
4221        AnyWindowHandle, AppContext as _, Context, InputEvent, Keystroke, MouseMoveEvent,
4222        TestAppContext, canvas, util::FluentBuilder as _,
4223    };
4224    use std::{cell::Cell, rc::Weak};
4225
4226    struct GroupHoverTestView {
4227        render_count: Rc<Cell<usize>>,
4228        anonymous_paint_count: Rc<Cell<usize>>,
4229        stateful_width: Rc<Cell<Pixels>>,
4230    }
4231
4232    impl Render for GroupHoverTestView {
4233        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4234            self.render_count.set(self.render_count.get() + 1);
4235            let anonymous_paint_count = self.anonymous_paint_count.clone();
4236            let stateful_width = self.stateful_width.clone();
4237            div().size_full().child(
4238                div()
4239                    .ml(px(20.))
4240                    .mt(px(20.))
4241                    .size(px(50.))
4242                    .relative()
4243                    .group("hover-group")
4244                    .child(
4245                        div()
4246                            .absolute()
4247                            .size_full()
4248                            .invisible()
4249                            .group_hover("hover-group", |style| style.visible())
4250                            .child(canvas(
4251                                |_, _, _| {},
4252                                move |_, _, _, _| {
4253                                    anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4254                                },
4255                            )),
4256                    )
4257                    .child(
4258                        div()
4259                            .id("stateful-group-hover-target")
4260                            .absolute()
4261                            .top_0()
4262                            .left_0()
4263                            .size(px(10.))
4264                            .group_hover("hover-group", |style| style.size(px(20.)))
4265                            .child(canvas(
4266                                move |bounds, _, _| stateful_width.set(bounds.size.width),
4267                                |_, _, _, _| {},
4268                            )),
4269                    ),
4270            )
4271        }
4272    }
4273
4274    #[gpui::test]
4275    fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4276        let render_count = Rc::new(Cell::new(0));
4277        let anonymous_paint_count = Rc::new(Cell::new(0));
4278        let stateful_width = Rc::new(Cell::new(px(0.)));
4279        let window = cx.add_window({
4280            let render_count = render_count.clone();
4281            let anonymous_paint_count = anonymous_paint_count.clone();
4282            let stateful_width = stateful_width.clone();
4283            move |_, _| GroupHoverTestView {
4284                render_count,
4285                anonymous_paint_count,
4286                stateful_width,
4287            }
4288        });
4289        let window = AnyWindowHandle::from(window);
4290
4291        cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4292            .unwrap();
4293        assert_eq!(anonymous_paint_count.get(), 0);
4294        assert_eq!(stateful_width.get(), px(10.));
4295
4296        let move_mouse = |cx: &mut TestAppContext, position| {
4297            cx.update_window(window, |_, window, cx| {
4298                window.simulate_mouse_move(position, cx)
4299            })
4300            .unwrap();
4301        };
4302
4303        let initial_render_count = render_count.get();
4304        move_mouse(cx, point(px(25.), px(25.)));
4305        assert_eq!(render_count.get(), initial_render_count + 1);
4306        assert_eq!(anonymous_paint_count.get(), 1);
4307        assert_eq!(stateful_width.get(), px(20.));
4308
4309        move_mouse(cx, point(px(30.), px(30.)));
4310        assert_eq!(render_count.get(), initial_render_count + 1);
4311        assert_eq!(anonymous_paint_count.get(), 1);
4312        assert_eq!(stateful_width.get(), px(20.));
4313
4314        move_mouse(cx, point(px(5.), px(5.)));
4315        assert_eq!(render_count.get(), initial_render_count + 2);
4316        assert_eq!(anonymous_paint_count.get(), 1);
4317        assert_eq!(stateful_width.get(), px(10.));
4318
4319        move_mouse(cx, point(px(10.), px(10.)));
4320        assert_eq!(render_count.get(), initial_render_count + 2);
4321        assert_eq!(anonymous_paint_count.get(), 1);
4322        assert_eq!(stateful_width.get(), px(10.));
4323    }
4324
4325    struct TestTooltipView;
4326
4327    impl Render for TestTooltipView {
4328        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4329            div().w(px(20.)).h(px(20.)).child("tooltip")
4330        }
4331    }
4332
4333    type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4334
4335    struct TooltipCaptureElement {
4336        child: AnyElement,
4337        captured_active_tooltip: CapturedActiveTooltip,
4338    }
4339
4340    impl IntoElement for TooltipCaptureElement {
4341        type Element = Self;
4342
4343        fn into_element(self) -> Self::Element {
4344            self
4345        }
4346    }
4347
4348    impl Element for TooltipCaptureElement {
4349        type RequestLayoutState = ();
4350        type PrepaintState = ();
4351
4352        fn id(&self) -> Option<ElementId> {
4353            None
4354        }
4355
4356        fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4357            None
4358        }
4359
4360        fn request_layout(
4361            &mut self,
4362            _id: Option<&GlobalElementId>,
4363            _inspector_id: Option<&InspectorElementId>,
4364            window: &mut Window,
4365            cx: &mut App,
4366        ) -> (LayoutId, Self::RequestLayoutState) {
4367            (self.child.request_layout(window, cx), ())
4368        }
4369
4370        fn prepaint(
4371            &mut self,
4372            _id: Option<&GlobalElementId>,
4373            _inspector_id: Option<&InspectorElementId>,
4374            _bounds: Bounds<Pixels>,
4375            _request_layout: &mut Self::RequestLayoutState,
4376            window: &mut Window,
4377            cx: &mut App,
4378        ) -> Self::PrepaintState {
4379            self.child.prepaint(window, cx);
4380        }
4381
4382        fn paint(
4383            &mut self,
4384            _id: Option<&GlobalElementId>,
4385            _inspector_id: Option<&InspectorElementId>,
4386            _bounds: Bounds<Pixels>,
4387            _request_layout: &mut Self::RequestLayoutState,
4388            _prepaint: &mut Self::PrepaintState,
4389            window: &mut Window,
4390            cx: &mut App,
4391        ) {
4392            self.child.paint(window, cx);
4393            window.with_global_id("target".into(), |global_id, window| {
4394                window.with_element_state::<InteractiveElementState, _>(
4395                    global_id,
4396                    |state, _window| {
4397                        let state = state.unwrap();
4398                        *self.captured_active_tooltip.borrow_mut() =
4399                            state.active_tooltip.as_ref().map(Rc::downgrade);
4400                        ((), state)
4401                    },
4402                )
4403            });
4404        }
4405    }
4406
4407    struct TooltipOwner {
4408        captured_active_tooltip: CapturedActiveTooltip,
4409        show_delay_override: Option<Duration>,
4410    }
4411
4412    impl Render for TooltipOwner {
4413        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4414            TooltipCaptureElement {
4415                child: div()
4416                    .size_full()
4417                    .child(
4418                        div()
4419                            .id("target")
4420                            .w(px(50.))
4421                            .h(px(50.))
4422                            .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4423                            .when_some(self.show_delay_override, |this, delay| {
4424                                this.tooltip_show_delay(delay)
4425                            }),
4426                    )
4427                    .into_any_element(),
4428                captured_active_tooltip: self.captured_active_tooltip.clone(),
4429            }
4430        }
4431    }
4432
4433    #[test]
4434    fn scroll_handle_aligns_wide_children_to_left_edge() {
4435        let handle = ScrollHandle::new();
4436        {
4437            let mut state = handle.0.borrow_mut();
4438            state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4439            state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4440            state.overflow.x = Overflow::Scroll;
4441            state.active_item = Some(ScrollActiveItem {
4442                index: 0,
4443                strategy: ScrollStrategy::default(),
4444            });
4445        }
4446
4447        handle.scroll_to_active_item();
4448
4449        assert_eq!(handle.offset().x, px(-25.));
4450    }
4451
4452    #[test]
4453    fn scroll_handle_aligns_tall_children_to_top_edge() {
4454        let handle = ScrollHandle::new();
4455        {
4456            let mut state = handle.0.borrow_mut();
4457            state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4458            state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4459            state.overflow.y = Overflow::Scroll;
4460            state.active_item = Some(ScrollActiveItem {
4461                index: 0,
4462                strategy: ScrollStrategy::default(),
4463            });
4464        }
4465
4466        handle.scroll_to_active_item();
4467
4468        assert_eq!(handle.offset().y, px(-25.));
4469    }
4470
4471    fn setup_tooltip_owner_test(
4472        show_delay_override: Option<Duration>,
4473    ) -> (
4474        TestAppContext,
4475        crate::AnyWindowHandle,
4476        CapturedActiveTooltip,
4477    ) {
4478        let mut test_app = TestAppContext::single();
4479        let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
4480        let window = test_app.add_window({
4481            let captured_active_tooltip = captured_active_tooltip.clone();
4482            move |_, _| TooltipOwner {
4483                captured_active_tooltip,
4484                show_delay_override,
4485            }
4486        });
4487        let any_window = window.into();
4488
4489        test_app
4490            .update_window(any_window, |_, window, cx| {
4491                window.draw(cx).clear(cx);
4492            })
4493            .unwrap();
4494
4495        test_app
4496            .update_window(any_window, |_, window, cx| {
4497                window.dispatch_event(
4498                    MouseMoveEvent {
4499                        position: point(px(10.), px(10.)),
4500                        modifiers: Default::default(),
4501                        pressed_button: None,
4502                    }
4503                    .to_platform_input(),
4504                    cx,
4505                );
4506            })
4507            .unwrap();
4508
4509        test_app
4510            .update_window(any_window, |_, window, cx| {
4511                window.draw(cx).clear(cx);
4512            })
4513            .unwrap();
4514
4515        (test_app, any_window, captured_active_tooltip)
4516    }
4517
4518    #[test]
4519    fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
4520        let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4521
4522        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4523        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4524        assert!(matches!(
4525            active_tooltip.borrow().as_ref(),
4526            Some(ActiveTooltip::WaitingForShow { .. })
4527        ));
4528
4529        test_app
4530            .update_window(any_window, |_, window, _| {
4531                window.remove_window();
4532            })
4533            .unwrap();
4534        test_app.run_until_parked();
4535        drop(active_tooltip);
4536
4537        assert!(weak_active_tooltip.upgrade().is_none());
4538    }
4539
4540    #[test]
4541    fn tooltip_respects_custom_show_delay() {
4542        let extra_delay = Duration::from_secs(1);
4543        let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
4544        let (mut test_app, _any_window, captured_active_tooltip) =
4545            setup_tooltip_owner_test(Some(show_delay_override));
4546
4547        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4548        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4549
4550        test_app
4551            .dispatcher
4552            .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4553        test_app.run_until_parked();
4554
4555        assert!(matches!(
4556            active_tooltip.borrow().as_ref(),
4557            Some(ActiveTooltip::WaitingForShow { .. })
4558        ));
4559
4560        test_app.dispatcher.advance_clock(extra_delay);
4561        test_app.run_until_parked();
4562
4563        assert!(matches!(
4564            active_tooltip.borrow().as_ref(),
4565            Some(ActiveTooltip::Visible { .. })
4566        ));
4567    }
4568
4569    #[test]
4570    fn tooltip_is_released_when_its_owner_disappears() {
4571        let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4572
4573        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4574        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4575
4576        test_app
4577            .dispatcher
4578            .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4579        test_app.run_until_parked();
4580
4581        assert!(matches!(
4582            active_tooltip.borrow().as_ref(),
4583            Some(ActiveTooltip::Visible { .. })
4584        ));
4585
4586        test_app
4587            .update_window(any_window, |_, window, _| {
4588                window.remove_window();
4589            })
4590            .unwrap();
4591        test_app.run_until_parked();
4592        drop(active_tooltip);
4593
4594        assert!(weak_active_tooltip.upgrade().is_none());
4595    }
4596
4597    #[test]
4598    fn tooltip_hides_after_mouse_leaves_origin() {
4599        let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4600
4601        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4602        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4603
4604        test_app
4605            .dispatcher
4606            .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4607        test_app.run_until_parked();
4608
4609        assert!(matches!(
4610            active_tooltip.borrow().as_ref(),
4611            Some(ActiveTooltip::Visible { .. })
4612        ));
4613
4614        test_app
4615            .update_window(any_window, |_, window, cx| {
4616                window.dispatch_event(
4617                    MouseMoveEvent {
4618                        position: point(px(75.), px(75.)),
4619                        modifiers: Default::default(),
4620                        pressed_button: None,
4621                    }
4622                    .to_platform_input(),
4623                    cx,
4624                );
4625            })
4626            .unwrap();
4627
4628        assert!(active_tooltip.borrow().is_none());
4629    }
4630
4631    struct MouseDownOutOwner {
4632        mouse_down_out_count: Rc<RefCell<usize>>,
4633    }
4634
4635    impl Render for MouseDownOutOwner {
4636        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4637            let mouse_down_out_count = self.mouse_down_out_count.clone();
4638            div()
4639                .size_full()
4640                .child(div().id("target").w(px(50.)).h(px(50.)).on_mouse_down_out(
4641                    move |_, _, _| {
4642                        *mouse_down_out_count.borrow_mut() += 1;
4643                    },
4644                ))
4645        }
4646    }
4647
4648    #[test]
4649    fn mouse_down_out_is_suppressed_while_window_prompt_is_active() {
4650        let mut test_app = TestAppContext::single();
4651        let mouse_down_out_count = Rc::new(RefCell::new(0));
4652        let window = test_app.add_window({
4653            let mouse_down_out_count = mouse_down_out_count.clone();
4654            move |_, _| MouseDownOutOwner {
4655                mouse_down_out_count,
4656            }
4657        });
4658        let any_window: AnyWindowHandle = window.into();
4659
4660        fn dispatch_mouse_down_outside_target(
4661            test_app: &mut TestAppContext,
4662            any_window: AnyWindowHandle,
4663        ) {
4664            test_app
4665                .update_window(any_window, |_, window, cx| {
4666                    window.dispatch_event(
4667                        MouseDownEvent {
4668                            position: point(px(75.), px(75.)),
4669                            button: MouseButton::Left,
4670                            modifiers: Default::default(),
4671                            click_count: 1,
4672                            first_mouse: false,
4673                        }
4674                        .to_platform_input(),
4675                        cx,
4676                    );
4677                })
4678                .unwrap();
4679        }
4680
4681        test_app
4682            .update_window(any_window, |_, window, cx| {
4683                window.draw(cx).clear(cx);
4684            })
4685            .unwrap();
4686
4687        dispatch_mouse_down_outside_target(&mut test_app, any_window);
4688        assert_eq!(
4689            *mouse_down_out_count.borrow(),
4690            1,
4691            "mouse down outside the element should fire mouse-down-out listeners"
4692        );
4693
4694        test_app
4695            .update_window(any_window, |_, window, cx| {
4696                cx.set_prompt_builder(crate::fallback_prompt_renderer);
4697                let _receiver =
4698                    window.prompt(crate::PromptLevel::Warning, "message", None, &["Ok"], cx);
4699                assert!(window.has_active_prompt());
4700                window.draw(cx).clear(cx);
4701            })
4702            .unwrap();
4703
4704        dispatch_mouse_down_outside_target(&mut test_app, any_window);
4705        assert_eq!(
4706            *mouse_down_out_count.borrow(),
4707            1,
4708            "mouse down over an active prompt should not fire mouse-down-out listeners"
4709        );
4710    }
4711
4712    #[test]
4713    fn test_write_a11y_info_string_and_numeric_properties() {
4714        let mut interactivity = Interactivity::default();
4715        interactivity.aria.label = Some("Buffer Font Size".into());
4716        interactivity.aria.value = Some("15".into());
4717        interactivity.aria.placeholder = Some("Search".into());
4718        interactivity.aria.numeric_value = Some(15.0);
4719        interactivity.aria.min_numeric_value = Some(6.0);
4720        interactivity.aria.max_numeric_value = Some(72.0);
4721        interactivity.aria.numeric_value_step = Some(1.0);
4722
4723        let mut node = accesskit::Node::new(accesskit::Role::SpinButton);
4724        interactivity.write_a11y_info(&mut node);
4725
4726        assert_eq!(node.label(), Some("Buffer Font Size"));
4727        assert_eq!(node.value(), Some("15"));
4728        assert_eq!(node.placeholder(), Some("Search"));
4729        assert_eq!(node.numeric_value(), Some(15.0));
4730        assert_eq!(node.min_numeric_value(), Some(6.0));
4731        assert_eq!(node.max_numeric_value(), Some(72.0));
4732        assert_eq!(node.numeric_value_step(), Some(1.0));
4733    }
4734
4735    /// Two focusable, clickable elements ("a" and "b") used to exercise the
4736    /// Enter/Space -> synthesized click press/release pairing.
4737    struct KeyboardActivationTest {
4738        focus_a: FocusHandle,
4739        focus_b: FocusHandle,
4740        clicks: Rc<RefCell<Vec<&'static str>>>,
4741    }
4742
4743    impl Render for KeyboardActivationTest {
4744        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4745            let clicks_a = self.clicks.clone();
4746            let clicks_b = self.clicks.clone();
4747            div()
4748                .size_full()
4749                .child(
4750                    div()
4751                        .id("a")
4752                        .w(px(50.))
4753                        .h(px(50.))
4754                        .track_focus(&self.focus_a)
4755                        .on_click(move |_, _, _| clicks_a.borrow_mut().push("a")),
4756                )
4757                .child(
4758                    div()
4759                        .id("b")
4760                        .w(px(50.))
4761                        .h(px(50.))
4762                        .track_focus(&self.focus_b)
4763                        .on_click(move |_, _, _| clicks_b.borrow_mut().push("b")),
4764                )
4765        }
4766    }
4767
4768    fn setup_keyboard_activation_test() -> (
4769        TestAppContext,
4770        AnyWindowHandle,
4771        Rc<RefCell<Vec<&'static str>>>,
4772        FocusHandle,
4773        FocusHandle,
4774    ) {
4775        let mut cx = TestAppContext::single();
4776        let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
4777        let clicks: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
4778        let window = cx.add_window({
4779            let focus_a = focus_a.clone();
4780            let focus_b = focus_b.clone();
4781            let clicks = clicks.clone();
4782            move |_, _| KeyboardActivationTest {
4783                focus_a,
4784                focus_b,
4785                clicks,
4786            }
4787        });
4788        (cx, window.into(), clicks, focus_a, focus_b)
4789    }
4790
4791    /// Move focus to `handle`, flush effects, then paint so the newly focused
4792    /// element registers its key handlers for the next dispatched event.
4793    fn focus_and_draw(cx: &mut TestAppContext, window: AnyWindowHandle, handle: &FocusHandle) {
4794        cx.update_window(window, |_, window, cx| window.focus(handle, cx))
4795            .unwrap();
4796        cx.run_until_parked();
4797        cx.update_window(window, |_, window, cx| {
4798            window.draw(cx).clear(cx);
4799        })
4800        .unwrap();
4801    }
4802
4803    fn key_down(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4804        let keystroke = Keystroke::parse(key).unwrap();
4805        cx.update_window(window, |_, window, cx| {
4806            window.dispatch_event(
4807                KeyDownEvent {
4808                    keystroke,
4809                    is_held: false,
4810                    prefer_character_input: false,
4811                }
4812                .to_platform_input(),
4813                cx,
4814            );
4815        })
4816        .unwrap();
4817    }
4818
4819    fn key_up(cx: &mut TestAppContext, window: AnyWindowHandle, key: &str) {
4820        let keystroke = Keystroke::parse(key).unwrap();
4821        cx.update_window(window, |_, window, cx| {
4822            window.dispatch_event(KeyUpEvent { keystroke }.to_platform_input(), cx);
4823        })
4824        .unwrap();
4825    }
4826
4827    /// Pressing and releasing Enter on the same focused element fires a click.
4828    #[test]
4829    fn keyboard_activation_fires_click_on_same_element() {
4830        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4831
4832        focus_and_draw(&mut cx, window, &focus_a);
4833        key_down(&mut cx, window, "enter");
4834        key_up(&mut cx, window, "enter");
4835
4836        assert_eq!(*clicks.borrow(), vec!["a"]);
4837    }
4838
4839    /// A key-down whose key-up lands on a *different* element (because focus
4840    /// moved in between) must not leak a synthesized click onto the newly
4841    /// focused element. This is the core regression: previously the key-up
4842    /// handler fired unconditionally on whatever was focused at key-up time.
4843    #[test]
4844    fn keyboard_activation_does_not_leak_across_focus_change() {
4845        let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
4846
4847        // Enter pressed while "a" is focused...
4848        focus_and_draw(&mut cx, window, &focus_a);
4849        key_down(&mut cx, window, "enter");
4850
4851        // ...focus moves to "b" before the release (as a confirm action would)...
4852        focus_and_draw(&mut cx, window, &focus_b);
4853        key_up(&mut cx, window, "enter");
4854
4855        // ...so neither element is clicked: "a" never saw the up, and "b"
4856        // never saw the down.
4857        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4858    }
4859
4860    /// A keydown whose flag is left pending because focus moved away before
4861    /// the keyup must not fire a click when focus later *returns* to the same
4862    /// element (the menu trigger reopening case). The stamped focus generation
4863    /// no longer matches, so the stale pending state is ignored.
4864    #[test]
4865    fn keyboard_activation_does_not_leak_when_focus_returns() {
4866        let (mut cx, window, clicks, focus_a, focus_b) = setup_keyboard_activation_test();
4867
4868        // Enter pressed on "a"...
4869        focus_and_draw(&mut cx, window, &focus_a);
4870        key_down(&mut cx, window, "enter");
4871
4872        // ...focus leaves "a" before its keyup (so the pending state is never
4873        // consumed), then comes back to "a"...
4874        focus_and_draw(&mut cx, window, &focus_b);
4875        focus_and_draw(&mut cx, window, &focus_a);
4876        key_up(&mut cx, window, "enter");
4877
4878        // ...and the now-stale pending keydown must not fire a click.
4879        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4880    }
4881
4882    /// A non-activation key *released* during the press must cancel the pending
4883    /// activation. For the sequence escape-down, space-down, escape-up,
4884    /// space-up the space forms a clean down/up pair, but the intervening
4885    /// escape-up means this isn't a plain space activation, so no click fires.
4886    #[test]
4887    fn keyboard_activation_cleared_by_intervening_key_release() {
4888        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4889
4890        focus_and_draw(&mut cx, window, &focus_a);
4891        key_down(&mut cx, window, "escape");
4892        key_down(&mut cx, window, "space");
4893        key_up(&mut cx, window, "escape");
4894        key_up(&mut cx, window, "space");
4895
4896        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4897    }
4898
4899    /// The flag is a single activation marker, not keyed by which activation
4900    /// key was used, so a Space down paired with an Enter up on the same
4901    /// element still fires a click.
4902    #[test]
4903    fn keyboard_activation_does_not_distinguish_space_and_enter() {
4904        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4905
4906        focus_and_draw(&mut cx, window, &focus_a);
4907        key_down(&mut cx, window, "space");
4908        key_up(&mut cx, window, "enter");
4909
4910        assert_eq!(*clicks.borrow(), vec!["a"]);
4911    }
4912
4913    /// A non-activation key pressed between the activation down and up clears
4914    /// the pending flag, suppressing the click.
4915    #[test]
4916    fn keyboard_activation_cleared_by_intervening_keydown() {
4917        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4918
4919        focus_and_draw(&mut cx, window, &focus_a);
4920        key_down(&mut cx, window, "enter");
4921        key_down(&mut cx, window, "a");
4922        key_up(&mut cx, window, "enter");
4923
4924        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4925    }
4926
4927    /// A modified Enter (e.g. cmd-enter) is not treated as an activation key,
4928    /// so it neither sets the pending flag nor fires a click on release.
4929    #[test]
4930    fn keyboard_activation_ignores_modified_keys() {
4931        let (mut cx, window, clicks, focus_a, _focus_b) = setup_keyboard_activation_test();
4932
4933        focus_and_draw(&mut cx, window, &focus_a);
4934        key_down(&mut cx, window, "cmd-enter");
4935        key_up(&mut cx, window, "cmd-enter");
4936
4937        assert!(clicks.borrow().is_empty(), "clicks: {:?}", clicks.borrow());
4938    }
4939
4940    /// Two sibling tab groups, each a focusable container that is *not* itself a
4941    /// tab stop and holds a single tab stop. Mirrors how the title bar and
4942    /// status bar expose their controls as ARIA toolbars.
4943    struct TabGroupFocus {
4944        group_a: FocusHandle,
4945        item_a: FocusHandle,
4946        group_b: FocusHandle,
4947        item_b: FocusHandle,
4948    }
4949
4950    impl Render for TabGroupFocus {
4951        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4952            fn group(container: &FocusHandle, item: &FocusHandle) -> Div {
4953                div()
4954                    .track_focus(container)
4955                    .tab_group()
4956                    .child(div().track_focus(item))
4957            }
4958            div()
4959                .child(group(&self.group_a, &self.item_a))
4960                .child(group(&self.group_b, &self.item_b))
4961        }
4962    }
4963
4964    /// Focusing a tab-group container and pressing Tab (`focus_next`) must move
4965    /// focus to the first tab stop *inside that container*, as documented on
4966    /// [`InteractiveElement::tab_stop`].
4967    #[test]
4968    fn focus_next_from_tab_group_container_enters_that_group() {
4969        let mut cx = TestAppContext::single();
4970        let (group_a, item_a, group_b, item_b) = cx.update(|cx| {
4971            (
4972                cx.focus_handle(),
4973                cx.focus_handle().tab_stop(true),
4974                cx.focus_handle(),
4975                cx.focus_handle().tab_stop(true),
4976            )
4977        });
4978        let window: AnyWindowHandle = cx
4979            .add_window({
4980                let (group_a, item_a, group_b, item_b) =
4981                    (group_a, item_a, group_b.clone(), item_b.clone());
4982                move |_, _| TabGroupFocus {
4983                    group_a,
4984                    item_a,
4985                    group_b,
4986                    item_b,
4987                }
4988            })
4989            .into();
4990        cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4991            .unwrap();
4992
4993        // Focus the *second* group's container, then advance like Tab would.
4994        let focused = cx
4995            .update_window(window, |_, window, cx| {
4996                window.focus(&group_b, cx);
4997                window.focus_next(cx);
4998                window.focused(cx).map(|handle| handle.id)
4999            })
5000            .unwrap();
5001
5002        assert_eq!(focused, Some(item_b.id));
5003    }
5004
5005    #[gpui::test]
5006    fn test_fractional_padding_does_not_make_a_fitting_container_scrollable(
5007        cx: &mut TestAppContext,
5008    ) {
5009        struct PaddedContainer {
5010            scroll_handle: ScrollHandle,
5011        }
5012
5013        impl Render for PaddedContainer {
5014            fn render(
5015                &mut self,
5016                _window: &mut Window,
5017                _cx: &mut Context<Self>,
5018            ) -> impl IntoElement {
5019                // 4.25px of padding snaps to 4px in layout, so a 42px child
5020                // fits the 50px box exactly.
5021                div().size_full().child(
5022                    div()
5023                        .id("container")
5024                        .h(px(50.))
5025                        .w(px(100.))
5026                        .py(px(4.25))
5027                        .overflow_y_scroll()
5028                        .track_scroll(&self.scroll_handle)
5029                        .child(div().w_full().h(px(42.))),
5030                )
5031            }
5032        }
5033
5034        let scroll_handle = ScrollHandle::new();
5035        let window: AnyWindowHandle = cx
5036            .add_window({
5037                let scroll_handle = scroll_handle.clone();
5038                move |_, _| PaddedContainer { scroll_handle }
5039            })
5040            .into();
5041        cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
5042            .unwrap();
5043
5044        assert_eq!(scroll_handle.max_offset().y, px(0.));
5045    }
5046}