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