Skip to main content

wgpui/elements/
div.rs

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