Skip to main content

rgpui/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::PinchEvent;
19use crate::ResultExt;
20use crate::collections::HashMap;
21use crate::refineable::Refineable;
22use crate::{
23    Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent, DispatchPhase,
24    Display, Element, ElementId, Entity, FocusHandle, Global, GlobalElementId, Hitbox,
25    HitboxBehavior, HitboxId, InspectorElementId, IntoElement, IsZero, KeyContext, KeyDownEvent,
26    KeyUpEvent, KeyboardButton, KeyboardClickEvent, LayoutId, ModifiersChangedEvent, MouseButton,
27    MouseClickEvent, MouseDownEvent, MouseMoveEvent, MousePressureEvent, MouseUpEvent, Overflow,
28    ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style,
29    StyleRefinement, Styled, Task, TooltipId, Visibility, Window, WindowControlArea, point, px,
30    size,
31};
32use smallvec::SmallVec;
33use stacksafe::{StackSafe, stacksafe};
34use std::{
35    any::{Any, TypeId},
36    cell::RefCell,
37    cmp::Ordering,
38    fmt::Debug,
39    marker::PhantomData,
40    mem,
41    rc::Rc,
42    sync::Arc,
43    time::Duration,
44};
45
46use super::ImageCacheProvider;
47
48const DRAG_THRESHOLD: f64 = 2.;
49const DEFAULT_TOOLTIP_SHOW_DELAY: Duration = Duration::from_millis(500);
50const HOVERABLE_TOOLTIP_HIDE_DELAY: Duration = Duration::from_millis(500);
51
52/// The styling information for a given group.
53pub struct GroupStyle {
54    /// The identifier for this group.
55    pub group: SharedString,
56
57    /// The specific style refinement that this group would apply
58    /// to its children.
59    pub style: Box<StyleRefinement>,
60}
61
62/// An event for when a drag is moving over this element, with the given state type.
63pub struct DragMoveEvent<T> {
64    /// The mouse move event that triggered this drag move event.
65    pub event: MouseMoveEvent,
66
67    /// The bounds of this element.
68    pub bounds: Bounds<Pixels>,
69    drag: PhantomData<T>,
70    dragged_item: Arc<dyn Any>,
71}
72
73impl<T: 'static> DragMoveEvent<T> {
74    /// Returns the drag state for this event.
75    pub fn drag<'b>(&self, cx: &'b App) -> &'b T {
76        cx.active_drag
77            .as_ref()
78            .and_then(|drag| drag.value.downcast_ref::<T>())
79            .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
80    }
81
82    /// An item that is about to be dropped.
83    pub fn dragged_item(&self) -> &dyn Any {
84        self.dragged_item.as_ref()
85    }
86}
87
88impl Interactivity {
89    /// Create an `Interactivity`, capturing the caller location in debug mode.
90    #[cfg(any(feature = "inspector", debug_assertions))]
91    #[track_caller]
92    pub fn new() -> Interactivity {
93        Interactivity {
94            source_location: Some(core::panic::Location::caller()),
95            ..Default::default()
96        }
97    }
98
99    /// Create an `Interactivity`, capturing the caller location in debug mode.
100    #[cfg(not(any(feature = "inspector", debug_assertions)))]
101    pub fn new() -> Interactivity {
102        Interactivity::default()
103    }
104
105    /// Gets the source location of construction. Returns `None` when not in debug mode.
106    pub fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
107        #[cfg(any(feature = "inspector", debug_assertions))]
108        {
109            self.source_location
110        }
111
112        #[cfg(not(any(feature = "inspector", debug_assertions)))]
113        {
114            None
115        }
116    }
117
118    /// Bind the given callback to the mouse down event for the given mouse button, during the bubble phase.
119    /// The imperative API equivalent of [`InteractiveElement::on_mouse_down`].
120    ///
121    /// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
122    pub fn on_mouse_down(
123        &mut self,
124        button: MouseButton,
125        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
126    ) {
127        self.mouse_down_listeners
128            .push(Box::new(move |event, phase, hitbox, window, cx| {
129                if phase == DispatchPhase::Bubble
130                    && event.button == button
131                    && hitbox.is_hovered(window)
132                {
133                    (listener)(event, window, cx)
134                }
135            }));
136    }
137
138    /// Bind the given callback to the mouse down event for any button, during the capture phase.
139    /// The imperative API equivalent of [`InteractiveElement::capture_any_mouse_down`].
140    ///
141    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
142    pub fn capture_any_mouse_down(
143        &mut self,
144        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
145    ) {
146        self.mouse_down_listeners
147            .push(Box::new(move |event, phase, hitbox, window, cx| {
148                if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
149                    (listener)(event, window, cx)
150                }
151            }));
152    }
153
154    /// Bind the given callback to the mouse down event for any button, during the bubble phase.
155    /// The imperative API equivalent to [`InteractiveElement::on_any_mouse_down`].
156    ///
157    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
158    pub fn on_any_mouse_down(
159        &mut self,
160        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
161    ) {
162        self.mouse_down_listeners
163            .push(Box::new(move |event, phase, hitbox, window, cx| {
164                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
165                    (listener)(event, window, cx)
166                }
167            }));
168    }
169
170    /// Bind the given callback to the mouse pressure event, during the bubble phase
171    /// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
172    ///
173    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
174    pub fn on_mouse_pressure(
175        &mut self,
176        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
177    ) {
178        self.mouse_pressure_listeners
179            .push(Box::new(move |event, phase, hitbox, window, cx| {
180                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
181                    (listener)(event, window, cx)
182                }
183            }));
184    }
185
186    /// Bind the given callback to the mouse pressure event, during the capture phase
187    /// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
188    ///
189    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
190    pub fn capture_mouse_pressure(
191        &mut self,
192        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
193    ) {
194        self.mouse_pressure_listeners
195            .push(Box::new(move |event, phase, hitbox, window, cx| {
196                if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
197                    (listener)(event, window, cx)
198                }
199            }));
200    }
201
202    /// Bind the given callback to the mouse up event for the given button, during the bubble phase.
203    /// The imperative API equivalent to [`InteractiveElement::on_mouse_up`].
204    ///
205    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
206    pub fn on_mouse_up(
207        &mut self,
208        button: MouseButton,
209        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
210    ) {
211        self.mouse_up_listeners
212            .push(Box::new(move |event, phase, hitbox, window, cx| {
213                if phase == DispatchPhase::Bubble
214                    && event.button == button
215                    && hitbox.is_hovered(window)
216                {
217                    (listener)(event, window, cx)
218                }
219            }));
220    }
221
222    /// Bind the given callback to the mouse up event for any button, during the capture phase.
223    /// The imperative API equivalent to [`InteractiveElement::capture_any_mouse_up`].
224    ///
225    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
226    pub fn capture_any_mouse_up(
227        &mut self,
228        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
229    ) {
230        self.mouse_up_listeners
231            .push(Box::new(move |event, phase, hitbox, window, cx| {
232                if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
233                    (listener)(event, window, cx)
234                }
235            }));
236    }
237
238    /// Bind the given callback to the mouse up event for any button, during the bubble phase.
239    /// The imperative API equivalent to [`Interactivity::on_any_mouse_up`].
240    ///
241    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
242    pub fn on_any_mouse_up(
243        &mut self,
244        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
245    ) {
246        self.mouse_up_listeners
247            .push(Box::new(move |event, phase, hitbox, window, cx| {
248                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
249                    (listener)(event, window, cx)
250                }
251            }));
252    }
253
254    /// Bind the given callback to the mouse down event, on any button, during the capture phase,
255    /// when the mouse is outside of the bounds of this element.
256    /// The imperative API equivalent to [`InteractiveElement::on_mouse_down_out`].
257    ///
258    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
259    pub fn on_mouse_down_out(
260        &mut self,
261        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
262    ) {
263        self.mouse_down_listeners
264            .push(Box::new(move |event, phase, hitbox, window, cx| {
265                if phase == DispatchPhase::Capture && !hitbox.contains(&window.mouse_position()) {
266                    (listener)(event, window, cx)
267                }
268            }));
269    }
270
271    /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
272    /// when the mouse is outside of the bounds of this element.
273    /// The imperative API equivalent to [`InteractiveElement::on_mouse_up_out`].
274    ///
275    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
276    pub fn on_mouse_up_out(
277        &mut self,
278        button: MouseButton,
279        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
280    ) {
281        self.mouse_up_listeners
282            .push(Box::new(move |event, phase, hitbox, window, cx| {
283                if phase == DispatchPhase::Capture
284                    && event.button == button
285                    && !hitbox.is_hovered(window)
286                {
287                    (listener)(event, window, cx);
288                }
289            }));
290    }
291
292    /// Bind the given callback to the mouse move event, during the bubble phase.
293    /// The imperative API equivalent to [`InteractiveElement::on_mouse_move`].
294    ///
295    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
296    pub fn on_mouse_move(
297        &mut self,
298        listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
299    ) {
300        self.mouse_move_listeners
301            .push(Box::new(move |event, phase, hitbox, window, cx| {
302                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
303                    (listener)(event, window, cx);
304                }
305            }));
306    }
307
308    /// Bind the given callback to the mouse drag event of the given type. Note that this
309    /// will be called for all move events, inside or outside of this element, as long as the
310    /// drag was started with this element under the mouse. Useful for implementing draggable
311    /// UIs that don't conform to a drag and drop style interaction, like resizing.
312    /// The imperative API equivalent to [`InteractiveElement::on_drag_move`].
313    ///
314    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
315    pub fn on_drag_move<T>(
316        &mut self,
317        listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
318    ) where
319        T: 'static,
320    {
321        self.mouse_move_listeners
322            .push(Box::new(move |event, phase, hitbox, window, cx| {
323                if phase == DispatchPhase::Capture
324                    && let Some(drag) = &cx.active_drag
325                    && drag.value.as_ref().type_id() == TypeId::of::<T>()
326                {
327                    (listener)(
328                        &DragMoveEvent {
329                            event: event.clone(),
330                            bounds: hitbox.bounds,
331                            drag: PhantomData,
332                            dragged_item: Arc::clone(&drag.value),
333                        },
334                        window,
335                        cx,
336                    );
337                }
338            }));
339    }
340
341    /// Bind the given callback to scroll wheel events during the bubble phase.
342    /// The imperative API equivalent to [`InteractiveElement::on_scroll_wheel`].
343    ///
344    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
345    pub fn on_scroll_wheel(
346        &mut self,
347        listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
348    ) {
349        self.scroll_wheel_listeners
350            .push(Box::new(move |event, phase, hitbox, window, cx| {
351                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
352                    (listener)(event, window, cx);
353                }
354            }));
355    }
356
357    /// Bind the given callback to pinch gesture events during the bubble phase.
358    ///
359    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
360    pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
361        self.pinch_listeners
362            .push(Box::new(move |event, phase, hitbox, window, cx| {
363                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
364                    (listener)(event, window, cx);
365                }
366            }));
367    }
368
369    /// Bind the given callback to pinch gesture events during the capture phase.
370    ///
371    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
372    pub fn capture_pinch(
373        &mut self,
374        listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
375    ) {
376        self.pinch_listeners
377            .push(Box::new(move |event, phase, _hitbox, window, cx| {
378                if phase == DispatchPhase::Capture {
379                    (listener)(event, window, cx);
380                } else {
381                    cx.propagate();
382                }
383            }));
384    }
385
386    /// Bind the given callback to an action dispatch during the capture phase.
387    /// The imperative API equivalent to [`InteractiveElement::capture_action`].
388    ///
389    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
390    pub fn capture_action<A: Action>(
391        &mut self,
392        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
393    ) {
394        self.action_listeners.push((
395            TypeId::of::<A>(),
396            Box::new(move |action, phase, window, cx| {
397                let action = action.downcast_ref().unwrap();
398                if phase == DispatchPhase::Capture {
399                    (listener)(action, window, cx)
400                } else {
401                    cx.propagate();
402                }
403            }),
404        ));
405    }
406
407    /// Bind the given callback to an action dispatch during the bubble phase.
408    /// The imperative API equivalent to [`InteractiveElement::on_action`].
409    ///
410    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
411    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
412        self.action_listeners.push((
413            TypeId::of::<A>(),
414            Box::new(move |action, phase, window, cx| {
415                let action = action.downcast_ref().unwrap();
416                if phase == DispatchPhase::Bubble {
417                    (listener)(action, window, cx)
418                }
419            }),
420        ));
421    }
422
423    /// Bind the given callback to an action dispatch, based on a dynamic action parameter
424    /// instead of a type parameter. Useful for component libraries that want to expose
425    /// action bindings to their users.
426    /// The imperative API equivalent to [`InteractiveElement::on_boxed_action`].
427    ///
428    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
429    pub fn on_boxed_action(
430        &mut self,
431        action: &dyn Action,
432        listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
433    ) {
434        let action = action.boxed_clone();
435        self.action_listeners.push((
436            (*action).type_id(),
437            Box::new(move |_, phase, window, cx| {
438                if phase == DispatchPhase::Bubble {
439                    (listener)(&*action, window, cx)
440                }
441            }),
442        ));
443    }
444
445    /// Bind the given callback to key down events during the bubble phase.
446    /// The imperative API equivalent to [`InteractiveElement::on_key_down`].
447    ///
448    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
449    pub fn on_key_down(
450        &mut self,
451        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
452    ) {
453        self.key_down_listeners
454            .push(Box::new(move |event, phase, window, cx| {
455                if phase == DispatchPhase::Bubble {
456                    (listener)(event, window, cx)
457                }
458            }));
459    }
460
461    /// Bind the given callback to key down events during the capture phase.
462    /// The imperative API equivalent to [`InteractiveElement::capture_key_down`].
463    ///
464    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
465    pub fn capture_key_down(
466        &mut self,
467        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
468    ) {
469        self.key_down_listeners
470            .push(Box::new(move |event, phase, window, cx| {
471                if phase == DispatchPhase::Capture {
472                    listener(event, window, cx)
473                }
474            }));
475    }
476
477    /// Bind the given callback to key up events during the bubble phase.
478    /// The imperative API equivalent to [`InteractiveElement::on_key_up`].
479    ///
480    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
481    pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
482        self.key_up_listeners
483            .push(Box::new(move |event, phase, window, cx| {
484                if phase == DispatchPhase::Bubble {
485                    listener(event, window, cx)
486                }
487            }));
488    }
489
490    /// Bind the given callback to key up events during the capture phase.
491    /// The imperative API equivalent to [`InteractiveElement::on_key_up`].
492    ///
493    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
494    pub fn capture_key_up(
495        &mut self,
496        listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
497    ) {
498        self.key_up_listeners
499            .push(Box::new(move |event, phase, window, cx| {
500                if phase == DispatchPhase::Capture {
501                    listener(event, window, cx)
502                }
503            }));
504    }
505
506    /// Bind the given callback to modifiers changing events.
507    /// The imperative API equivalent to [`InteractiveElement::on_modifiers_changed`].
508    ///
509    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
510    pub fn on_modifiers_changed(
511        &mut self,
512        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
513    ) {
514        self.modifiers_changed_listeners
515            .push(Box::new(move |event, window, cx| {
516                listener(event, window, cx)
517            }));
518    }
519
520    /// Bind the given callback to drop events of the given type, whether or not the drag started on this element.
521    /// The imperative API equivalent to [`InteractiveElement::on_drop`].
522    ///
523    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
524    pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
525        self.drop_listeners.push((
526            TypeId::of::<T>(),
527            Box::new(move |dragged_value, window, cx| {
528                listener(dragged_value.downcast_ref().unwrap(), window, cx);
529            }),
530        ));
531    }
532
533    /// Use the given predicate to determine whether or not a drop event should be dispatched to this element.
534    /// The imperative API equivalent to [`InteractiveElement::can_drop`].
535    pub fn can_drop(
536        &mut self,
537        predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
538    ) {
539        self.can_drop_predicate = Some(Box::new(predicate));
540    }
541
542    /// Bind the given callback to click events of this element.
543    /// The imperative API equivalent to [`StatefulInteractiveElement::on_click`].
544    ///
545    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
546    pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
547    where
548        Self: Sized,
549    {
550        self.click_listeners.push(Rc::new(move |event, window, cx| {
551            listener(event, window, cx)
552        }));
553    }
554
555    /// Bind the given callback to non-primary click events of this element.
556    /// The imperative API equivalent to [`StatefulInteractiveElement::on_aux_click`].
557    ///
558    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
559    pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
560    where
561        Self: Sized,
562    {
563        self.aux_click_listeners
564            .push(Rc::new(move |event, window, cx| {
565                listener(event, window, cx)
566            }));
567    }
568
569    /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
570    /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
571    /// the [`Self::on_drag_move`] API.
572    /// The imperative API equivalent to [`StatefulInteractiveElement::on_drag`].
573    ///
574    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
575    pub fn on_drag<T, W>(
576        &mut self,
577        value: T,
578        constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
579    ) where
580        Self: Sized,
581        T: 'static,
582        W: 'static + Render,
583    {
584        debug_assert!(
585            self.drag_listener.is_none(),
586            "calling on_drag more than once on the same element is not supported"
587        );
588        self.drag_listener = Some((
589            Arc::new(value),
590            Box::new(move |value, offset, window, cx| {
591                constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
592            }),
593        ));
594    }
595
596    /// Bind the given callback on the hover start and end events of this element. Note that the boolean
597    /// passed to the callback is true when the hover starts and false when it ends.
598    /// The imperative API equivalent to [`StatefulInteractiveElement::on_hover`].
599    ///
600    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
601    pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
602    where
603        Self: Sized,
604    {
605        debug_assert!(
606            self.hover_listener.is_none(),
607            "calling on_hover more than once on the same element is not supported"
608        );
609        self.hover_listener = Some(Box::new(listener));
610    }
611
612    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
613    /// The imperative API equivalent to [`StatefulInteractiveElement::tooltip`].
614    pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
615    where
616        Self: Sized,
617    {
618        debug_assert!(
619            self.tooltip_builder.is_none(),
620            "calling tooltip more than once on the same element is not supported"
621        );
622        self.tooltip_builder = Some(TooltipBuilder {
623            build: Rc::new(build_tooltip),
624            hoverable: false,
625        });
626    }
627
628    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
629    /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
630    /// the tooltip. The imperative API equivalent to [`StatefulInteractiveElement::hoverable_tooltip`].
631    pub fn hoverable_tooltip(
632        &mut self,
633        build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
634    ) where
635        Self: Sized,
636    {
637        debug_assert!(
638            self.tooltip_builder.is_none(),
639            "calling tooltip more than once on the same element is not supported"
640        );
641        self.tooltip_builder = Some(TooltipBuilder {
642            build: Rc::new(build_tooltip),
643            hoverable: true,
644        });
645    }
646
647    /// 设置此元素提示框的显示延迟。
648    /// 对应 [`StatefulInteractiveElement::tooltip_show_delay`] 的命令式 API。
649    pub fn tooltip_show_delay(&mut self, delay: Duration) {
650        self.tooltip_show_delay = Some(delay);
651    }
652
653    /// Block the mouse from all interactions with elements behind this element's hitbox. Typically
654    /// `block_mouse_except_scroll` should be preferred.
655    ///
656    /// The imperative API equivalent to [`InteractiveElement::occlude`]
657    pub fn occlude_mouse(&mut self) {
658        self.hitbox_behavior = HitboxBehavior::BlockMouse;
659    }
660
661    /// Set the bounds of this element as a window control area for the platform window.
662    /// The imperative API equivalent to [`InteractiveElement::window_control_area`]
663    pub fn window_control_area(&mut self, area: WindowControlArea) {
664        self.window_control = Some(area);
665    }
666
667    /// Block non-scroll mouse interactions with elements behind this element's hitbox.
668    /// The imperative API equivalent to [`InteractiveElement::block_mouse_except_scroll`].
669    ///
670    /// See [`Hitbox::is_hovered`] for details.
671    pub fn block_mouse_except_scroll(&mut self) {
672        self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
673    }
674
675    fn has_pinch_listeners(&self) -> bool {
676        !self.pinch_listeners.is_empty()
677    }
678}
679
680/// A trait for elements that want to use the standard GPUI event handlers that don't
681/// require any state.
682pub trait InteractiveElement: Sized {
683    /// Retrieve the interactivity state associated with this element
684    fn interactivity(&mut self) -> &mut Interactivity;
685
686    /// Assign this element to a group of elements that can be styled together
687    fn group(mut self, group: impl Into<SharedString>) -> Self {
688        self.interactivity().group = Some(group.into());
689        self
690    }
691
692    /// Assign this element an ID, so that it can be used with interactivity
693    fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
694        self.interactivity().element_id = Some(id.into());
695
696        Stateful { element: self }
697    }
698
699    /// Track the focus state of the given focus handle on this element.
700    /// If the focus handle is focused by the application, this element will
701    /// apply its focused styles.
702    fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
703        self.interactivity().focusable = true;
704        self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
705        self
706    }
707
708    /// Set whether this element is a tab stop.
709    ///
710    /// When false, the element remains in tab-index order but cannot be reached via keyboard navigation.
711    /// Useful for container elements: focus the container, then call `window.focus_next(cx)` to focus
712    /// the first tab stop inside it while having the container element itself be unreachable via the keyboard.
713    /// Should only be used with `tab_index`.
714    fn tab_stop(mut self, tab_stop: bool) -> Self {
715        self.interactivity().tab_stop = tab_stop;
716        self
717    }
718
719    /// Set index of the tab stop order, and set this node as a tab stop.
720    /// This will default the element to being a tab stop. See [`Self::tab_stop`] for more information.
721    /// This should only be used in conjunction with `tab_group`
722    /// in order to not interfere with the tab index of other elements.
723    fn tab_index(mut self, index: isize) -> Self {
724        self.interactivity().focusable = true;
725        self.interactivity().tab_index = Some(index);
726        self.interactivity().tab_stop = true;
727        self
728    }
729
730    /// Designate this div as a "tab group". Tab groups have their own location in the tab-index order,
731    /// but for children of the tab group, the tab index is reset to 0. This can be useful for swapping
732    /// the order of tab stops within the group, without having to renumber all the tab stops in the whole
733    /// application.
734    fn tab_group(mut self) -> Self {
735        self.interactivity().tab_group = true;
736        if self.interactivity().tab_index.is_none() {
737            self.interactivity().tab_index = Some(0);
738        }
739        self
740    }
741
742    /// Set the keymap context for this element. This will be used to determine
743    /// which action to dispatch from the keymap.
744    fn key_context<C, E>(mut self, key_context: C) -> Self
745    where
746        C: TryInto<KeyContext, Error = E>,
747        E: std::fmt::Display,
748    {
749        if let Some(key_context) = key_context.try_into().log_err() {
750            self.interactivity().key_context = Some(key_context);
751        }
752        self
753    }
754
755    /// Apply the given style to this element when the mouse hovers over it
756    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
757        debug_assert!(
758            self.interactivity().hover_style.is_none(),
759            "hover style already set"
760        );
761        self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
762        self
763    }
764
765    /// Apply the given style to this element when the mouse hovers over a group member
766    fn group_hover(
767        mut self,
768        group_name: impl Into<SharedString>,
769        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
770    ) -> Self {
771        self.interactivity().group_hover_style = Some(GroupStyle {
772            group: group_name.into(),
773            style: Box::new(f(StyleRefinement::default())),
774        });
775        self
776    }
777
778    /// Bind the given callback to the mouse down event for the given mouse button.
779    /// The fluent API equivalent to [`Interactivity::on_mouse_down`].
780    ///
781    /// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
782    fn on_mouse_down(
783        mut self,
784        button: MouseButton,
785        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
786    ) -> Self {
787        self.interactivity().on_mouse_down(button, listener);
788        self
789    }
790
791    #[cfg(any(test, feature = "test-support"))]
792    /// Set a key that can be used to look up this element's bounds
793    /// in the [`crate::VisualTestContext::debug_bounds`] map
794    /// This is a noop in release builds
795    fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
796        self.interactivity().debug_selector = Some(f());
797        self
798    }
799
800    #[cfg(not(any(test, feature = "test-support")))]
801    /// Set a key that can be used to look up this element's bounds
802    /// in the [`crate::VisualTestContext::debug_bounds`] map
803    /// This is a noop in release builds
804    #[inline]
805    fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
806        self
807    }
808
809    /// Bind the given callback to the mouse down event for any button, during the capture phase.
810    /// The fluent API equivalent to [`Interactivity::capture_any_mouse_down`].
811    ///
812    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
813    fn capture_any_mouse_down(
814        mut self,
815        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
816    ) -> Self {
817        self.interactivity().capture_any_mouse_down(listener);
818        self
819    }
820
821    /// Bind the given callback to the mouse down event for any button, during the capture phase.
822    /// The fluent API equivalent to [`Interactivity::on_any_mouse_down`].
823    ///
824    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
825    fn on_any_mouse_down(
826        mut self,
827        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
828    ) -> Self {
829        self.interactivity().on_any_mouse_down(listener);
830        self
831    }
832
833    /// Bind the given callback to the mouse up event for the given button, during the bubble phase.
834    /// The fluent API equivalent to [`Interactivity::on_mouse_up`].
835    ///
836    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
837    fn on_mouse_up(
838        mut self,
839        button: MouseButton,
840        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
841    ) -> Self {
842        self.interactivity().on_mouse_up(button, listener);
843        self
844    }
845
846    /// Bind the given callback to the mouse up event for any button, during the capture phase.
847    /// The fluent API equivalent to [`Interactivity::capture_any_mouse_up`].
848    ///
849    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
850    fn capture_any_mouse_up(
851        mut self,
852        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
853    ) -> Self {
854        self.interactivity().capture_any_mouse_up(listener);
855        self
856    }
857
858    /// Bind the given callback to the mouse pressure event, during the bubble phase
859    /// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
860    ///
861    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
862    fn on_mouse_pressure(
863        mut self,
864        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
865    ) -> Self {
866        self.interactivity().on_mouse_pressure(listener);
867        self
868    }
869
870    /// Bind the given callback to the mouse pressure event, during the capture phase
871    /// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
872    ///
873    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
874    fn capture_mouse_pressure(
875        mut self,
876        listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
877    ) -> Self {
878        self.interactivity().capture_mouse_pressure(listener);
879        self
880    }
881
882    /// Bind the given callback to the mouse down event, on any button, during the capture phase,
883    /// when the mouse is outside of the bounds of this element.
884    /// The fluent API equivalent to [`Interactivity::on_mouse_down_out`].
885    ///
886    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
887    fn on_mouse_down_out(
888        mut self,
889        listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
890    ) -> Self {
891        self.interactivity().on_mouse_down_out(listener);
892        self
893    }
894
895    /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
896    /// when the mouse is outside of the bounds of this element.
897    /// The fluent API equivalent to [`Interactivity::on_mouse_up_out`].
898    ///
899    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
900    fn on_mouse_up_out(
901        mut self,
902        button: MouseButton,
903        listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
904    ) -> Self {
905        self.interactivity().on_mouse_up_out(button, listener);
906        self
907    }
908
909    /// Bind the given callback to the mouse move event, during the bubble phase.
910    /// The fluent API equivalent to [`Interactivity::on_mouse_move`].
911    ///
912    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
913    fn on_mouse_move(
914        mut self,
915        listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
916    ) -> Self {
917        self.interactivity().on_mouse_move(listener);
918        self
919    }
920
921    /// Bind the given callback to the mouse drag event of the given type. Note that this
922    /// will be called for all move events, inside or outside of this element, as long as the
923    /// drag was started with this element under the mouse. Useful for implementing draggable
924    /// UIs that don't conform to a drag and drop style interaction, like resizing.
925    /// The fluent API equivalent to [`Interactivity::on_drag_move`].
926    ///
927    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
928    fn on_drag_move<T: 'static>(
929        mut self,
930        listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
931    ) -> Self {
932        self.interactivity().on_drag_move(listener);
933        self
934    }
935
936    /// Bind the given callback to scroll wheel events during the bubble phase.
937    /// The fluent API equivalent to [`Interactivity::on_scroll_wheel`].
938    ///
939    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
940    fn on_scroll_wheel(
941        mut self,
942        listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
943    ) -> Self {
944        self.interactivity().on_scroll_wheel(listener);
945        self
946    }
947
948    /// Bind the given callback to pinch gesture events during the bubble phase.
949    /// The fluent API equivalent to [`Interactivity::on_pinch`].
950    ///
951    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
952    fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
953        self.interactivity().on_pinch(listener);
954        self
955    }
956
957    /// Bind the given callback to pinch gesture events during the capture phase.
958    /// The fluent API equivalent to [`Interactivity::capture_pinch`].
959    ///
960    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
961    fn capture_pinch(
962        mut self,
963        listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
964    ) -> Self {
965        self.interactivity().capture_pinch(listener);
966        self
967    }
968    /// Capture the given action, before normal action dispatch can fire.
969    /// The fluent API equivalent to [`Interactivity::capture_action`].
970    ///
971    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
972    fn capture_action<A: Action>(
973        mut self,
974        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
975    ) -> Self {
976        self.interactivity().capture_action(listener);
977        self
978    }
979
980    /// Bind the given callback to an action dispatch during the bubble phase.
981    /// The fluent API equivalent to [`Interactivity::on_action`].
982    ///
983    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
984    fn on_action<A: Action>(
985        mut self,
986        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
987    ) -> Self {
988        self.interactivity().on_action(listener);
989        self
990    }
991
992    /// Bind the given callback to an action dispatch, based on a dynamic action parameter
993    /// instead of a type parameter. Useful for component libraries that want to expose
994    /// action bindings to their users.
995    /// The fluent API equivalent to [`Interactivity::on_boxed_action`].
996    ///
997    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
998    fn on_boxed_action(
999        mut self,
1000        action: &dyn Action,
1001        listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1002    ) -> Self {
1003        self.interactivity().on_boxed_action(action, listener);
1004        self
1005    }
1006
1007    /// Bind the given callback to key down events during the bubble phase.
1008    /// The fluent API equivalent to [`Interactivity::on_key_down`].
1009    ///
1010    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1011    fn on_key_down(
1012        mut self,
1013        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1014    ) -> Self {
1015        self.interactivity().on_key_down(listener);
1016        self
1017    }
1018
1019    /// Bind the given callback to key down events during the capture phase.
1020    /// The fluent API equivalent to [`Interactivity::capture_key_down`].
1021    ///
1022    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1023    fn capture_key_down(
1024        mut self,
1025        listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1026    ) -> Self {
1027        self.interactivity().capture_key_down(listener);
1028        self
1029    }
1030
1031    /// Bind the given callback to key up events during the bubble phase.
1032    /// The fluent API equivalent to [`Interactivity::on_key_up`].
1033    ///
1034    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1035    fn on_key_up(
1036        mut self,
1037        listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1038    ) -> Self {
1039        self.interactivity().on_key_up(listener);
1040        self
1041    }
1042
1043    /// Bind the given callback to key up events during the capture phase.
1044    /// The fluent API equivalent to [`Interactivity::capture_key_up`].
1045    ///
1046    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1047    fn capture_key_up(
1048        mut self,
1049        listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1050    ) -> Self {
1051        self.interactivity().capture_key_up(listener);
1052        self
1053    }
1054
1055    /// Bind the given callback to modifiers changing events.
1056    /// The fluent API equivalent to [`Interactivity::on_modifiers_changed`].
1057    ///
1058    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1059    fn on_modifiers_changed(
1060        mut self,
1061        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1062    ) -> Self {
1063        self.interactivity().on_modifiers_changed(listener);
1064        self
1065    }
1066
1067    /// Apply the given style when the given data type is dragged over this element
1068    fn drag_over<S: 'static>(
1069        mut self,
1070        f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1071    ) -> Self {
1072        self.interactivity().drag_over_styles.push((
1073            TypeId::of::<S>(),
1074            Box::new(move |currently_dragged: &dyn Any, window, cx| {
1075                f(
1076                    StyleRefinement::default(),
1077                    currently_dragged.downcast_ref::<S>().unwrap(),
1078                    window,
1079                    cx,
1080                )
1081            }),
1082        ));
1083        self
1084    }
1085
1086    /// Apply the given style when the given data type is dragged over this element's group
1087    fn group_drag_over<S: 'static>(
1088        mut self,
1089        group_name: impl Into<SharedString>,
1090        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1091    ) -> Self {
1092        self.interactivity().group_drag_over_styles.push((
1093            TypeId::of::<S>(),
1094            GroupStyle {
1095                group: group_name.into(),
1096                style: Box::new(f(StyleRefinement::default())),
1097            },
1098        ));
1099        self
1100    }
1101
1102    /// Bind the given callback to drop events of the given type, whether or not the drag started on this element.
1103    /// The fluent API equivalent to [`Interactivity::on_drop`].
1104    ///
1105    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1106    fn on_drop<T: 'static>(
1107        mut self,
1108        listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1109    ) -> Self {
1110        self.interactivity().on_drop(listener);
1111        self
1112    }
1113
1114    /// Use the given predicate to determine whether or not a drop event should be dispatched to this element.
1115    /// The fluent API equivalent to [`Interactivity::can_drop`].
1116    fn can_drop(
1117        mut self,
1118        predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1119    ) -> Self {
1120        self.interactivity().can_drop(predicate);
1121        self
1122    }
1123
1124    /// Block the mouse from all interactions with elements behind this element's hitbox. Typically
1125    /// `block_mouse_except_scroll` should be preferred.
1126    /// The fluent API equivalent to [`Interactivity::occlude_mouse`].
1127    fn occlude(mut self) -> Self {
1128        self.interactivity().occlude_mouse();
1129        self
1130    }
1131
1132    /// Set the bounds of this element as a window control area for the platform window.
1133    /// The fluent API equivalent to [`Interactivity::window_control_area`].
1134    fn window_control_area(mut self, area: WindowControlArea) -> Self {
1135        self.interactivity().window_control_area(area);
1136        self
1137    }
1138
1139    /// Block non-scroll mouse interactions with elements behind this element's hitbox.
1140    /// The fluent API equivalent to [`Interactivity::block_mouse_except_scroll`].
1141    ///
1142    /// See [`Hitbox::is_hovered`] for details.
1143    fn block_mouse_except_scroll(mut self) -> Self {
1144        self.interactivity().block_mouse_except_scroll();
1145        self
1146    }
1147
1148    /// Set the given styles to be applied when this element, specifically, is focused.
1149    /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1150    fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1151    where
1152        Self: Sized,
1153    {
1154        self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1155        self
1156    }
1157
1158    /// Set the given styles to be applied when this element is inside another element that is focused.
1159    /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1160    fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1161    where
1162        Self: Sized,
1163    {
1164        self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1165        self
1166    }
1167
1168    /// Set the given styles to be applied when this element is focused via keyboard navigation.
1169    /// This is similar to CSS's `:focus-visible` pseudo-class - it only applies when the element
1170    /// is focused AND the user is navigating via keyboard (not mouse clicks).
1171    /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1172    fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1173    where
1174        Self: Sized,
1175    {
1176        self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1177        self
1178    }
1179}
1180
1181/// A trait for elements that want to use the standard GPUI interactivity features
1182/// that require state.
1183pub trait StatefulInteractiveElement: InteractiveElement {
1184    /// Set the accessible role for this element.
1185    fn role(mut self, role: accesskit::Role) -> Self {
1186        debug_assert!(
1187            role != accesskit::Role::GenericContainer,
1188            "GenericContainer is filtered out of the a11y tree and has no effect"
1189        );
1190        self.interactivity().override_role = Some(role);
1191        self
1192    }
1193
1194    /// Set the accessible label for this element.
1195    fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1196        self.interactivity().aria_label = Some(label.into());
1197        self
1198    }
1199
1200    /// Set the selected state for this element.
1201    fn aria_selected(mut self, selected: bool) -> Self {
1202        self.interactivity().aria_selected = Some(selected);
1203        self
1204    }
1205
1206    /// Set the expanded state for this element.
1207    fn aria_expanded(mut self, expanded: bool) -> Self {
1208        self.interactivity().aria_expanded = Some(expanded);
1209        self
1210    }
1211
1212    /// Set the toggled state for this element.
1213    fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1214        self.interactivity().aria_toggled = Some(toggled);
1215        self
1216    }
1217
1218    /// Set the numeric value for this element.
1219    fn aria_numeric_value(mut self, value: f64) -> Self {
1220        self.interactivity().aria_numeric_value = Some(value);
1221        self
1222    }
1223
1224    /// Set the minimum numeric value for this element.
1225    fn aria_min_numeric_value(mut self, value: f64) -> Self {
1226        self.interactivity().aria_min_numeric_value = Some(value);
1227        self
1228    }
1229
1230    /// Set the maximum numeric value for this element.
1231    fn aria_max_numeric_value(mut self, value: f64) -> Self {
1232        self.interactivity().aria_max_numeric_value = Some(value);
1233        self
1234    }
1235
1236    /// Set the orientation of this element.
1237    fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1238        self.interactivity().aria_orientation = Some(orientation);
1239        self
1240    }
1241
1242    /// Set the heading level of this element.
1243    fn aria_level(mut self, level: usize) -> Self {
1244        self.interactivity().aria_level = Some(level);
1245        self
1246    }
1247
1248    /// Set the position in set of this element.
1249    fn aria_position_in_set(mut self, position: usize) -> Self {
1250        self.interactivity().aria_position_in_set = Some(position);
1251        self
1252    }
1253
1254    /// Set the size of set for this element.
1255    fn aria_size_of_set(mut self, size: usize) -> Self {
1256        self.interactivity().aria_size_of_set = Some(size);
1257        self
1258    }
1259
1260    /// Set the row index for this element.
1261    fn aria_row_index(mut self, index: usize) -> Self {
1262        self.interactivity().aria_row_index = Some(index);
1263        self
1264    }
1265
1266    /// Set the column index for this element.
1267    fn aria_column_index(mut self, index: usize) -> Self {
1268        self.interactivity().aria_column_index = Some(index);
1269        self
1270    }
1271
1272    /// Set the row count for this element.
1273    fn aria_row_count(mut self, count: usize) -> Self {
1274        self.interactivity().aria_row_count = Some(count);
1275        self
1276    }
1277
1278    /// Set the column count for this element.
1279    fn aria_column_count(mut self, count: usize) -> Self {
1280        self.interactivity().aria_column_count = Some(count);
1281        self
1282    }
1283
1284    /// Register a handler for an accessibility action on this element.
1285    fn on_a11y_action(
1286        mut self,
1287        action: accesskit::Action,
1288        listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1289        + 'static,
1290    ) -> Self {
1291        self.interactivity()
1292            .a11y_action_listeners
1293            .push((action, Box::new(listener)));
1294        self
1295    }
1296
1297    /// Set this element to focusable.
1298    fn focusable(mut self) -> Self {
1299        self.interactivity().focusable = true;
1300        self
1301    }
1302
1303    /// Set the overflow x and y to scroll.
1304    fn overflow_scroll(mut self) -> Self {
1305        self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1306        self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1307        self
1308    }
1309
1310    /// Set the overflow x to scroll.
1311    fn overflow_x_scroll(mut self) -> Self {
1312        self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1313        self
1314    }
1315
1316    /// Set the overflow y to scroll.
1317    fn overflow_y_scroll(mut self) -> Self {
1318        self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1319        self
1320    }
1321
1322    /// Track the scroll state of this element with the given handle.
1323    fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1324        self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1325        self
1326    }
1327
1328    /// Track the scroll state of this element with the given handle.
1329    fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1330        self.interactivity().scroll_anchor = scroll_anchor;
1331        self
1332    }
1333
1334    /// Set the given styles to be applied when this element is active.
1335    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1336    where
1337        Self: Sized,
1338    {
1339        self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1340        self
1341    }
1342
1343    /// Set the given styles to be applied when this element's group is active.
1344    fn group_active(
1345        mut self,
1346        group_name: impl Into<SharedString>,
1347        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1348    ) -> Self
1349    where
1350        Self: Sized,
1351    {
1352        self.interactivity().group_active_style = Some(GroupStyle {
1353            group: group_name.into(),
1354            style: Box::new(f(StyleRefinement::default())),
1355        });
1356        self
1357    }
1358
1359    /// Bind the given callback to click events of this element.
1360    /// The fluent API equivalent to [`Interactivity::on_click`].
1361    ///
1362    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1363    fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1364    where
1365        Self: Sized,
1366    {
1367        self.interactivity().on_click(listener);
1368        self
1369    }
1370
1371    /// Bind the given callback to non-primary click events of this element.
1372    /// The fluent API equivalent to [`Interactivity::on_aux_click`].
1373    ///
1374    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1375    fn on_aux_click(
1376        mut self,
1377        listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1378    ) -> Self
1379    where
1380        Self: Sized,
1381    {
1382        self.interactivity().on_aux_click(listener);
1383        self
1384    }
1385
1386    /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
1387    /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
1388    /// the [`InteractiveElement::on_drag_move`] API.
1389    /// The callback also has access to the offset of triggering click from the origin of parent element.
1390    /// The fluent API equivalent to [`Interactivity::on_drag`].
1391    ///
1392    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1393    fn on_drag<T, W>(
1394        mut self,
1395        value: T,
1396        constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1397    ) -> Self
1398    where
1399        Self: Sized,
1400        T: 'static,
1401        W: 'static + Render,
1402    {
1403        self.interactivity().on_drag(value, constructor);
1404        self
1405    }
1406
1407    /// Bind the given callback on the hover start and end events of this element. Note that the boolean
1408    /// passed to the callback is true when the hover starts and false when it ends.
1409    /// The fluent API equivalent to [`Interactivity::on_hover`].
1410    ///
1411    /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1412    fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1413    where
1414        Self: Sized,
1415    {
1416        self.interactivity().on_hover(listener);
1417        self
1418    }
1419
1420    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
1421    /// The fluent API equivalent to [`Interactivity::tooltip`].
1422    fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1423    where
1424        Self: Sized,
1425    {
1426        self.interactivity().tooltip(build_tooltip);
1427        self
1428    }
1429
1430    /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
1431    /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
1432    /// the tooltip. The fluent API equivalent to [`Interactivity::hoverable_tooltip`].
1433    fn hoverable_tooltip(
1434        mut self,
1435        build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1436    ) -> Self
1437    where
1438        Self: Sized,
1439    {
1440        self.interactivity().hoverable_tooltip(build_tooltip);
1441        self
1442    }
1443
1444    /// 设置此元素提示框的显示延迟。
1445    /// 对应 [`Interactivity::tooltip_show_delay`] 的流畅 API。
1446    fn tooltip_show_delay(mut self, delay: Duration) -> Self
1447    where
1448        Self: Sized,
1449    {
1450        self.interactivity().tooltip_show_delay(delay);
1451        self
1452    }
1453}
1454
1455pub(crate) type MouseDownListener =
1456    Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1457pub(crate) type MouseUpListener =
1458    Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1459pub(crate) type MousePressureListener =
1460    Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1461pub(crate) type MouseMoveListener =
1462    Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1463
1464pub(crate) type ScrollWheelListener =
1465    Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1466
1467pub(crate) type PinchListener =
1468    Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1469
1470pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1471
1472pub(crate) type DragListener =
1473    Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>;
1474
1475type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1476
1477type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1478
1479pub(crate) struct TooltipBuilder {
1480    build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1481    hoverable: bool,
1482}
1483
1484pub(crate) type KeyDownListener =
1485    Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1486
1487pub(crate) type KeyUpListener =
1488    Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1489
1490pub(crate) type ModifiersChangedListener =
1491    Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1492
1493pub(crate) type ActionListener =
1494    Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1495
1496/// Construct a new [`Div`] element
1497#[track_caller]
1498pub fn div() -> Div {
1499    Div {
1500        interactivity: Interactivity::new(),
1501        children: SmallVec::default(),
1502        prepaint_listener: None,
1503        image_cache: None,
1504        prepaint_order_fn: None,
1505    }
1506}
1507
1508/// A [`Div`] element, the all-in-one element for building complex UIs in GPUI
1509pub struct Div {
1510    interactivity: Interactivity,
1511    children: SmallVec<[StackSafe<AnyElement>; 2]>,
1512    prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1513    image_cache: Option<Box<dyn ImageCacheProvider>>,
1514    prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1515}
1516
1517impl Div {
1518    /// Add a listener to be called when the children of this `Div` are prepainted.
1519    /// This allows you to store the [`Bounds`] of the children for later use.
1520    pub fn on_children_prepainted(
1521        mut self,
1522        listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1523    ) -> Self {
1524        self.prepaint_listener = Some(Box::new(listener));
1525        self
1526    }
1527
1528    /// Add an image cache at the location of this div in the element tree.
1529    pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1530        self.image_cache = Some(Box::new(cache));
1531        self
1532    }
1533
1534    /// Specify a function that determines the order in which children are prepainted.
1535    ///
1536    /// The function is called at prepaint time and should return a vector of child indices
1537    /// in the desired prepaint order. Each index should appear exactly once.
1538    ///
1539    /// This is useful when the prepaint of one child affects state that another child reads.
1540    /// For example, in split editor views, the editor with an autoscroll request should
1541    /// be prepainted first so its scroll position update is visible to the other editor.
1542    pub fn with_dynamic_prepaint_order(
1543        mut self,
1544        order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1545    ) -> Self {
1546        self.prepaint_order_fn = Some(Box::new(order_fn));
1547        self
1548    }
1549}
1550
1551/// A frame state for a `Div` element, which contains layout IDs for its children.
1552///
1553/// This struct is used internally by the `Div` element to manage the layout state of its children
1554/// during the UI update cycle. It holds a small vector of `LayoutId` values, each corresponding to
1555/// a child element of the `Div`. These IDs are used to query the layout engine for the computed
1556/// bounds of the children after the layout phase is complete.
1557pub struct DivFrameState {
1558    child_layout_ids: SmallVec<[LayoutId; 2]>,
1559}
1560
1561/// Interactivity state displayed an manipulated in the inspector.
1562#[derive(Clone)]
1563pub struct DivInspectorState {
1564    /// The inspected element's base style. This is used for both inspecting and modifying the
1565    /// state. In the future it will make sense to separate the read and write, possibly tracking
1566    /// the modifications.
1567    #[cfg(any(feature = "inspector", debug_assertions))]
1568    pub base_style: Box<StyleRefinement>,
1569    /// Inspects the bounds of the element.
1570    pub bounds: Bounds<Pixels>,
1571    /// Size of the children of the element, or `bounds.size` if it has no children.
1572    pub content_size: Size<Pixels>,
1573}
1574
1575impl Styled for Div {
1576    fn style(&mut self) -> &mut StyleRefinement {
1577        &mut self.interactivity.base_style
1578    }
1579}
1580
1581impl InteractiveElement for Div {
1582    fn interactivity(&mut self) -> &mut Interactivity {
1583        &mut self.interactivity
1584    }
1585}
1586
1587impl ParentElement for Div {
1588    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1589        self.children
1590            .extend(elements.into_iter().map(StackSafe::new))
1591    }
1592}
1593
1594impl Element for Div {
1595    type RequestLayoutState = DivFrameState;
1596    type PrepaintState = Option<Hitbox>;
1597
1598    fn id(&self) -> Option<ElementId> {
1599        self.interactivity.element_id.clone()
1600    }
1601
1602    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1603        self.interactivity.source_location()
1604    }
1605
1606    fn a11y_role(&self) -> Option<accesskit::Role> {
1607        self.interactivity
1608            .override_role
1609            .filter(|role| *role != accesskit::Role::GenericContainer)
1610    }
1611
1612    fn write_a11y_info(&self, node: &mut accesskit::Node) {
1613        self.interactivity.write_a11y_info(node);
1614    }
1615
1616    #[stacksafe]
1617    fn request_layout(
1618        &mut self,
1619        global_id: Option<&GlobalElementId>,
1620        inspector_id: Option<&InspectorElementId>,
1621        window: &mut Window,
1622        cx: &mut App,
1623    ) -> (LayoutId, Self::RequestLayoutState) {
1624        let mut child_layout_ids = SmallVec::new();
1625        let image_cache = self
1626            .image_cache
1627            .as_mut()
1628            .map(|provider| provider.provide(window, cx));
1629
1630        let layout_id = window.with_image_cache(image_cache, |window| {
1631            self.interactivity.request_layout(
1632                global_id,
1633                inspector_id,
1634                window,
1635                cx,
1636                |style, window, cx| {
1637                    window.with_text_style(style.text_style().cloned(), |window| {
1638                        child_layout_ids = self
1639                            .children
1640                            .iter_mut()
1641                            .map(|child| child.request_layout(window, cx))
1642                            .collect::<SmallVec<_>>();
1643                        window.request_layout(style, child_layout_ids.iter().copied(), cx)
1644                    })
1645                },
1646            )
1647        });
1648
1649        (layout_id, DivFrameState { child_layout_ids })
1650    }
1651
1652    #[stacksafe]
1653    fn prepaint(
1654        &mut self,
1655        global_id: Option<&GlobalElementId>,
1656        inspector_id: Option<&InspectorElementId>,
1657        bounds: Bounds<Pixels>,
1658        request_layout: &mut Self::RequestLayoutState,
1659        window: &mut Window,
1660        cx: &mut App,
1661    ) -> Option<Hitbox> {
1662        let image_cache = self
1663            .image_cache
1664            .as_mut()
1665            .map(|provider| provider.provide(window, cx));
1666
1667        let has_prepaint_listener = self.prepaint_listener.is_some();
1668        let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1669            request_layout.child_layout_ids.len()
1670        } else {
1671            0
1672        });
1673
1674        let mut child_min = point(Pixels::MAX, Pixels::MAX);
1675        let mut child_max = Point::default();
1676        if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1677            *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1678        }
1679        let content_size = if request_layout.child_layout_ids.is_empty() {
1680            bounds.size
1681        } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1682            let mut state = scroll_handle.0.borrow_mut();
1683            state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1684            for child_layout_id in &request_layout.child_layout_ids {
1685                let child_bounds = window.layout_bounds(*child_layout_id);
1686                child_min = child_min.min(&child_bounds.origin);
1687                child_max = child_max.max(&child_bounds.bottom_right());
1688                state.child_bounds.push(child_bounds);
1689            }
1690            (child_max - child_min).into()
1691        } else {
1692            for child_layout_id in &request_layout.child_layout_ids {
1693                let child_bounds = window.layout_bounds(*child_layout_id);
1694                child_min = child_min.min(&child_bounds.origin);
1695                child_max = child_max.max(&child_bounds.bottom_right());
1696
1697                if has_prepaint_listener {
1698                    children_bounds.push(child_bounds);
1699                }
1700            }
1701            (child_max - child_min).into()
1702        };
1703
1704        if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1705            scroll_handle.scroll_to_active_item();
1706        }
1707
1708        self.interactivity.prepaint(
1709            global_id,
1710            inspector_id,
1711            bounds,
1712            content_size,
1713            window,
1714            cx,
1715            |style, scroll_offset, hitbox, window, cx| {
1716                // skip children
1717                if style.display == Display::None {
1718                    return hitbox;
1719                }
1720
1721                window.with_image_cache(image_cache, |window| {
1722                    window.with_element_offset(scroll_offset, |window| {
1723                        if let Some(order_fn) = &self.prepaint_order_fn {
1724                            let order = order_fn(window, cx);
1725                            for idx in order {
1726                                if let Some(child) = self.children.get_mut(idx) {
1727                                    child.prepaint(window, cx);
1728                                }
1729                            }
1730                        } else {
1731                            for child in &mut self.children {
1732                                child.prepaint(window, cx);
1733                            }
1734                        }
1735                    });
1736
1737                    if let Some(listener) = self.prepaint_listener.as_ref() {
1738                        listener(children_bounds, window, cx);
1739                    }
1740                });
1741
1742                hitbox
1743            },
1744        )
1745    }
1746
1747    #[stacksafe]
1748    fn paint(
1749        &mut self,
1750        global_id: Option<&GlobalElementId>,
1751        inspector_id: Option<&InspectorElementId>,
1752        bounds: Bounds<Pixels>,
1753        _request_layout: &mut Self::RequestLayoutState,
1754        hitbox: &mut Option<Hitbox>,
1755        window: &mut Window,
1756        cx: &mut App,
1757    ) {
1758        let image_cache = self
1759            .image_cache
1760            .as_mut()
1761            .map(|provider| provider.provide(window, cx));
1762
1763        window.with_image_cache(image_cache, |window| {
1764            self.interactivity.paint(
1765                global_id,
1766                inspector_id,
1767                bounds,
1768                hitbox.as_ref(),
1769                window,
1770                cx,
1771                |style, window, cx| {
1772                    // skip children
1773                    if style.display == Display::None {
1774                        return;
1775                    }
1776
1777                    for child in &mut self.children {
1778                        child.paint(window, cx);
1779                    }
1780                },
1781            )
1782        });
1783    }
1784}
1785
1786impl IntoElement for Div {
1787    type Element = Self;
1788
1789    fn into_element(self) -> Self::Element {
1790        self
1791    }
1792}
1793
1794/// The interactivity struct. Powers all of the general-purpose
1795/// interactivity in the `Div` element.
1796#[derive(Default)]
1797pub struct Interactivity {
1798    /// The element ID of the element. In id is required to support a stateful subset of the interactivity such as on_click.
1799    pub element_id: Option<ElementId>,
1800    /// Whether the element was clicked. This will only be present after layout.
1801    pub active: Option<bool>,
1802    /// Whether the element was hovered. This will only be present after paint if an hitbox
1803    /// was created for the interactive element.
1804    pub hovered: Option<bool>,
1805    pub(crate) tooltip_id: Option<TooltipId>,
1806    pub(crate) content_size: Size<Pixels>,
1807    pub(crate) key_context: Option<KeyContext>,
1808    pub(crate) focusable: bool,
1809    pub(crate) tracked_focus_handle: Option<FocusHandle>,
1810    pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
1811    pub(crate) scroll_anchor: Option<ScrollAnchor>,
1812    pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
1813    pub(crate) group: Option<SharedString>,
1814    /// The base style of the element, before any modifications are applied
1815    /// by focus, active, etc.
1816    pub base_style: Box<StyleRefinement>,
1817    pub(crate) focus_style: Option<Box<StyleRefinement>>,
1818    pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
1819    pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
1820    pub(crate) hover_style: Option<Box<StyleRefinement>>,
1821    pub(crate) group_hover_style: Option<GroupStyle>,
1822    pub(crate) active_style: Option<Box<StyleRefinement>>,
1823    pub(crate) group_active_style: Option<GroupStyle>,
1824    pub(crate) drag_over_styles: Vec<(
1825        TypeId,
1826        Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
1827    )>,
1828    pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
1829    pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
1830    pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
1831    pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
1832    pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
1833    pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
1834    pub(crate) pinch_listeners: Vec<PinchListener>,
1835    pub(crate) key_down_listeners: Vec<KeyDownListener>,
1836    pub(crate) key_up_listeners: Vec<KeyUpListener>,
1837    pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
1838    pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
1839    pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
1840    pub(crate) can_drop_predicate: Option<CanDropPredicate>,
1841    pub(crate) click_listeners: Vec<ClickListener>,
1842    pub(crate) aux_click_listeners: Vec<ClickListener>,
1843    pub(crate) drag_listener: Option<(Arc<dyn Any>, DragListener)>,
1844    pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
1845    pub(crate) tooltip_builder: Option<TooltipBuilder>,
1846    pub(crate) tooltip_show_delay: Option<Duration>,
1847    pub(crate) window_control: Option<WindowControlArea>,
1848    pub(crate) hitbox_behavior: HitboxBehavior,
1849    pub(crate) tab_index: Option<isize>,
1850    pub(crate) tab_group: bool,
1851    pub(crate) tab_stop: bool,
1852    pub(crate) a11y_action_listeners:
1853        Vec<(accesskit::Action, crate::window::a11y::A11yActionListener)>,
1854    pub(crate) override_role: Option<accesskit::Role>,
1855    pub(crate) aria_label: Option<SharedString>,
1856    pub(crate) aria_selected: Option<bool>,
1857    pub(crate) aria_expanded: Option<bool>,
1858    pub(crate) aria_toggled: Option<accesskit::Toggled>,
1859    pub(crate) aria_numeric_value: Option<f64>,
1860    pub(crate) aria_min_numeric_value: Option<f64>,
1861    pub(crate) aria_max_numeric_value: Option<f64>,
1862    pub(crate) aria_orientation: Option<accesskit::Orientation>,
1863    pub(crate) aria_level: Option<usize>,
1864    pub(crate) aria_position_in_set: Option<usize>,
1865    pub(crate) aria_size_of_set: Option<usize>,
1866    pub(crate) aria_row_index: Option<usize>,
1867    pub(crate) aria_column_index: Option<usize>,
1868    pub(crate) aria_row_count: Option<usize>,
1869    pub(crate) aria_column_count: Option<usize>,
1870
1871    #[cfg(any(feature = "inspector", debug_assertions))]
1872    pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
1873
1874    #[cfg(any(test, feature = "test-support"))]
1875    pub(crate) debug_selector: Option<String>,
1876}
1877
1878impl Interactivity {
1879    /// Layout this element according to this interactivity state's configured styles
1880    pub fn request_layout(
1881        &mut self,
1882        global_id: Option<&GlobalElementId>,
1883        _inspector_id: Option<&InspectorElementId>,
1884        window: &mut Window,
1885        cx: &mut App,
1886        f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
1887    ) -> LayoutId {
1888        #[cfg(any(feature = "inspector", debug_assertions))]
1889        window.with_inspector_state(
1890            _inspector_id,
1891            cx,
1892            |inspector_state: &mut Option<DivInspectorState>, _window| {
1893                if let Some(inspector_state) = inspector_state {
1894                    self.base_style = inspector_state.base_style.clone();
1895                } else {
1896                    *inspector_state = Some(DivInspectorState {
1897                        base_style: self.base_style.clone(),
1898                        bounds: Default::default(),
1899                        content_size: Default::default(),
1900                    })
1901                }
1902            },
1903        );
1904
1905        window.with_optional_element_state::<InteractiveElementState, _>(
1906            global_id,
1907            |element_state, window| {
1908                let mut element_state =
1909                    element_state.map(|element_state| element_state.unwrap_or_default());
1910
1911                if let Some(element_state) = element_state.as_ref()
1912                    && cx.has_active_drag()
1913                {
1914                    if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
1915                        *pending_mouse_down.borrow_mut() = None;
1916                    }
1917                    if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1918                        *clicked_state.borrow_mut() = ElementClickedState::default();
1919                    }
1920                }
1921
1922                // Ensure we store a focus handle in our element state if we're focusable.
1923                // If there's an explicit focus handle we're tracking, use that. Otherwise
1924                // create a new handle and store it in the element state, which lives for as
1925                // as frames contain an element with this id.
1926                if self.focusable
1927                    && self.tracked_focus_handle.is_none()
1928                    && let Some(element_state) = element_state.as_mut()
1929                {
1930                    let mut handle = element_state
1931                        .focus_handle
1932                        .get_or_insert_with(|| cx.focus_handle())
1933                        .clone()
1934                        .tab_stop(self.tab_stop);
1935
1936                    if let Some(index) = self.tab_index {
1937                        handle = handle.tab_index(index);
1938                    }
1939
1940                    self.tracked_focus_handle = Some(handle);
1941                }
1942
1943                if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
1944                    self.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
1945                } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
1946                    || self.base_style.overflow.y == Some(Overflow::Scroll))
1947                    && let Some(element_state) = element_state.as_mut()
1948                {
1949                    self.scroll_offset = Some(
1950                        element_state
1951                            .scroll_offset
1952                            .get_or_insert_with(Rc::default)
1953                            .clone(),
1954                    );
1955                }
1956
1957                let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
1958                let layout_id = f(style, window, cx);
1959                (layout_id, element_state)
1960            },
1961        )
1962    }
1963
1964    /// Commit the bounds of this element according to this interactivity state's configured styles.
1965    pub fn prepaint<R>(
1966        &mut self,
1967        global_id: Option<&GlobalElementId>,
1968        _inspector_id: Option<&InspectorElementId>,
1969        bounds: Bounds<Pixels>,
1970        content_size: Size<Pixels>,
1971        window: &mut Window,
1972        cx: &mut App,
1973        f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
1974    ) -> R {
1975        self.content_size = content_size;
1976
1977        #[cfg(any(feature = "inspector", debug_assertions))]
1978        window.with_inspector_state(
1979            _inspector_id,
1980            cx,
1981            |inspector_state: &mut Option<DivInspectorState>, _window| {
1982                if let Some(inspector_state) = inspector_state {
1983                    inspector_state.bounds = bounds;
1984                    inspector_state.content_size = content_size;
1985                }
1986            },
1987        );
1988
1989        if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1990            window.set_focus_handle(focus_handle, cx);
1991            if window.a11y.is_active() {
1992                if let Some(global_id) = global_id {
1993                    let node_id = global_id.accesskit_node_id();
1994                    window.a11y.focus_ids.insert(node_id, focus_handle.id);
1995                    if focus_handle.is_focused(window) {
1996                        window.a11y.nodes.set_focus(node_id);
1997                    }
1998                }
1999            }
2000        }
2001        window.with_optional_element_state::<InteractiveElementState, _>(
2002            global_id,
2003            |element_state, window| {
2004                let mut element_state =
2005                    element_state.map(|element_state| element_state.unwrap_or_default());
2006                let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2007
2008                if let Some(element_state) = element_state.as_mut() {
2009                    if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2010                        let clicked_state = clicked_state.borrow();
2011                        self.active = Some(clicked_state.element);
2012                    }
2013                    if self.hover_style.is_some() || self.group_hover_style.is_some() {
2014                        element_state
2015                            .hover_state
2016                            .get_or_insert_with(Default::default);
2017                    }
2018                    if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2019                        if self.tooltip_builder.is_some() {
2020                            self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2021                        } else {
2022                            // If there is no longer a tooltip builder, remove the active tooltip.
2023                            element_state.active_tooltip.take();
2024                        }
2025                    }
2026                }
2027
2028                window.with_text_style(style.text_style().cloned(), |window| {
2029                    window.with_content_mask(
2030                        style.overflow_mask(bounds, window.rem_size()),
2031                        |window| {
2032                            let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2033                                Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2034                            } else {
2035                                None
2036                            };
2037
2038                            let scroll_offset =
2039                                self.clamp_scroll_position(bounds, &style, window, cx);
2040                            let result = f(&style, scroll_offset, hitbox, window, cx);
2041                            (result, element_state)
2042                        },
2043                    )
2044                })
2045            },
2046        )
2047    }
2048
2049    fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2050        self.hitbox_behavior != HitboxBehavior::Normal
2051            || self.window_control.is_some()
2052            || style.mouse_cursor.is_some()
2053            || self.group.is_some()
2054            || self.scroll_offset.is_some()
2055            || self.tracked_focus_handle.is_some()
2056            || self.hover_style.is_some()
2057            || self.group_hover_style.is_some()
2058            || self.hover_listener.is_some()
2059            || !self.mouse_up_listeners.is_empty()
2060            || !self.mouse_pressure_listeners.is_empty()
2061            || !self.mouse_down_listeners.is_empty()
2062            || !self.mouse_move_listeners.is_empty()
2063            || !self.click_listeners.is_empty()
2064            || !self.aux_click_listeners.is_empty()
2065            || !self.scroll_wheel_listeners.is_empty()
2066            || self.has_pinch_listeners()
2067            || self.drag_listener.is_some()
2068            || !self.drop_listeners.is_empty()
2069            || self.tooltip_builder.is_some()
2070            || window.is_inspector_picking(cx)
2071    }
2072
2073    fn clamp_scroll_position(
2074        &self,
2075        bounds: Bounds<Pixels>,
2076        style: &Style,
2077        window: &mut Window,
2078        _cx: &mut App,
2079    ) -> Point<Pixels> {
2080        fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2081            const ROUNDING_FACTOR: f32 = 100.0;
2082            (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2083        }
2084
2085        if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2086            let mut scroll_to_bottom = false;
2087            let mut tracked_scroll_handle = self
2088                .tracked_scroll_handle
2089                .as_ref()
2090                .map(|handle| handle.0.borrow_mut());
2091            if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2092                scroll_handle_state.overflow = style.overflow;
2093                scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2094            }
2095
2096            let rem_size = window.rem_size();
2097            let padding = style.padding.to_pixels(bounds.size.into(), rem_size);
2098            let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2099            // The floating point values produced by Taffy and ours often vary
2100            // slightly after ~5 decimal places. This can lead to cases where after
2101            // subtracting these, the container becomes scrollable for less than
2102            // 0.00000x pixels. As we generally don't benefit from a precision that
2103            // high for the maximum scroll, we round the scroll max to 2 decimal
2104            // places here.
2105            let padded_content_size = self.content_size + padding_size;
2106            let scroll_max = Point::from(padded_content_size - bounds.size)
2107                .map(round_to_two_decimals)
2108                .max(&Default::default());
2109            // Clamp scroll offset in case scroll max is smaller now (e.g., if children
2110            // were removed or the bounds became larger).
2111            let mut scroll_offset = scroll_offset.borrow_mut();
2112
2113            scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2114            if scroll_to_bottom {
2115                scroll_offset.y = -scroll_max.y;
2116            } else {
2117                scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2118            }
2119
2120            if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2121                scroll_handle_state.max_offset = scroll_max;
2122                scroll_handle_state.bounds = bounds;
2123            }
2124
2125            *scroll_offset
2126        } else {
2127            Point::default()
2128        }
2129    }
2130
2131    /// Paint this element according to this interactivity state's configured styles
2132    /// and bind the element's mouse and keyboard events.
2133    ///
2134    /// content_size is the size of the content of the element, which may be larger than the
2135    /// element's bounds if the element is scrollable.
2136    ///
2137    /// the final computed style will be passed to the provided function, along
2138    /// with the current scroll offset
2139    pub fn paint(
2140        &mut self,
2141        global_id: Option<&GlobalElementId>,
2142        _inspector_id: Option<&InspectorElementId>,
2143        bounds: Bounds<Pixels>,
2144        hitbox: Option<&Hitbox>,
2145        window: &mut Window,
2146        cx: &mut App,
2147        f: impl FnOnce(&Style, &mut Window, &mut App),
2148    ) {
2149        self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2150        window.with_optional_element_state::<InteractiveElementState, _>(
2151            global_id,
2152            |element_state, window| {
2153                let mut element_state =
2154                    element_state.map(|element_state| element_state.unwrap_or_default());
2155
2156                let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2157
2158                #[cfg(any(feature = "test-support", test))]
2159                if let Some(debug_selector) = &self.debug_selector {
2160                    window
2161                        .next_frame
2162                        .debug_bounds
2163                        .insert(debug_selector.clone(), bounds);
2164                }
2165
2166                self.paint_hover_group_handler(window, cx);
2167
2168                if style.visibility == Visibility::Hidden {
2169                    return ((), element_state);
2170                }
2171
2172                let mut tab_group = None;
2173                if self.tab_group {
2174                    tab_group = self.tab_index;
2175                }
2176                if let Some(focus_handle) = &self.tracked_focus_handle {
2177                    window.next_frame.tab_stops.insert(focus_handle);
2178                }
2179
2180                window.with_element_opacity(style.opacity, |window| {
2181                    style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2182                        window.with_text_style(style.text_style().cloned(), |window| {
2183                            window.with_content_mask(
2184                                style.overflow_mask(bounds, window.rem_size()),
2185                                |window| {
2186                                    window.with_tab_group(tab_group, |window| {
2187                                        if let Some(hitbox) = hitbox {
2188                                            #[cfg(debug_assertions)]
2189                                            self.paint_debug_info(
2190                                                global_id, hitbox, &style, window, cx,
2191                                            );
2192
2193                                            if let Some(drag) = cx.active_drag.as_ref() {
2194                                                if let Some(mouse_cursor) = drag.cursor_style {
2195                                                    window.set_window_cursor_style(mouse_cursor);
2196                                                }
2197                                            } else {
2198                                                if let Some(mouse_cursor) = style.mouse_cursor {
2199                                                    window.set_cursor_style(mouse_cursor, hitbox);
2200                                                }
2201                                            }
2202
2203                                            if let Some(group) = self.group.clone() {
2204                                                GroupHitboxes::push(group, hitbox.id, cx);
2205                                            }
2206
2207                                            if let Some(area) = self.window_control {
2208                                                window.insert_window_control_hitbox(
2209                                                    area,
2210                                                    hitbox.clone(),
2211                                                );
2212                                            }
2213
2214                                            self.paint_mouse_listeners(
2215                                                hitbox,
2216                                                element_state.as_mut(),
2217                                                window,
2218                                                cx,
2219                                            );
2220                                            self.paint_scroll_listener(hitbox, &style, window, cx);
2221                                        }
2222
2223                                        self.paint_keyboard_listeners(window, cx);
2224                                        if window.a11y.is_active() {
2225                                            if let Some(global_id) = global_id {
2226                                                if !self.a11y_action_listeners.is_empty() {
2227                                                    let node_id = global_id.accesskit_node_id();
2228                                                    for (action, listener) in
2229                                                        self.a11y_action_listeners.drain(..)
2230                                                    {
2231                                                        window.on_a11y_action(
2232                                                            node_id, action, listener,
2233                                                        );
2234                                                    }
2235                                                }
2236                                            }
2237                                        }
2238                                        f(&style, window, cx);
2239
2240                                        if let Some(_hitbox) = hitbox {
2241                                            #[cfg(any(feature = "inspector", debug_assertions))]
2242                                            window.insert_inspector_hitbox(
2243                                                _hitbox.id,
2244                                                _inspector_id,
2245                                                cx,
2246                                            );
2247
2248                                            if let Some(group) = self.group.as_ref() {
2249                                                GroupHitboxes::pop(group, cx);
2250                                            }
2251                                        }
2252                                    })
2253                                },
2254                            );
2255                        });
2256                    });
2257                });
2258
2259                ((), element_state)
2260            },
2261        );
2262    }
2263
2264    #[cfg(debug_assertions)]
2265    fn paint_debug_info(
2266        &self,
2267        global_id: Option<&GlobalElementId>,
2268        hitbox: &Hitbox,
2269        style: &Style,
2270        window: &mut Window,
2271        cx: &mut App,
2272    ) {
2273        use crate::{BorderStyle, TextAlign};
2274
2275        if let Some(global_id) = global_id
2276            && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2277            && hitbox.is_hovered(window)
2278        {
2279            const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2280            let element_id = format!("{global_id:?}");
2281            let str_len = element_id.len();
2282
2283            let render_debug_text = |window: &mut Window| {
2284                if let Some(text) = window
2285                    .text_system()
2286                    .shape_text(
2287                        element_id.into(),
2288                        FONT_SIZE,
2289                        &[window.text_style().to_run(str_len)],
2290                        None,
2291                        None,
2292                    )
2293                    .ok()
2294                    .and_then(|mut text| text.pop())
2295                {
2296                    text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2297                        .ok();
2298
2299                    let text_bounds = crate::Bounds {
2300                        origin: hitbox.origin,
2301                        size: text.size(FONT_SIZE),
2302                    };
2303                    if let Some(source_location) = self.source_location
2304                        && text_bounds.contains(&window.mouse_position())
2305                        && window.modifiers().secondary()
2306                    {
2307                        let secondary_held = window.modifiers().secondary();
2308                        window.on_key_event({
2309                            move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2310                                if e.modifiers.secondary() != secondary_held
2311                                    && text_bounds.contains(&window.mouse_position())
2312                                {
2313                                    window.refresh();
2314                                }
2315                            }
2316                        });
2317
2318                        let was_hovered = hitbox.is_hovered(window);
2319                        let current_view = window.current_view();
2320                        window.on_mouse_event({
2321                            let hitbox = hitbox.clone();
2322                            move |_: &MouseMoveEvent, phase, window, cx| {
2323                                if phase == DispatchPhase::Capture {
2324                                    let hovered = hitbox.is_hovered(window);
2325                                    if hovered != was_hovered {
2326                                        cx.notify(current_view)
2327                                    }
2328                                }
2329                            }
2330                        });
2331
2332                        window.on_mouse_event({
2333                            let hitbox = hitbox.clone();
2334                            move |e: &crate::MouseDownEvent, phase, window, cx| {
2335                                if text_bounds.contains(&e.position)
2336                                    && phase.capture()
2337                                    && hitbox.is_hovered(window)
2338                                {
2339                                    cx.stop_propagation();
2340                                    let Ok(dir) = std::env::current_dir() else {
2341                                        return;
2342                                    };
2343
2344                                    eprintln!(
2345                                        "This element was created at:\n{}:{}:{}",
2346                                        dir.join(source_location.file()).to_string_lossy(),
2347                                        source_location.line(),
2348                                        source_location.column()
2349                                    );
2350                                }
2351                            }
2352                        });
2353                        window.paint_quad(crate::outline(
2354                            crate::Bounds {
2355                                origin: hitbox.origin
2356                                    + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2357                                size: crate::Size {
2358                                    width: text_bounds.size.width,
2359                                    height: crate::px(1.),
2360                                },
2361                            },
2362                            crate::red(),
2363                            BorderStyle::default(),
2364                        ))
2365                    }
2366                }
2367            };
2368
2369            window.with_text_style(
2370                Some(crate::TextStyleRefinement {
2371                    color: Some(crate::red()),
2372                    line_height: Some(FONT_SIZE.into()),
2373                    background_color: Some(crate::white()),
2374                    ..Default::default()
2375                }),
2376                render_debug_text,
2377            )
2378        }
2379    }
2380
2381    fn paint_mouse_listeners(
2382        &mut self,
2383        hitbox: &Hitbox,
2384        element_state: Option<&mut InteractiveElementState>,
2385        window: &mut Window,
2386        cx: &mut App,
2387    ) {
2388        let is_focused = self
2389            .tracked_focus_handle
2390            .as_ref()
2391            .map(|handle| handle.is_focused(window))
2392            .unwrap_or(false);
2393
2394        // If this element can be focused, register a mouse down listener
2395        // that will automatically transfer focus when hitting the element.
2396        // This behavior can be suppressed by using `cx.prevent_default()`.
2397        if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2398            let hitbox = hitbox.clone();
2399            window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2400                if phase == DispatchPhase::Bubble
2401                    && hitbox.is_hovered(window)
2402                    && !window.default_prevented()
2403                {
2404                    window.focus(&focus_handle, cx);
2405                    // If there is a parent that is also focusable, prevent it
2406                    // from transferring focus because we already did so.
2407                    window.prevent_default();
2408                }
2409            });
2410        }
2411
2412        for listener in self.mouse_down_listeners.drain(..) {
2413            let hitbox = hitbox.clone();
2414            window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2415                listener(event, phase, &hitbox, window, cx);
2416            })
2417        }
2418
2419        for listener in self.mouse_up_listeners.drain(..) {
2420            let hitbox = hitbox.clone();
2421            window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2422                listener(event, phase, &hitbox, window, cx);
2423            })
2424        }
2425
2426        for listener in self.mouse_pressure_listeners.drain(..) {
2427            let hitbox = hitbox.clone();
2428            window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2429                listener(event, phase, &hitbox, window, cx);
2430            })
2431        }
2432
2433        for listener in self.mouse_move_listeners.drain(..) {
2434            let hitbox = hitbox.clone();
2435            window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2436                listener(event, phase, &hitbox, window, cx);
2437            })
2438        }
2439
2440        for listener in self.scroll_wheel_listeners.drain(..) {
2441            let hitbox = hitbox.clone();
2442            window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2443                listener(event, phase, &hitbox, window, cx);
2444            })
2445        }
2446
2447        for listener in self.pinch_listeners.drain(..) {
2448            let hitbox = hitbox.clone();
2449            window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2450                listener(event, phase, &hitbox, window, cx);
2451            })
2452        }
2453
2454        if self.hover_style.is_some()
2455            || self.base_style.mouse_cursor.is_some()
2456            || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2457        {
2458            let hitbox = hitbox.clone();
2459            let hover_state = self.hover_style.as_ref().and_then(|_| {
2460                element_state
2461                    .as_ref()
2462                    .and_then(|state| state.hover_state.as_ref())
2463                    .cloned()
2464            });
2465            let current_view = window.current_view();
2466
2467            window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2468                let hovered = hitbox.is_hovered(window);
2469                let was_hovered = hover_state
2470                    .as_ref()
2471                    .is_some_and(|state| state.borrow().element);
2472                if phase == DispatchPhase::Capture && hovered != was_hovered {
2473                    if let Some(hover_state) = &hover_state {
2474                        hover_state.borrow_mut().element = hovered;
2475                        cx.notify(current_view);
2476                    }
2477                }
2478            });
2479        }
2480
2481        if let Some(group_hover) = self.group_hover_style.as_ref() {
2482            if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2483                let hover_state = element_state
2484                    .as_ref()
2485                    .and_then(|element| element.hover_state.as_ref())
2486                    .cloned();
2487                let current_view = window.current_view();
2488
2489                window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2490                    let group_hovered = group_hitbox_id.is_hovered(window);
2491                    let was_group_hovered = hover_state
2492                        .as_ref()
2493                        .is_some_and(|state| state.borrow().group);
2494                    if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2495                        if let Some(hover_state) = &hover_state {
2496                            hover_state.borrow_mut().group = group_hovered;
2497                        }
2498                        cx.notify(current_view);
2499                    }
2500                });
2501            }
2502        }
2503
2504        let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2505
2506        let mut drag_listener = mem::take(&mut self.drag_listener);
2507        let drop_listeners = mem::take(&mut self.drop_listeners);
2508        let click_listeners = mem::take(&mut self.click_listeners);
2509        let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2510        let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2511
2512        if !drop_listeners.is_empty() {
2513            let hitbox = hitbox.clone();
2514            window.on_mouse_event({
2515                move |_: &MouseUpEvent, phase, window, cx| {
2516                    if let Some(drag) = &cx.active_drag
2517                        && phase == DispatchPhase::Bubble
2518                        && hitbox.is_hovered(window)
2519                    {
2520                        let drag_state_type = drag.value.as_ref().type_id();
2521                        for (drop_state_type, listener) in &drop_listeners {
2522                            if *drop_state_type == drag_state_type {
2523                                let drag = cx
2524                                    .active_drag
2525                                    .take()
2526                                    .expect("checked for type drag state type above");
2527
2528                                let mut can_drop = true;
2529                                if let Some(predicate) = &can_drop_predicate {
2530                                    can_drop = predicate(drag.value.as_ref(), window, cx);
2531                                }
2532
2533                                if can_drop {
2534                                    listener(drag.value.as_ref(), window, cx);
2535                                    window.refresh();
2536                                    cx.stop_propagation();
2537                                }
2538                            }
2539                        }
2540                    }
2541                }
2542            });
2543        }
2544
2545        if let Some(element_state) = element_state {
2546            if !click_listeners.is_empty()
2547                || !aux_click_listeners.is_empty()
2548                || drag_listener.is_some()
2549            {
2550                let pending_mouse_down = element_state
2551                    .pending_mouse_down
2552                    .get_or_insert_with(Default::default)
2553                    .clone();
2554
2555                let clicked_state = element_state
2556                    .clicked_state
2557                    .get_or_insert_with(Default::default)
2558                    .clone();
2559
2560                window.on_mouse_event({
2561                    let pending_mouse_down = pending_mouse_down.clone();
2562                    let hitbox = hitbox.clone();
2563                    let has_aux_click_listeners = !aux_click_listeners.is_empty();
2564                    move |event: &MouseDownEvent, phase, window, _cx| {
2565                        if phase == DispatchPhase::Bubble
2566                            && (event.button == MouseButton::Left || has_aux_click_listeners)
2567                            && hitbox.is_hovered(window)
2568                        {
2569                            *pending_mouse_down.borrow_mut() = Some(event.clone());
2570                            window.refresh();
2571                        }
2572                    }
2573                });
2574
2575                window.on_mouse_event({
2576                    let pending_mouse_down = pending_mouse_down.clone();
2577                    let hitbox = hitbox.clone();
2578                    move |event: &MouseMoveEvent, phase, window, cx| {
2579                        if phase == DispatchPhase::Capture {
2580                            return;
2581                        }
2582
2583                        let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2584                        if let Some(mouse_down) = pending_mouse_down.clone()
2585                            && !cx.has_active_drag()
2586                            && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2587                            && let Some((drag_value, drag_listener)) = drag_listener.take()
2588                            && mouse_down.button == MouseButton::Left
2589                        {
2590                            *clicked_state.borrow_mut() = ElementClickedState::default();
2591                            let cursor_offset = event.position - hitbox.origin;
2592                            let drag =
2593                                (drag_listener)(drag_value.as_ref(), cursor_offset, window, cx);
2594                            cx.active_drag = Some(AnyDrag {
2595                                view: drag,
2596                                value: drag_value,
2597                                cursor_offset,
2598                                cursor_style: drag_cursor_style,
2599                            });
2600                            pending_mouse_down.take();
2601                            window.refresh();
2602                            cx.stop_propagation();
2603                        }
2604                    }
2605                });
2606
2607                if is_focused {
2608                    // Press enter, space to trigger click, when the element is focused.
2609                    window.on_key_event({
2610                        let click_listeners = click_listeners.clone();
2611                        let hitbox = hitbox.clone();
2612                        move |event: &KeyUpEvent, phase, window, cx| {
2613                            if phase.bubble() && !window.default_prevented() {
2614                                let stroke = &event.keystroke;
2615                                let keyboard_button = if stroke.key.eq("enter") {
2616                                    Some(KeyboardButton::Enter)
2617                                } else if stroke.key.eq("space") {
2618                                    Some(KeyboardButton::Space)
2619                                } else {
2620                                    None
2621                                };
2622
2623                                if let Some(button) = keyboard_button
2624                                    && !stroke.modifiers.modified()
2625                                {
2626                                    let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2627                                        button,
2628                                        bounds: hitbox.bounds,
2629                                    });
2630
2631                                    for listener in &click_listeners {
2632                                        listener(&click_event, window, cx);
2633                                    }
2634                                }
2635                            }
2636                        }
2637                    });
2638                }
2639
2640                window.on_mouse_event({
2641                    let mut captured_mouse_down = None;
2642                    let hitbox = hitbox.clone();
2643                    move |event: &MouseUpEvent, phase, window, cx| match phase {
2644                        // Clear the pending mouse down during the capture phase,
2645                        // so that it happens even if another event handler stops
2646                        // propagation.
2647                        DispatchPhase::Capture => {
2648                            let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2649                            if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2650                                captured_mouse_down = pending_mouse_down.take();
2651                                window.refresh();
2652                            } else if pending_mouse_down.is_some() {
2653                                // Clear the pending mouse down event (without firing click handlers)
2654                                // if the hitbox is not being hovered.
2655                                // This avoids dragging elements that changed their position
2656                                // immediately after being clicked.
2657                                // See https://github.com/zed-industries/zed/issues/24600 for more details
2658                                pending_mouse_down.take();
2659                                window.refresh();
2660                            }
2661                        }
2662                        // Fire click handlers during the bubble phase.
2663                        DispatchPhase::Bubble => {
2664                            if let Some(mouse_down) = captured_mouse_down.take() {
2665                                let btn = mouse_down.button;
2666
2667                                let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2668                                    down: mouse_down,
2669                                    up: event.clone(),
2670                                });
2671
2672                                match btn {
2673                                    MouseButton::Left => {
2674                                        for listener in &click_listeners {
2675                                            listener(&mouse_click, window, cx);
2676                                        }
2677                                    }
2678                                    _ => {
2679                                        for listener in &aux_click_listeners {
2680                                            listener(&mouse_click, window, cx);
2681                                        }
2682                                    }
2683                                }
2684                            }
2685                        }
2686                    }
2687                });
2688            }
2689
2690            if let Some(hover_listener) = self.hover_listener.take() {
2691                let hitbox = hitbox.clone();
2692                let was_hovered = element_state
2693                    .hover_listener_state
2694                    .get_or_insert_with(Default::default)
2695                    .clone();
2696                let has_mouse_down = element_state
2697                    .pending_mouse_down
2698                    .get_or_insert_with(Default::default)
2699                    .clone();
2700
2701                window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2702                    if phase != DispatchPhase::Bubble {
2703                        return;
2704                    }
2705                    let is_hovered = has_mouse_down.borrow().is_none()
2706                        && !cx.has_active_drag()
2707                        && hitbox.is_hovered(window);
2708                    let mut was_hovered = was_hovered.borrow_mut();
2709
2710                    if is_hovered != *was_hovered {
2711                        *was_hovered = is_hovered;
2712                        drop(was_hovered);
2713
2714                        hover_listener(&is_hovered, window, cx);
2715                    }
2716                });
2717            }
2718
2719            if let Some(tooltip_builder) = self.tooltip_builder.take() {
2720                let active_tooltip = element_state
2721                    .active_tooltip
2722                    .get_or_insert_with(Default::default)
2723                    .clone();
2724                let pending_mouse_down = element_state
2725                    .pending_mouse_down
2726                    .get_or_insert_with(Default::default)
2727                    .clone();
2728
2729                let tooltip_is_hoverable = tooltip_builder.hoverable;
2730                let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
2731                    Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
2732                });
2733                // Use bounds instead of testing hitbox since this is called during prepaint.
2734                let check_is_hovered_during_prepaint = Rc::new({
2735                    let pending_mouse_down = pending_mouse_down.clone();
2736                    let source_bounds = hitbox.bounds;
2737                    move |window: &Window| {
2738                        !window.last_input_was_keyboard()
2739                            && pending_mouse_down.borrow().is_none()
2740                            && source_bounds.contains(&window.mouse_position())
2741                    }
2742                });
2743                let check_is_hovered = Rc::new({
2744                    let hitbox = hitbox.clone();
2745                    move |window: &Window| {
2746                        pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
2747                    }
2748                });
2749                register_tooltip_mouse_handlers(
2750                    &active_tooltip,
2751                    self.tooltip_id,
2752                    build_tooltip,
2753                    check_is_hovered,
2754                    check_is_hovered_during_prepaint,
2755                    self.tooltip_show_delay,
2756                    window,
2757                );
2758            }
2759
2760            // We unconditionally bind both the mouse up and mouse down active state handlers
2761            // Because we might not get a chance to render a frame before the mouse up event arrives.
2762            let active_state = element_state
2763                .clicked_state
2764                .get_or_insert_with(Default::default)
2765                .clone();
2766
2767            {
2768                let active_state = active_state.clone();
2769                window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
2770                    if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
2771                        *active_state.borrow_mut() = ElementClickedState::default();
2772                        window.refresh();
2773                    }
2774                });
2775            }
2776
2777            {
2778                let active_group_hitbox = self
2779                    .group_active_style
2780                    .as_ref()
2781                    .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
2782                let hitbox = hitbox.clone();
2783                window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
2784                    if phase == DispatchPhase::Bubble && !window.default_prevented() {
2785                        let group_hovered = active_group_hitbox
2786                            .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
2787                        let element_hovered = hitbox.is_hovered(window);
2788                        if group_hovered || element_hovered {
2789                            *active_state.borrow_mut() = ElementClickedState {
2790                                group: group_hovered,
2791                                element: element_hovered,
2792                            };
2793                            window.refresh();
2794                        }
2795                    }
2796                });
2797            }
2798        }
2799    }
2800
2801    fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
2802        let key_down_listeners = mem::take(&mut self.key_down_listeners);
2803        let key_up_listeners = mem::take(&mut self.key_up_listeners);
2804        let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
2805        let action_listeners = mem::take(&mut self.action_listeners);
2806        if let Some(context) = self.key_context.clone() {
2807            window.set_key_context(context);
2808        }
2809
2810        for listener in key_down_listeners {
2811            window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
2812                listener(event, phase, window, cx);
2813            })
2814        }
2815
2816        for listener in key_up_listeners {
2817            window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
2818                listener(event, phase, window, cx);
2819            })
2820        }
2821
2822        for listener in modifiers_changed_listeners {
2823            window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
2824                listener(event, window, cx);
2825            })
2826        }
2827
2828        for (action_type, listener) in action_listeners {
2829            window.on_action(action_type, listener)
2830        }
2831    }
2832
2833    fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
2834        let group_hitbox = self
2835            .group_hover_style
2836            .as_ref()
2837            .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
2838
2839        if let Some(group_hitbox) = group_hitbox {
2840            let was_hovered = group_hitbox.is_hovered(window);
2841            let current_view = window.current_view();
2842            window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2843                let hovered = group_hitbox.is_hovered(window);
2844                if phase == DispatchPhase::Capture && hovered != was_hovered {
2845                    cx.notify(current_view);
2846                }
2847            });
2848        }
2849    }
2850
2851    fn paint_scroll_listener(
2852        &self,
2853        hitbox: &Hitbox,
2854        style: &Style,
2855        window: &mut Window,
2856        _cx: &mut App,
2857    ) {
2858        if let Some(scroll_offset) = self.scroll_offset.clone() {
2859            let overflow = style.overflow;
2860            let allow_concurrent_scroll = style.allow_concurrent_scroll;
2861            let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
2862            let line_height = window.line_height();
2863            let hitbox = hitbox.clone();
2864            let current_view = window.current_view();
2865            window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2866                if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
2867                    let mut scroll_offset = scroll_offset.borrow_mut();
2868                    let old_scroll_offset = *scroll_offset;
2869                    let delta = event.delta.pixel_delta(line_height);
2870
2871                    let mut delta_x = Pixels::ZERO;
2872                    if overflow.x == Overflow::Scroll {
2873                        if !delta.x.is_zero() {
2874                            delta_x = delta.x;
2875                        } else if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll {
2876                            delta_x = delta.y;
2877                        }
2878                    }
2879                    let mut delta_y = Pixels::ZERO;
2880                    if overflow.y == Overflow::Scroll {
2881                        if !delta.y.is_zero() {
2882                            delta_y = delta.y;
2883                        } else if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll {
2884                            delta_y = delta.x;
2885                        }
2886                    }
2887                    if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
2888                        if delta_x.abs() > delta_y.abs() {
2889                            delta_y = Pixels::ZERO;
2890                        } else {
2891                            delta_x = Pixels::ZERO;
2892                        }
2893                    }
2894                    scroll_offset.y += delta_y;
2895                    scroll_offset.x += delta_x;
2896                    if *scroll_offset != old_scroll_offset {
2897                        cx.notify(current_view);
2898                    }
2899                }
2900            });
2901        }
2902    }
2903
2904    /// Compute the visual style for this element, based on the current bounds and the element's state.
2905    pub fn compute_style(
2906        &self,
2907        global_id: Option<&GlobalElementId>,
2908        hitbox: Option<&Hitbox>,
2909        window: &mut Window,
2910        cx: &mut App,
2911    ) -> Style {
2912        window.with_optional_element_state(global_id, |element_state, window| {
2913            let mut element_state =
2914                element_state.map(|element_state| element_state.unwrap_or_default());
2915            let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2916            (style, element_state)
2917        })
2918    }
2919
2920    /// Called from internal methods that have already called with_element_state.
2921    fn compute_style_internal(
2922        &self,
2923        hitbox: Option<&Hitbox>,
2924        element_state: Option<&mut InteractiveElementState>,
2925        window: &mut Window,
2926        cx: &mut App,
2927    ) -> Style {
2928        let mut style = Style::default();
2929        style.refine(&self.base_style);
2930
2931        if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2932            if let Some(in_focus_style) = self.in_focus_style.as_ref()
2933                && focus_handle.within_focused(window, cx)
2934            {
2935                style.refine(in_focus_style);
2936            }
2937
2938            if let Some(focus_style) = self.focus_style.as_ref()
2939                && focus_handle.is_focused(window)
2940            {
2941                style.refine(focus_style);
2942            }
2943
2944            if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
2945                && focus_handle.is_focused(window)
2946                && window.last_input_was_keyboard()
2947            {
2948                style.refine(focus_visible_style);
2949            }
2950        }
2951
2952        if !cx.has_active_drag() {
2953            if let Some(group_hover) = self.group_hover_style.as_ref() {
2954                let is_group_hovered =
2955                    if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2956                        group_hitbox_id.is_hovered(window)
2957                    } else if let Some(element_state) = element_state.as_ref() {
2958                        element_state
2959                            .hover_state
2960                            .as_ref()
2961                            .map(|state| state.borrow().group)
2962                            .unwrap_or(false)
2963                    } else {
2964                        false
2965                    };
2966
2967                if is_group_hovered {
2968                    style.refine(&group_hover.style);
2969                }
2970            }
2971
2972            if let Some(hover_style) = self.hover_style.as_ref() {
2973                let is_hovered = if let Some(hitbox) = hitbox {
2974                    hitbox.is_hovered(window)
2975                } else if let Some(element_state) = element_state.as_ref() {
2976                    element_state
2977                        .hover_state
2978                        .as_ref()
2979                        .map(|state| state.borrow().element)
2980                        .unwrap_or(false)
2981                } else {
2982                    false
2983                };
2984
2985                if is_hovered {
2986                    style.refine(hover_style);
2987                }
2988            }
2989        }
2990
2991        if let Some(hitbox) = hitbox {
2992            if let Some(drag) = cx.active_drag.take() {
2993                let mut can_drop = true;
2994                if let Some(can_drop_predicate) = &self.can_drop_predicate {
2995                    can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
2996                }
2997
2998                if can_drop {
2999                    for (state_type, group_drag_style) in &self.group_drag_over_styles {
3000                        if let Some(group_hitbox_id) =
3001                            GroupHitboxes::get(&group_drag_style.group, cx)
3002                            && *state_type == drag.value.as_ref().type_id()
3003                            && group_hitbox_id.is_hovered(window)
3004                        {
3005                            style.refine(&group_drag_style.style);
3006                        }
3007                    }
3008
3009                    for (state_type, build_drag_over_style) in &self.drag_over_styles {
3010                        if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3011                        {
3012                            style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3013                        }
3014                    }
3015                }
3016
3017                style.mouse_cursor = drag.cursor_style;
3018                cx.active_drag = Some(drag);
3019            }
3020        }
3021
3022        if let Some(element_state) = element_state {
3023            let clicked_state = element_state
3024                .clicked_state
3025                .get_or_insert_with(Default::default)
3026                .borrow();
3027            if clicked_state.group
3028                && let Some(group) = self.group_active_style.as_ref()
3029            {
3030                style.refine(&group.style)
3031            }
3032
3033            if let Some(active_style) = self.active_style.as_ref()
3034                && clicked_state.element
3035            {
3036                style.refine(active_style)
3037            }
3038        }
3039
3040        style
3041    }
3042
3043    pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3044        if let Some(label) = &self.aria_label {
3045            node.set_label(label.to_string());
3046        }
3047        if let Some(selected) = self.aria_selected {
3048            node.set_selected(selected);
3049        }
3050        if let Some(expanded) = self.aria_expanded {
3051            node.set_expanded(expanded);
3052        }
3053        if let Some(toggled) = self.aria_toggled {
3054            node.set_toggled(toggled);
3055        }
3056        if let Some(value) = self.aria_numeric_value {
3057            node.set_numeric_value(value);
3058        }
3059        if let Some(value) = self.aria_min_numeric_value {
3060            node.set_min_numeric_value(value);
3061        }
3062        if let Some(value) = self.aria_max_numeric_value {
3063            node.set_max_numeric_value(value);
3064        }
3065        if let Some(orientation) = self.aria_orientation {
3066            node.set_orientation(orientation);
3067        }
3068        if let Some(level) = self.aria_level {
3069            node.set_level(level);
3070        }
3071        if let Some(position) = self.aria_position_in_set {
3072            node.set_position_in_set(position);
3073        }
3074        if let Some(size) = self.aria_size_of_set {
3075            node.set_size_of_set(size);
3076        }
3077        if let Some(index) = self.aria_row_index {
3078            node.set_row_index(index);
3079        }
3080        if let Some(index) = self.aria_column_index {
3081            node.set_column_index(index);
3082        }
3083        if let Some(count) = self.aria_row_count {
3084            node.set_row_count(count);
3085        }
3086        if let Some(count) = self.aria_column_count {
3087            node.set_column_count(count);
3088        }
3089        if !self.click_listeners.is_empty() {
3090            node.add_action(accesskit::Action::Click);
3091        }
3092        if self.tracked_focus_handle.is_some() || self.focusable {
3093            node.add_action(accesskit::Action::Focus);
3094        }
3095        for (action, _) in &self.a11y_action_listeners {
3096            node.add_action(*action);
3097        }
3098    }
3099}
3100
3101/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks
3102/// and scroll offsets.
3103#[derive(Default)]
3104pub struct InteractiveElementState {
3105    pub(crate) focus_handle: Option<FocusHandle>,
3106    pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3107    pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3108    pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3109    pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3110    pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3111    pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3112}
3113
3114/// Whether or not the element or a group that contains it is clicked by the mouse.
3115#[derive(Copy, Clone, Default, Eq, PartialEq)]
3116pub struct ElementClickedState {
3117    /// True if this element's group has been clicked, false otherwise
3118    pub group: bool,
3119
3120    /// True if this element has been clicked, false otherwise
3121    pub element: bool,
3122}
3123
3124impl ElementClickedState {
3125    fn is_clicked(&self) -> bool {
3126        self.group || self.element
3127    }
3128}
3129
3130/// Whether or not the element or a group that contains it is hovered.
3131#[derive(Copy, Clone, Default, Eq, PartialEq)]
3132pub struct ElementHoverState {
3133    /// True if this element's group is hovered, false otherwise
3134    pub group: bool,
3135
3136    /// True if this element is hovered, false otherwise
3137    pub element: bool,
3138}
3139
3140pub(crate) enum ActiveTooltip {
3141    /// Currently delaying before showing the tooltip.
3142    WaitingForShow { _task: Task<()> },
3143    /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
3144    Visible {
3145        tooltip: AnyTooltip,
3146        is_hoverable: bool,
3147    },
3148    /// Tooltip is visible and hoverable, but the mouse is no longer hovering. Currently delaying
3149    /// before hiding it.
3150    WaitingForHide {
3151        tooltip: AnyTooltip,
3152        _task: Task<()>,
3153    },
3154}
3155
3156pub(crate) fn clear_active_tooltip(
3157    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3158    window: &mut Window,
3159) {
3160    match active_tooltip.borrow_mut().take() {
3161        None => {}
3162        Some(ActiveTooltip::WaitingForShow { .. }) => {}
3163        Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3164        Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3165    }
3166}
3167
3168pub(crate) fn clear_active_tooltip_if_not_hoverable(
3169    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3170    window: &mut Window,
3171) {
3172    let should_clear = match active_tooltip.borrow().as_ref() {
3173        None => false,
3174        Some(ActiveTooltip::WaitingForShow { .. }) => false,
3175        Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3176        Some(ActiveTooltip::WaitingForHide { .. }) => false,
3177    };
3178    if should_clear {
3179        active_tooltip.borrow_mut().take();
3180        window.refresh();
3181    }
3182}
3183
3184pub(crate) fn set_tooltip_on_window(
3185    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3186    window: &mut Window,
3187) -> Option<TooltipId> {
3188    let tooltip = match active_tooltip.borrow().as_ref() {
3189        None => return None,
3190        Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3191        Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3192        Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3193    };
3194    Some(window.set_tooltip(tooltip))
3195}
3196
3197pub(crate) fn register_tooltip_mouse_handlers(
3198    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3199    tooltip_id: Option<TooltipId>,
3200    build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3201    check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3202    check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3203    show_delay: Option<Duration>,
3204    window: &mut Window,
3205) {
3206    let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3207
3208    window.on_mouse_event({
3209        let active_tooltip = active_tooltip.clone();
3210        let build_tooltip = build_tooltip.clone();
3211        let check_is_hovered = check_is_hovered.clone();
3212        move |_: &MouseMoveEvent, phase, window, cx| {
3213            handle_tooltip_mouse_move(
3214                &active_tooltip,
3215                &build_tooltip,
3216                &check_is_hovered,
3217                &check_is_hovered_during_prepaint,
3218                phase,
3219                show_delay,
3220                window,
3221                cx,
3222            )
3223        }
3224    });
3225
3226    window.on_mouse_event({
3227        let active_tooltip = active_tooltip.clone();
3228        move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3229            if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3230                clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3231            }
3232        }
3233    });
3234
3235    window.on_mouse_event({
3236        let active_tooltip = active_tooltip.clone();
3237        move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
3238            if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3239                clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3240            }
3241        }
3242    });
3243}
3244
3245/// Handles displaying tooltips when an element is hovered.
3246///
3247/// The mouse hovering logic also relies on being called from window prepaint in order to handle the
3248/// case where the element the tooltip is on is not rendered - in that case its mouse listeners are
3249/// also not registered. During window prepaint, the hitbox information is not available, so
3250/// `check_is_hovered_during_prepaint` is used which bases the check off of the absolute bounds of
3251/// the element.
3252///
3253/// TODO: There's a minor bug due to the use of absolute bounds while checking during prepaint - it
3254/// does not know if the hitbox is occluded. In the case where a tooltip gets displayed and then
3255/// gets occluded after display, it will stick around until the mouse exits the hover bounds.
3256fn handle_tooltip_mouse_move(
3257    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3258    build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3259    check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3260    check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3261    phase: DispatchPhase,
3262    show_delay: Duration,
3263    window: &mut Window,
3264    cx: &mut App,
3265) {
3266    // Separates logic for what mutation should occur from applying it, to avoid overlapping
3267    // RefCell borrows.
3268    enum Action {
3269        None,
3270        CancelShow,
3271        ScheduleShow,
3272    }
3273
3274    let action = match active_tooltip.borrow().as_ref() {
3275        None => {
3276            let is_hovered = check_is_hovered(window);
3277            if is_hovered && phase.bubble() {
3278                Action::ScheduleShow
3279            } else {
3280                Action::None
3281            }
3282        }
3283        Some(ActiveTooltip::WaitingForShow { .. }) => {
3284            let is_hovered = check_is_hovered(window);
3285            if is_hovered {
3286                Action::None
3287            } else {
3288                Action::CancelShow
3289            }
3290        }
3291        // These are handled in check_visible_and_update.
3292        Some(ActiveTooltip::Visible { .. }) | Some(ActiveTooltip::WaitingForHide { .. }) => {
3293            Action::None
3294        }
3295    };
3296
3297    match action {
3298        Action::None => {}
3299        Action::CancelShow => {
3300            // Cancel waiting to show tooltip when it is no longer hovered.
3301            active_tooltip.borrow_mut().take();
3302        }
3303        Action::ScheduleShow => {
3304            let delayed_show_task = window.spawn(cx, {
3305                let weak_active_tooltip = Rc::downgrade(active_tooltip);
3306                let build_tooltip = build_tooltip.clone();
3307                let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3308                async move |cx| {
3309                    cx.background_executor().timer(show_delay).await;
3310                    let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3311                        return;
3312                    };
3313                    cx.update(|window, cx| {
3314                        let new_tooltip =
3315                            build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3316                                let weak_active_tooltip = Rc::downgrade(&active_tooltip);
3317                                ActiveTooltip::Visible {
3318                                    tooltip: AnyTooltip {
3319                                        view,
3320                                        mouse_position: window.mouse_position(),
3321                                        check_visible_and_update: Rc::new(
3322                                            move |tooltip_bounds, window, cx| {
3323                                                let Some(active_tooltip) =
3324                                                    weak_active_tooltip.upgrade()
3325                                                else {
3326                                                    return false;
3327                                                };
3328                                                handle_tooltip_check_visible_and_update(
3329                                                    &active_tooltip,
3330                                                    tooltip_is_hoverable,
3331                                                    &check_is_hovered_during_prepaint,
3332                                                    tooltip_bounds,
3333                                                    window,
3334                                                    cx,
3335                                                )
3336                                            },
3337                                        ),
3338                                    },
3339                                    is_hoverable: tooltip_is_hoverable,
3340                                }
3341                            });
3342                        *active_tooltip.borrow_mut() = new_tooltip;
3343                        window.refresh();
3344                    })
3345                    .ok();
3346                }
3347            });
3348            active_tooltip
3349                .borrow_mut()
3350                .replace(ActiveTooltip::WaitingForShow {
3351                    _task: delayed_show_task,
3352                });
3353        }
3354    }
3355}
3356
3357/// Returns a callback which will be called by window prepaint to update tooltip visibility. The
3358/// purpose of doing this logic here instead of the mouse move handler is that the mouse move
3359/// handler won't get called when the element is not painted (e.g. via use of `visible_on_hover`).
3360fn handle_tooltip_check_visible_and_update(
3361    active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3362    tooltip_is_hoverable: bool,
3363    check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3364    tooltip_bounds: Bounds<Pixels>,
3365    window: &mut Window,
3366    cx: &mut App,
3367) -> bool {
3368    // Separates logic for what mutation should occur from applying it, to avoid overlapping RefCell
3369    // borrows.
3370    enum Action {
3371        None,
3372        Hide,
3373        ScheduleHide(AnyTooltip),
3374        CancelHide(AnyTooltip),
3375    }
3376
3377    let is_hovered = check_is_hovered(window)
3378        || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
3379    let action = match active_tooltip.borrow().as_ref() {
3380        Some(ActiveTooltip::Visible { tooltip, .. }) => {
3381            if is_hovered {
3382                Action::None
3383            } else {
3384                if tooltip_is_hoverable {
3385                    Action::ScheduleHide(tooltip.clone())
3386                } else {
3387                    Action::Hide
3388                }
3389            }
3390        }
3391        Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
3392            if is_hovered {
3393                Action::CancelHide(tooltip.clone())
3394            } else {
3395                Action::None
3396            }
3397        }
3398        None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
3399    };
3400
3401    match action {
3402        Action::None => {}
3403        Action::Hide => clear_active_tooltip(active_tooltip, window),
3404        Action::ScheduleHide(tooltip) => {
3405            let delayed_hide_task = window.spawn(cx, {
3406                let weak_active_tooltip = Rc::downgrade(active_tooltip);
3407                async move |cx| {
3408                    cx.background_executor()
3409                        .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
3410                        .await;
3411                    let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3412                        return;
3413                    };
3414                    if active_tooltip.borrow_mut().take().is_some() {
3415                        cx.update(|window, _cx| window.refresh()).ok();
3416                    }
3417                }
3418            });
3419            active_tooltip
3420                .borrow_mut()
3421                .replace(ActiveTooltip::WaitingForHide {
3422                    tooltip,
3423                    _task: delayed_hide_task,
3424                });
3425        }
3426        Action::CancelHide(tooltip) => {
3427            // Cancel waiting to hide tooltip when it becomes hovered.
3428            active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
3429                tooltip,
3430                is_hoverable: true,
3431            });
3432        }
3433    }
3434
3435    active_tooltip.borrow().is_some()
3436}
3437
3438#[derive(Default)]
3439pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
3440
3441impl Global for GroupHitboxes {}
3442
3443impl GroupHitboxes {
3444    pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
3445        cx.default_global::<Self>()
3446            .0
3447            .get(name)
3448            .and_then(|bounds_stack| bounds_stack.last())
3449            .cloned()
3450    }
3451
3452    pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
3453        cx.default_global::<Self>()
3454            .0
3455            .entry(name)
3456            .or_default()
3457            .push(hitbox_id);
3458    }
3459
3460    pub fn pop(name: &SharedString, cx: &mut App) {
3461        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
3462    }
3463}
3464
3465/// A wrapper around an element that can store state, produced after assigning an ElementId.
3466pub struct Stateful<E> {
3467    pub(crate) element: E,
3468}
3469
3470impl<E> Styled for Stateful<E>
3471where
3472    E: Styled,
3473{
3474    fn style(&mut self) -> &mut StyleRefinement {
3475        self.element.style()
3476    }
3477}
3478
3479impl<E> StatefulInteractiveElement for Stateful<E>
3480where
3481    E: Element,
3482    Self: InteractiveElement,
3483{
3484}
3485
3486impl<E> InteractiveElement for Stateful<E>
3487where
3488    E: InteractiveElement,
3489{
3490    fn interactivity(&mut self) -> &mut Interactivity {
3491        self.element.interactivity()
3492    }
3493}
3494
3495impl<E> Element for Stateful<E>
3496where
3497    E: Element,
3498{
3499    type RequestLayoutState = E::RequestLayoutState;
3500    type PrepaintState = E::PrepaintState;
3501
3502    fn id(&self) -> Option<ElementId> {
3503        self.element.id()
3504    }
3505
3506    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3507        self.element.source_location()
3508    }
3509
3510    fn a11y_role(&self) -> Option<accesskit::Role> {
3511        self.element.a11y_role()
3512    }
3513
3514    fn write_a11y_info(&self, node: &mut accesskit::Node) {
3515        self.element.write_a11y_info(node);
3516    }
3517
3518    fn request_layout(
3519        &mut self,
3520        id: Option<&GlobalElementId>,
3521        inspector_id: Option<&InspectorElementId>,
3522        window: &mut Window,
3523        cx: &mut App,
3524    ) -> (LayoutId, Self::RequestLayoutState) {
3525        self.element.request_layout(id, inspector_id, window, cx)
3526    }
3527
3528    fn prepaint(
3529        &mut self,
3530        id: Option<&GlobalElementId>,
3531        inspector_id: Option<&InspectorElementId>,
3532        bounds: Bounds<Pixels>,
3533        state: &mut Self::RequestLayoutState,
3534        window: &mut Window,
3535        cx: &mut App,
3536    ) -> E::PrepaintState {
3537        self.element
3538            .prepaint(id, inspector_id, bounds, state, window, cx)
3539    }
3540
3541    fn paint(
3542        &mut self,
3543        id: Option<&GlobalElementId>,
3544        inspector_id: Option<&InspectorElementId>,
3545        bounds: Bounds<Pixels>,
3546        request_layout: &mut Self::RequestLayoutState,
3547        prepaint: &mut Self::PrepaintState,
3548        window: &mut Window,
3549        cx: &mut App,
3550    ) {
3551        self.element.paint(
3552            id,
3553            inspector_id,
3554            bounds,
3555            request_layout,
3556            prepaint,
3557            window,
3558            cx,
3559        );
3560    }
3561}
3562
3563impl<E> IntoElement for Stateful<E>
3564where
3565    E: Element,
3566{
3567    type Element = Self;
3568
3569    fn into_element(self) -> Self::Element {
3570        self
3571    }
3572}
3573
3574impl<E> ParentElement for Stateful<E>
3575where
3576    E: ParentElement,
3577{
3578    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
3579        self.element.extend(elements)
3580    }
3581}
3582
3583/// Represents an element that can be scrolled *to* in its parent element.
3584/// Contrary to [ScrollHandle::scroll_to_active_item], an anchored element does not have to be an immediate child of the parent.
3585#[derive(Clone)]
3586pub struct ScrollAnchor {
3587    handle: ScrollHandle,
3588    last_origin: Rc<RefCell<Point<Pixels>>>,
3589}
3590
3591impl ScrollAnchor {
3592    /// Creates a [ScrollAnchor] associated with a given [ScrollHandle].
3593    pub fn for_handle(handle: ScrollHandle) -> Self {
3594        Self {
3595            handle,
3596            last_origin: Default::default(),
3597        }
3598    }
3599    /// Request scroll to this item on the next frame.
3600    pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
3601        let this = self.clone();
3602
3603        window.on_next_frame(move |_, _| {
3604            let viewport_bounds = this.handle.bounds();
3605            let self_bounds = *this.last_origin.borrow();
3606            this.handle.set_offset(viewport_bounds.origin - self_bounds);
3607        });
3608    }
3609}
3610
3611#[derive(Default, Debug)]
3612struct ScrollHandleState {
3613    offset: Rc<RefCell<Point<Pixels>>>,
3614    bounds: Bounds<Pixels>,
3615    max_offset: Point<Pixels>,
3616    child_bounds: Vec<Bounds<Pixels>>,
3617    scroll_to_bottom: bool,
3618    overflow: Point<Overflow>,
3619    active_item: Option<ScrollActiveItem>,
3620}
3621
3622#[derive(Default, Debug, Clone, Copy)]
3623struct ScrollActiveItem {
3624    index: usize,
3625    strategy: ScrollStrategy,
3626}
3627
3628#[derive(Default, Debug, Clone, Copy)]
3629enum ScrollStrategy {
3630    #[default]
3631    FirstVisible,
3632    Top,
3633}
3634
3635/// A handle to the scrollable aspects of an element.
3636/// Used for accessing scroll state, like the current scroll offset,
3637/// and for mutating the scroll state, like scrolling to a specific child.
3638#[derive(Clone, Debug)]
3639pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
3640
3641impl Default for ScrollHandle {
3642    fn default() -> Self {
3643        Self::new()
3644    }
3645}
3646
3647impl ScrollHandle {
3648    /// Construct a new scroll handle.
3649    pub fn new() -> Self {
3650        Self(Rc::default())
3651    }
3652
3653    /// Get the current scroll offset.
3654    pub fn offset(&self) -> Point<Pixels> {
3655        *self.0.borrow().offset.borrow()
3656    }
3657
3658    /// Get the maximum scroll offset.
3659    pub fn max_offset(&self) -> Point<Pixels> {
3660        self.0.borrow().max_offset
3661    }
3662
3663    /// Get the top child that's scrolled into view.
3664    pub fn top_item(&self) -> usize {
3665        let state = self.0.borrow();
3666        let top = state.bounds.top() - state.offset.borrow().y;
3667
3668        match state.child_bounds.binary_search_by(|bounds| {
3669            if top < bounds.top() {
3670                Ordering::Greater
3671            } else if top > bounds.bottom() {
3672                Ordering::Less
3673            } else {
3674                Ordering::Equal
3675            }
3676        }) {
3677            Ok(ix) => ix,
3678            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
3679        }
3680    }
3681
3682    /// Get the bottom child that's scrolled into view.
3683    pub fn bottom_item(&self) -> usize {
3684        let state = self.0.borrow();
3685        let bottom = state.bounds.bottom() - state.offset.borrow().y;
3686
3687        match state.child_bounds.binary_search_by(|bounds| {
3688            if bottom < bounds.top() {
3689                Ordering::Greater
3690            } else if bottom > bounds.bottom() {
3691                Ordering::Less
3692            } else {
3693                Ordering::Equal
3694            }
3695        }) {
3696            Ok(ix) => ix,
3697            Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
3698        }
3699    }
3700
3701    /// Return the bounds into which this child is painted
3702    pub fn bounds(&self) -> Bounds<Pixels> {
3703        self.0.borrow().bounds
3704    }
3705
3706    /// Get the bounds for a specific child.
3707    pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
3708        self.0.borrow().child_bounds.get(ix).cloned()
3709    }
3710
3711    /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
3712    pub fn scroll_to_item(&self, ix: usize) {
3713        let mut state = self.0.borrow_mut();
3714        state.active_item = Some(ScrollActiveItem {
3715            index: ix,
3716            strategy: ScrollStrategy::default(),
3717        });
3718    }
3719
3720    /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
3721    /// This scrolls the minimal amount to ensure that the child is the first visible element
3722    pub fn scroll_to_top_of_item(&self, ix: usize) {
3723        let mut state = self.0.borrow_mut();
3724        state.active_item = Some(ScrollActiveItem {
3725            index: ix,
3726            strategy: ScrollStrategy::Top,
3727        });
3728    }
3729
3730    /// Scrolls the minimal amount to either ensure that the child is
3731    /// fully visible or the top element of the view depends on the
3732    /// scroll strategy
3733    fn scroll_to_active_item(&self) {
3734        let mut state = self.0.borrow_mut();
3735
3736        let Some(active_item) = state.active_item else {
3737            return;
3738        };
3739
3740        let active_item = match state.child_bounds.get(active_item.index) {
3741            Some(bounds) => {
3742                let mut scroll_offset = state.offset.borrow_mut();
3743
3744                match active_item.strategy {
3745                    ScrollStrategy::FirstVisible => {
3746                        if state.overflow.y == Overflow::Scroll {
3747                            let child_height = bounds.size.height;
3748                            let viewport_height = state.bounds.size.height;
3749                            if child_height > viewport_height {
3750                                scroll_offset.y = state.bounds.top() - bounds.top();
3751                            } else if bounds.top() + scroll_offset.y < state.bounds.top() {
3752                                scroll_offset.y = state.bounds.top() - bounds.top();
3753                            } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
3754                                scroll_offset.y = state.bounds.bottom() - bounds.bottom();
3755                            }
3756                        }
3757                    }
3758                    ScrollStrategy::Top => {
3759                        scroll_offset.y = state.bounds.top() - bounds.top();
3760                    }
3761                }
3762
3763                if state.overflow.x == Overflow::Scroll {
3764                    let child_width = bounds.size.width;
3765                    let viewport_width = state.bounds.size.width;
3766                    if child_width > viewport_width {
3767                        scroll_offset.x = state.bounds.left() - bounds.left();
3768                    } else if bounds.left() + scroll_offset.x < state.bounds.left() {
3769                        scroll_offset.x = state.bounds.left() - bounds.left();
3770                    } else if bounds.right() + scroll_offset.x > state.bounds.right() {
3771                        scroll_offset.x = state.bounds.right() - bounds.right();
3772                    }
3773                }
3774                None
3775            }
3776            None => Some(active_item),
3777        };
3778        state.active_item = active_item;
3779    }
3780
3781    /// Scrolls to the bottom.
3782    pub fn scroll_to_bottom(&self) {
3783        let mut state = self.0.borrow_mut();
3784        state.scroll_to_bottom = true;
3785    }
3786
3787    /// Set the offset explicitly. The offset is the distance from the top left of the
3788    /// parent container to the top left of the first child.
3789    /// As you scroll further down the offset becomes more negative.
3790    pub fn set_offset(&self, mut position: Point<Pixels>) {
3791        let state = self.0.borrow();
3792        *state.offset.borrow_mut() = position;
3793    }
3794
3795    /// Get the logical scroll top, based on a child index and a pixel offset.
3796    pub fn logical_scroll_top(&self) -> (usize, Pixels) {
3797        let ix = self.top_item();
3798        let state = self.0.borrow();
3799
3800        if let Some(child_bounds) = state.child_bounds.get(ix) {
3801            (
3802                ix,
3803                child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
3804            )
3805        } else {
3806            (ix, px(0.))
3807        }
3808    }
3809
3810    /// Get the logical scroll bottom, based on a child index and a pixel offset.
3811    pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
3812        let ix = self.bottom_item();
3813        let state = self.0.borrow();
3814
3815        if let Some(child_bounds) = state.child_bounds.get(ix) {
3816            (
3817                ix,
3818                child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
3819            )
3820        } else {
3821            (ix, px(0.))
3822        }
3823    }
3824
3825    /// Get the count of children for scrollable item.
3826    pub fn children_count(&self) -> usize {
3827        self.0.borrow().child_bounds.len()
3828    }
3829}
3830
3831#[cfg(test)]
3832mod tests {
3833    use super::*;
3834    use crate::{
3835        AppContext as _, Context, InputEvent, MouseMoveEvent, TestAppContext,
3836        util::FluentBuilder as _,
3837    };
3838    use std::rc::Weak;
3839
3840    struct TestTooltipView;
3841
3842    impl Render for TestTooltipView {
3843        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3844            div().w(px(20.)).h(px(20.)).child("tooltip")
3845        }
3846    }
3847
3848    type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
3849
3850    struct TooltipCaptureElement {
3851        child: AnyElement,
3852        captured_active_tooltip: CapturedActiveTooltip,
3853    }
3854
3855    impl IntoElement for TooltipCaptureElement {
3856        type Element = Self;
3857
3858        fn into_element(self) -> Self::Element {
3859            self
3860        }
3861    }
3862
3863    impl Element for TooltipCaptureElement {
3864        type RequestLayoutState = ();
3865        type PrepaintState = ();
3866
3867        fn id(&self) -> Option<ElementId> {
3868            None
3869        }
3870
3871        fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3872            None
3873        }
3874
3875        fn request_layout(
3876            &mut self,
3877            _id: Option<&GlobalElementId>,
3878            _inspector_id: Option<&InspectorElementId>,
3879            window: &mut Window,
3880            cx: &mut App,
3881        ) -> (LayoutId, Self::RequestLayoutState) {
3882            (self.child.request_layout(window, cx), ())
3883        }
3884
3885        fn prepaint(
3886            &mut self,
3887            _id: Option<&GlobalElementId>,
3888            _inspector_id: Option<&InspectorElementId>,
3889            _bounds: Bounds<Pixels>,
3890            _request_layout: &mut Self::RequestLayoutState,
3891            window: &mut Window,
3892            cx: &mut App,
3893        ) -> Self::PrepaintState {
3894            self.child.prepaint(window, cx);
3895        }
3896
3897        fn paint(
3898            &mut self,
3899            _id: Option<&GlobalElementId>,
3900            _inspector_id: Option<&InspectorElementId>,
3901            _bounds: Bounds<Pixels>,
3902            _request_layout: &mut Self::RequestLayoutState,
3903            _prepaint: &mut Self::PrepaintState,
3904            window: &mut Window,
3905            cx: &mut App,
3906        ) {
3907            self.child.paint(window, cx);
3908            window.with_global_id("target".into(), |global_id, window| {
3909                window.with_element_state::<InteractiveElementState, _>(
3910                    global_id,
3911                    |state, _window| {
3912                        let state = state.unwrap();
3913                        *self.captured_active_tooltip.borrow_mut() =
3914                            state.active_tooltip.as_ref().map(Rc::downgrade);
3915                        ((), state)
3916                    },
3917                )
3918            });
3919        }
3920    }
3921
3922    struct TooltipOwner {
3923        captured_active_tooltip: CapturedActiveTooltip,
3924        show_delay_override: Option<Duration>,
3925    }
3926
3927    impl Render for TooltipOwner {
3928        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3929            TooltipCaptureElement {
3930                child: div()
3931                    .size_full()
3932                    .child(
3933                        div()
3934                            .id("target")
3935                            .w(px(50.))
3936                            .h(px(50.))
3937                            .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
3938                            .when_some(self.show_delay_override, |this, delay| {
3939                                this.tooltip_show_delay(delay)
3940                            }),
3941                    )
3942                    .into_any_element(),
3943                captured_active_tooltip: self.captured_active_tooltip.clone(),
3944            }
3945        }
3946    }
3947
3948    #[test]
3949    fn scroll_handle_aligns_wide_children_to_left_edge() {
3950        let handle = ScrollHandle::new();
3951        {
3952            let mut state = handle.0.borrow_mut();
3953            state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
3954            state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
3955            state.overflow.x = Overflow::Scroll;
3956            state.active_item = Some(ScrollActiveItem {
3957                index: 0,
3958                strategy: ScrollStrategy::default(),
3959            });
3960        }
3961
3962        handle.scroll_to_active_item();
3963
3964        assert_eq!(handle.offset().x, px(-25.));
3965    }
3966
3967    #[test]
3968    fn scroll_handle_aligns_tall_children_to_top_edge() {
3969        let handle = ScrollHandle::new();
3970        {
3971            let mut state = handle.0.borrow_mut();
3972            state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
3973            state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
3974            state.overflow.y = Overflow::Scroll;
3975            state.active_item = Some(ScrollActiveItem {
3976                index: 0,
3977                strategy: ScrollStrategy::default(),
3978            });
3979        }
3980
3981        handle.scroll_to_active_item();
3982
3983        assert_eq!(handle.offset().y, px(-25.));
3984    }
3985
3986    fn setup_tooltip_owner_test(
3987        show_delay_override: Option<Duration>,
3988    ) -> (
3989        TestAppContext,
3990        crate::AnyWindowHandle,
3991        CapturedActiveTooltip,
3992    ) {
3993        let mut test_app = TestAppContext::single();
3994        let captured_active_tooltip: CapturedActiveTooltip = Rc::new(RefCell::new(None));
3995        let window = test_app.add_window({
3996            let captured_active_tooltip = captured_active_tooltip.clone();
3997            move |_, _| TooltipOwner {
3998                captured_active_tooltip,
3999                show_delay_override,
4000            }
4001        });
4002        let any_window = window.into();
4003
4004        test_app
4005            .update_window(any_window, |_, window, cx| {
4006                window.draw(cx).clear();
4007            })
4008            .unwrap();
4009
4010        test_app
4011            .update_window(any_window, |_, window, cx| {
4012                window.dispatch_event(
4013                    MouseMoveEvent {
4014                        position: point(px(10.), px(10.)),
4015                        modifiers: Default::default(),
4016                        pressed_button: None,
4017                    }
4018                    .to_platform_input(),
4019                    cx,
4020                );
4021            })
4022            .unwrap();
4023
4024        test_app
4025            .update_window(any_window, |_, window, cx| {
4026                window.draw(cx).clear();
4027            })
4028            .unwrap();
4029
4030        (test_app, any_window, captured_active_tooltip)
4031    }
4032
4033    #[test]
4034    fn tooltip_waiting_for_show_is_released_when_its_owner_disappears() {
4035        let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4036
4037        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4038        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4039        assert!(matches!(
4040            active_tooltip.borrow().as_ref(),
4041            Some(ActiveTooltip::WaitingForShow { .. })
4042        ));
4043
4044        test_app
4045            .update_window(any_window, |_, window, _| {
4046                window.remove_window();
4047            })
4048            .unwrap();
4049        test_app.run_until_parked();
4050        drop(active_tooltip);
4051
4052        assert!(weak_active_tooltip.upgrade().is_none());
4053    }
4054
4055    #[test]
4056    fn tooltip_respects_custom_show_delay() {
4057        let extra_delay = Duration::from_secs(1);
4058        let show_delay_override = DEFAULT_TOOLTIP_SHOW_DELAY + extra_delay;
4059        let (mut test_app, _any_window, captured_active_tooltip) =
4060            setup_tooltip_owner_test(Some(show_delay_override));
4061
4062        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4063        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4064
4065        test_app
4066            .dispatcher
4067            .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4068        test_app.run_until_parked();
4069
4070        assert!(matches!(
4071            active_tooltip.borrow().as_ref(),
4072            Some(ActiveTooltip::WaitingForShow { .. })
4073        ));
4074
4075        test_app.dispatcher.advance_clock(extra_delay);
4076        test_app.run_until_parked();
4077
4078        assert!(matches!(
4079            active_tooltip.borrow().as_ref(),
4080            Some(ActiveTooltip::Visible { .. })
4081        ));
4082    }
4083
4084    #[test]
4085    fn tooltip_is_released_when_its_owner_disappears() {
4086        let (mut test_app, any_window, captured_active_tooltip) = setup_tooltip_owner_test(None);
4087
4088        let weak_active_tooltip = captured_active_tooltip.borrow().clone().unwrap();
4089        let active_tooltip = weak_active_tooltip.upgrade().unwrap();
4090
4091        test_app
4092            .dispatcher
4093            .advance_clock(DEFAULT_TOOLTIP_SHOW_DELAY);
4094        test_app.run_until_parked();
4095
4096        assert!(matches!(
4097            active_tooltip.borrow().as_ref(),
4098            Some(ActiveTooltip::Visible { .. })
4099        ));
4100
4101        test_app
4102            .update_window(any_window, |_, window, _| {
4103                window.remove_window();
4104            })
4105            .unwrap();
4106        test_app.run_until_parked();
4107        drop(active_tooltip);
4108
4109        assert!(weak_active_tooltip.upgrade().is_none());
4110    }
4111}