Skip to main content

gpui/elements/
div.rs

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