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