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