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