Skip to main content

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