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