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