Skip to main content

gpui/elements/
div.rs

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