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 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 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 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 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 when container width is is less than or equal to 256.0 Pixels
680 fn container_3xs(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
681 self.container_query_with(256.0, f)
682 }
683
684 /// Apply the given style when container width is is less than or equal to 288.0 Pixels
685 fn container_2xs(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
686 self.container_query_with(288.0, f)
687 }
688
689 /// Apply the given style when container width is is less than or equal to 320.0 Pixels
690 fn container_xs(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
691 self.container_query_with(320.0, f)
692 }
693
694 /// Apply the given style when container width is is less than or equal to 384.0 Pixels
695 fn container_sm(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
696 self.container_query_with(384.0, f)
697 }
698
699 /// Apply the given style when container width is is less than or equal to 448.0 Pixels
700 fn container_md(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
701 self.container_query_with(448.0, f)
702 }
703
704 /// Apply the given style when container width is is less than or equal to 512.0 Pixels
705 fn container_lg(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
706 self.container_query_with(512.0, f)
707 }
708
709 /// Apply the given style when container width is is less than or equal to 576.0 Pixels
710 fn container_xl(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
711 self.container_query_with(576.0, f)
712 }
713
714 /// Apply the given style when width is less than or equal to the current value
715 fn container_query_with(
716 mut self,
717 width: impl Into<Pixels>,
718 f: impl Fn(StyleRefinement) -> StyleRefinement + 'static,
719 ) -> Self {
720 let width = width.into();
721
722 self.interactivity()
723 .container_queries
724 .push(Box::new(move |layout_width, style| {
725 if layout_width >= width {
726 f(style)
727 } else {
728 style
729 }
730 }));
731 self
732 }
733
734 /// Apply the given style to this element when the mouse hovers over a group member
735 fn group_hover(
736 mut self,
737 group_name: impl Into<SharedString>,
738 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
739 ) -> Self {
740 self.interactivity().group_hover_style = Some(GroupStyle {
741 group: group_name.into(),
742 style: Box::new(f(StyleRefinement::default())),
743 });
744 self
745 }
746
747 /// Bind the given callback to the mouse down event for the given mouse button,
748 /// the fluent API equivalent to [`Interactivity::on_mouse_down`]
749 ///
750 /// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
751 fn on_mouse_down(
752 mut self,
753 button: MouseButton,
754 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
755 ) -> Self {
756 self.interactivity().on_mouse_down(button, listener);
757 self
758 }
759
760 #[cfg(any(test, feature = "test-support"))]
761 /// Set a key that can be used to look up this element's bounds
762 /// in the [`crate::VisualTestContext::debug_bounds`] map
763 /// This is a noop in release builds
764 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
765 self.interactivity().debug_selector = Some(f());
766 self
767 }
768
769 #[cfg(not(any(test, feature = "test-support")))]
770 /// Set a key that can be used to look up this element's bounds
771 /// in the [`crate::VisualTestContext::debug_bounds`] map
772 /// This is a noop in release builds
773 #[inline]
774 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
775 self
776 }
777
778 /// Bind the given callback to the mouse down event for any button, during the capture phase
779 /// the fluent API equivalent to [`Interactivity::capture_any_mouse_down`]
780 ///
781 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
782 fn capture_any_mouse_down(
783 mut self,
784 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
785 ) -> Self {
786 self.interactivity().capture_any_mouse_down(listener);
787 self
788 }
789
790 /// Bind the given callback to the mouse down event for any button, during the capture phase
791 /// the fluent API equivalent to [`Interactivity::on_any_mouse_down`]
792 ///
793 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
794 fn on_any_mouse_down(
795 mut self,
796 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
797 ) -> Self {
798 self.interactivity().on_any_mouse_down(listener);
799 self
800 }
801
802 /// Bind the given callback to the mouse up event for the given button, during the bubble phase
803 /// the fluent API equivalent to [`Interactivity::on_mouse_up`]
804 ///
805 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
806 fn on_mouse_up(
807 mut self,
808 button: MouseButton,
809 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
810 ) -> Self {
811 self.interactivity().on_mouse_up(button, listener);
812 self
813 }
814
815 /// Bind the given callback to the mouse up event for any button, during the capture phase
816 /// the fluent API equivalent to [`Interactivity::capture_any_mouse_up`]
817 ///
818 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
819 fn capture_any_mouse_up(
820 mut self,
821 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
822 ) -> Self {
823 self.interactivity().capture_any_mouse_up(listener);
824 self
825 }
826
827 /// Bind the given callback to the mouse down event, on any button, during the capture phase,
828 /// when the mouse is outside of the bounds of this element.
829 /// The fluent API equivalent to [`Interactivity::on_mouse_down_out`]
830 ///
831 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
832 fn on_mouse_down_out(
833 mut self,
834 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
835 ) -> Self {
836 self.interactivity().on_mouse_down_out(listener);
837 self
838 }
839
840 /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
841 /// when the mouse is outside of the bounds of this element.
842 /// The fluent API equivalent to [`Interactivity::on_mouse_up_out`]
843 ///
844 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
845 fn on_mouse_up_out(
846 mut self,
847 button: MouseButton,
848 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
849 ) -> Self {
850 self.interactivity().on_mouse_up_out(button, listener);
851 self
852 }
853
854 /// Bind the given callback to the mouse move event, during the bubble phase
855 /// The fluent API equivalent to [`Interactivity::on_mouse_move`]
856 ///
857 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
858 fn on_mouse_move(
859 mut self,
860 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
861 ) -> Self {
862 self.interactivity().on_mouse_move(listener);
863 self
864 }
865
866 /// Bind the given callback to the mouse drag event of the given type. Note that this
867 /// will be called for all move events, inside or outside of this element, as long as the
868 /// drag was started with this element under the mouse. Useful for implementing draggable
869 /// UIs that don't conform to a drag and drop style interaction, like resizing.
870 /// The fluent API equivalent to [`Interactivity::on_drag_move`]
871 ///
872 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
873 fn on_drag_move<T: 'static>(
874 mut self,
875 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
876 ) -> Self {
877 self.interactivity().on_drag_move(listener);
878 self
879 }
880
881 /// Bind the given callback to scroll wheel events during the bubble phase
882 /// The fluent API equivalent to [`Interactivity::on_scroll_wheel`]
883 ///
884 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
885 fn on_scroll_wheel(
886 mut self,
887 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
888 ) -> Self {
889 self.interactivity().on_scroll_wheel(listener);
890 self
891 }
892
893 /// Capture the given action, before normal action dispatch can fire
894 /// The fluent API equivalent to [`Interactivity::on_scroll_wheel`]
895 ///
896 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
897 fn capture_action<A: Action>(
898 mut self,
899 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
900 ) -> Self {
901 self.interactivity().capture_action(listener);
902 self
903 }
904
905 /// Bind the given callback to an action dispatch during the bubble phase
906 /// The fluent API equivalent to [`Interactivity::on_action`]
907 ///
908 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
909 fn on_action<A: Action>(
910 mut self,
911 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
912 ) -> Self {
913 self.interactivity().on_action(listener);
914 self
915 }
916
917 /// Bind the given callback to an action dispatch, based on a dynamic action parameter
918 /// instead of a type parameter. Useful for component libraries that want to expose
919 /// action bindings to their users.
920 /// The fluent API equivalent to [`Interactivity::on_boxed_action`]
921 ///
922 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
923 fn on_boxed_action(
924 mut self,
925 action: &dyn Action,
926 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
927 ) -> Self {
928 self.interactivity().on_boxed_action(action, listener);
929 self
930 }
931
932 /// Bind the given callback to key down events during the bubble phase
933 /// The fluent API equivalent to [`Interactivity::on_key_down`]
934 ///
935 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
936 fn on_key_down(
937 mut self,
938 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
939 ) -> Self {
940 self.interactivity().on_key_down(listener);
941 self
942 }
943
944 /// Bind the given callback to key down events during the capture phase
945 /// The fluent API equivalent to [`Interactivity::capture_key_down`]
946 ///
947 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
948 fn capture_key_down(
949 mut self,
950 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
951 ) -> Self {
952 self.interactivity().capture_key_down(listener);
953 self
954 }
955
956 /// Bind the given callback to key up events during the bubble phase
957 /// The fluent API equivalent to [`Interactivity::on_key_up`]
958 ///
959 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
960 fn on_key_up(
961 mut self,
962 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
963 ) -> Self {
964 self.interactivity().on_key_up(listener);
965 self
966 }
967
968 /// Bind the given callback to key up events during the capture phase
969 /// The fluent API equivalent to [`Interactivity::capture_key_up`]
970 ///
971 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
972 fn capture_key_up(
973 mut self,
974 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
975 ) -> Self {
976 self.interactivity().capture_key_up(listener);
977 self
978 }
979
980 /// Bind the given callback to modifiers changing events.
981 /// The fluent API equivalent to [`Interactivity::on_modifiers_changed`]
982 ///
983 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
984 fn on_modifiers_changed(
985 mut self,
986 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
987 ) -> Self {
988 self.interactivity().on_modifiers_changed(listener);
989 self
990 }
991
992 /// Apply the given style when the given data type is dragged over this element
993 fn drag_over<S: 'static>(
994 mut self,
995 f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
996 ) -> Self {
997 self.interactivity().drag_over_styles.push((
998 TypeId::of::<S>(),
999 Box::new(move |currently_dragged: &dyn Any, window, cx| {
1000 f(
1001 StyleRefinement::default(),
1002 currently_dragged.downcast_ref::<S>().unwrap(),
1003 window,
1004 cx,
1005 )
1006 }),
1007 ));
1008 self
1009 }
1010
1011 /// Apply the given style when the given data type is dragged over this element's group
1012 fn group_drag_over<S: 'static>(
1013 mut self,
1014 group_name: impl Into<SharedString>,
1015 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1016 ) -> Self {
1017 self.interactivity().group_drag_over_styles.push((
1018 TypeId::of::<S>(),
1019 GroupStyle {
1020 group: group_name.into(),
1021 style: Box::new(f(StyleRefinement::default())),
1022 },
1023 ));
1024 self
1025 }
1026
1027 /// Bind the given callback to drop events of the given type, whether or not the drag started on this element
1028 /// The fluent API equivalent to [`Interactivity::on_drop`]
1029 ///
1030 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1031 fn on_drop<T: 'static>(
1032 mut self,
1033 listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1034 ) -> Self {
1035 self.interactivity().on_drop(listener);
1036 self
1037 }
1038
1039 /// Use the given predicate to determine whether or not a drop event should be dispatched to this element
1040 /// The fluent API equivalent to [`Interactivity::can_drop`]
1041 fn can_drop(
1042 mut self,
1043 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1044 ) -> Self {
1045 self.interactivity().can_drop(predicate);
1046 self
1047 }
1048
1049 /// Block the mouse from all interactions with elements behind this element's hitbox. Typically
1050 /// `block_mouse_except_scroll` should be preferred.
1051 /// The fluent API equivalent to [`Interactivity::occlude_mouse`]
1052 fn occlude(mut self) -> Self {
1053 self.interactivity().occlude_mouse();
1054 self
1055 }
1056
1057 /// Set the bounds of this element as a window control area for the platform window.
1058 /// The fluent API equivalent to [`Interactivity::window_control_area`]
1059 fn window_control_area(mut self, area: WindowControlArea) -> Self {
1060 self.interactivity().window_control_area(area);
1061 self
1062 }
1063
1064 /// Block non-scroll mouse interactions with elements behind this element's hitbox. See
1065 /// [`Hitbox::is_hovered`] for details.
1066 ///
1067 /// The fluent API equivalent to [`Interactivity::block_mouse_except_scroll`]
1068 fn block_mouse_except_scroll(mut self) -> Self {
1069 self.interactivity().block_mouse_except_scroll();
1070 self
1071 }
1072
1073 /// Set the given styles to be applied when this element, specifically, is focused.
1074 /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1075 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1076 where
1077 Self: Sized,
1078 {
1079 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1080 self
1081 }
1082
1083 /// Set the given styles to be applied when this element is inside another element that is focused.
1084 /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1085 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1086 where
1087 Self: Sized,
1088 {
1089 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1090 self
1091 }
1092
1093 /// Set the given styles to be applied when this element is focused via keyboard navigation.
1094 /// This is similar to CSS's `:focus-visible` pseudo-class - it only applies when the element
1095 /// is focused AND the user is navigating via keyboard (not mouse clicks).
1096 /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1097 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1098 where
1099 Self: Sized,
1100 {
1101 self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1102 self
1103 }
1104}
1105
1106/// A trait for elements that want to use the standard GPUI interactivity features
1107/// that require state.
1108pub trait StatefulInteractiveElement: InteractiveElement {
1109 /// Set this element to focusable.
1110 fn focusable(mut self) -> Self {
1111 self.interactivity().focusable = true;
1112 self
1113 }
1114
1115 /// Set the overflow x and y to scroll.
1116 fn overflow_scroll(mut self) -> Self {
1117 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1118 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1119 self
1120 }
1121
1122 /// Set the overflow x to scroll.
1123 fn overflow_x_scroll(mut self) -> Self {
1124 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1125 self
1126 }
1127
1128 /// Set the overflow y to scroll.
1129 fn overflow_y_scroll(mut self) -> Self {
1130 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1131 self
1132 }
1133
1134 /// Set the space to be reserved for rendering the scrollbar.
1135 ///
1136 /// This will only affect the layout of the element when overflow for this element is set to
1137 /// `Overflow::Scroll`.
1138 fn scrollbar_width(mut self, width: impl Into<AbsoluteLength>) -> Self {
1139 self.interactivity().base_style.scrollbar_width = Some(width.into());
1140 self
1141 }
1142
1143 /// Track the scroll state of this element with the given handle.
1144 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1145 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1146 self
1147 }
1148
1149 /// Track the scroll state of this element with the given handle.
1150 fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1151 self.interactivity().scroll_anchor = scroll_anchor;
1152 self
1153 }
1154
1155 /// Set the given styles to be applied when this element is active.
1156 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1157 where
1158 Self: Sized,
1159 {
1160 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1161 self
1162 }
1163
1164 /// Set the given styles to be applied when this element's group is active.
1165 fn group_active(
1166 mut self,
1167 group_name: impl Into<SharedString>,
1168 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1169 ) -> Self
1170 where
1171 Self: Sized,
1172 {
1173 self.interactivity().group_active_style = Some(GroupStyle {
1174 group: group_name.into(),
1175 style: Box::new(f(StyleRefinement::default())),
1176 });
1177 self
1178 }
1179
1180 /// Bind the given callback to click events of this element
1181 /// The fluent API equivalent to [`Interactivity::on_click`]
1182 ///
1183 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1184 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1185 where
1186 Self: Sized,
1187 {
1188 self.interactivity().on_click(listener);
1189 self
1190 }
1191
1192 /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
1193 /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
1194 /// the [`InteractiveElement::on_drag_move`] API.
1195 /// The callback also has access to the offset of triggering click from the origin of parent element.
1196 /// The fluent API equivalent to [`Interactivity::on_drag`]
1197 ///
1198 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1199 fn on_drag<T, W>(
1200 mut self,
1201 value: T,
1202 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1203 ) -> Self
1204 where
1205 Self: Sized,
1206 T: 'static,
1207 W: 'static + Render,
1208 {
1209 self.interactivity().on_drag(value, constructor);
1210 self
1211 }
1212
1213 /// Bind the given callback on the hover start and end events of this element. Note that the boolean
1214 /// passed to the callback is true when the hover starts and false when it ends.
1215 /// The fluent API equivalent to [`Interactivity::on_hover`]
1216 ///
1217 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1218 fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1219 where
1220 Self: Sized,
1221 {
1222 self.interactivity().on_hover(listener);
1223 self
1224 }
1225
1226 /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
1227 /// The fluent API equivalent to [`Interactivity::tooltip`]
1228 fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1229 where
1230 Self: Sized,
1231 {
1232 self.interactivity().tooltip(build_tooltip);
1233 self
1234 }
1235
1236 /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
1237 /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
1238 /// the tooltip. The fluent API equivalent to [`Interactivity::hoverable_tooltip`]
1239 fn hoverable_tooltip(
1240 mut self,
1241 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1242 ) -> Self
1243 where
1244 Self: Sized,
1245 {
1246 self.interactivity().hoverable_tooltip(build_tooltip);
1247 self
1248 }
1249}
1250
1251pub(crate) type MouseDownListener =
1252 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1253pub(crate) type MouseUpListener =
1254 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1255
1256pub(crate) type MouseMoveListener =
1257 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1258
1259pub(crate) type ScrollWheelListener =
1260 Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1261
1262pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1263
1264pub(crate) type DragListener =
1265 Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>;
1266
1267type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1268
1269type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1270
1271pub(crate) struct TooltipBuilder {
1272 build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1273 hoverable: bool,
1274}
1275
1276pub(crate) type KeyDownListener =
1277 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1278
1279pub(crate) type KeyUpListener =
1280 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1281
1282pub(crate) type ModifiersChangedListener =
1283 Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1284
1285pub(crate) type ActionListener =
1286 Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1287
1288/// Construct a new [`Div`] element
1289#[track_caller]
1290pub fn div() -> Div {
1291 Div {
1292 interactivity: Interactivity::new(),
1293 children: SmallVec::default(),
1294 prepaint_listener: None,
1295 image_cache: None,
1296 }
1297}
1298
1299/// A [`Div`] element, the all-in-one element for building complex UIs in GPUI
1300pub struct Div {
1301 interactivity: Interactivity,
1302 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1303 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1304 image_cache: Option<Box<dyn ImageCacheProvider>>,
1305}
1306
1307impl Div {
1308 /// Add a listener to be called when the children of this `Div` are prepainted.
1309 /// This allows you to store the [`Bounds`] of the children for later use.
1310 pub fn on_children_prepainted(
1311 mut self,
1312 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1313 ) -> Self {
1314 self.prepaint_listener = Some(Box::new(listener));
1315 self
1316 }
1317
1318 /// Add an image cache at the location of this div in the element tree.
1319 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1320 self.image_cache = Some(Box::new(cache));
1321 self
1322 }
1323}
1324
1325/// A frame state for a `Div` element, which contains layout IDs for its children.
1326///
1327/// This struct is used internally by the `Div` element to manage the layout state of its children
1328/// during the UI update cycle. It holds a small vector of `LayoutId` values, each corresponding to
1329/// a child element of the `Div`. These IDs are used to query the layout engine for the computed
1330/// bounds of the children after the layout phase is complete.
1331pub struct DivFrameState {
1332 child_layout_ids: SmallVec<[LayoutId; 2]>,
1333}
1334
1335/// Interactivity state displayed an manipulated in the inspector.
1336#[derive(Clone)]
1337pub struct DivInspectorState {
1338 /// The inspected element's base style. This is used for both inspecting and modifying the
1339 /// state. In the future it will make sense to separate the read and write, possibly tracking
1340 /// the modifications.
1341 #[cfg(any(feature = "inspector", debug_assertions))]
1342 pub base_style: Box<StyleRefinement>,
1343 /// Inspects the bounds of the element.
1344 pub bounds: Bounds<Pixels>,
1345 /// Size of the children of the element, or `bounds.size` if it has no children.
1346 pub content_size: Size<Pixels>,
1347}
1348
1349impl Styled for Div {
1350 fn style(&mut self) -> &mut StyleRefinement {
1351 &mut self.interactivity.base_style
1352 }
1353}
1354
1355impl InteractiveElement for Div {
1356 fn interactivity(&mut self) -> &mut Interactivity {
1357 &mut self.interactivity
1358 }
1359}
1360
1361impl ParentElement for Div {
1362 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1363 self.children
1364 .extend(elements.into_iter().map(StackSafe::new))
1365 }
1366}
1367
1368impl Element for Div {
1369 type RequestLayoutState = DivFrameState;
1370 type PrepaintState = Option<Hitbox>;
1371
1372 fn id(&self) -> Option<ElementId> {
1373 self.interactivity.element_id.clone()
1374 }
1375
1376 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1377 self.interactivity.source_location()
1378 }
1379
1380 #[stacksafe]
1381 fn request_layout(
1382 &mut self,
1383 global_id: Option<&GlobalElementId>,
1384 inspector_id: Option<&InspectorElementId>,
1385 window: &mut Window,
1386 cx: &mut App,
1387 ) -> (LayoutId, Self::RequestLayoutState) {
1388 let mut child_layout_ids = SmallVec::new();
1389 let image_cache = self
1390 .image_cache
1391 .as_mut()
1392 .map(|provider| provider.provide(window, cx));
1393
1394 let layout_id = window.with_image_cache(image_cache, |window| {
1395 self.interactivity.request_layout(
1396 global_id,
1397 inspector_id,
1398 window,
1399 cx,
1400 |style, window, cx| {
1401 window.with_text_style(style.text_style().cloned(), |window| {
1402 child_layout_ids = self
1403 .children
1404 .iter_mut()
1405 .map(|child| child.request_layout(window, cx))
1406 .collect::<SmallVec<_>>();
1407 window.request_layout(style, child_layout_ids.iter().copied(), cx)
1408 })
1409 },
1410 )
1411 });
1412
1413 (layout_id, DivFrameState { child_layout_ids })
1414 }
1415
1416 #[stacksafe]
1417 fn prepaint(
1418 &mut self,
1419 global_id: Option<&GlobalElementId>,
1420 inspector_id: Option<&InspectorElementId>,
1421 bounds: Bounds<Pixels>,
1422 request_layout: &mut Self::RequestLayoutState,
1423 window: &mut Window,
1424 cx: &mut App,
1425 ) -> Option<Hitbox> {
1426 let has_prepaint_listener = self.prepaint_listener.is_some();
1427 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1428 request_layout.child_layout_ids.len()
1429 } else {
1430 0
1431 });
1432
1433 let mut child_min = point(Pixels::MAX, Pixels::MAX);
1434 let mut child_max = Point::default();
1435 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1436 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1437 }
1438 let content_size = if request_layout.child_layout_ids.is_empty() {
1439 bounds.size
1440 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1441 let mut state = scroll_handle.0.borrow_mut();
1442 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1443 for child_layout_id in &request_layout.child_layout_ids {
1444 let child_bounds = window.layout_bounds(*child_layout_id);
1445 child_min = child_min.min(&child_bounds.origin);
1446 child_max = child_max.max(&child_bounds.bottom_right());
1447 state.child_bounds.push(child_bounds);
1448 }
1449 (child_max - child_min).into()
1450 } else {
1451 for child_layout_id in &request_layout.child_layout_ids {
1452 let child_bounds = window.layout_bounds(*child_layout_id);
1453 child_min = child_min.min(&child_bounds.origin);
1454 child_max = child_max.max(&child_bounds.bottom_right());
1455
1456 if has_prepaint_listener {
1457 children_bounds.push(child_bounds);
1458 }
1459 }
1460 (child_max - child_min).into()
1461 };
1462
1463 if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1464 scroll_handle.scroll_to_active_item();
1465 }
1466
1467 self.interactivity.prepaint(
1468 global_id,
1469 inspector_id,
1470 bounds,
1471 content_size,
1472 window,
1473 cx,
1474 |style, scroll_offset, hitbox, window, cx| {
1475 // skip children
1476 if style.display == Display::None {
1477 return hitbox;
1478 }
1479
1480 window.with_element_offset(scroll_offset, |window| {
1481 for child in &mut self.children {
1482 child.prepaint(window, cx);
1483 }
1484 });
1485
1486 if let Some(listener) = self.prepaint_listener.as_ref() {
1487 listener(children_bounds, window, cx);
1488 }
1489
1490 hitbox
1491 },
1492 )
1493 }
1494
1495 #[stacksafe]
1496 fn paint(
1497 &mut self,
1498 global_id: Option<&GlobalElementId>,
1499 inspector_id: Option<&InspectorElementId>,
1500 bounds: Bounds<Pixels>,
1501 _request_layout: &mut Self::RequestLayoutState,
1502 hitbox: &mut Option<Hitbox>,
1503 window: &mut Window,
1504 cx: &mut App,
1505 ) {
1506 let image_cache = self
1507 .image_cache
1508 .as_mut()
1509 .map(|provider| provider.provide(window, cx));
1510
1511 window.with_image_cache(image_cache, |window| {
1512 self.interactivity.paint(
1513 global_id,
1514 inspector_id,
1515 bounds,
1516 hitbox.as_ref(),
1517 window,
1518 cx,
1519 |style, window, cx| {
1520 // skip children
1521 if style.display == Display::None {
1522 return;
1523 }
1524
1525 for child in &mut self.children {
1526 child.paint(window, cx);
1527 }
1528 },
1529 )
1530 });
1531 }
1532}
1533
1534impl IntoElement for Div {
1535 type Element = Self;
1536
1537 fn into_element(self) -> Self::Element {
1538 self
1539 }
1540}
1541
1542/// The interactivity struct. Powers all of the general-purpose
1543/// interactivity in the `Div` element.
1544#[derive(Default)]
1545pub struct Interactivity {
1546 /// The element ID of the element. In id is required to support a stateful subset of the interactivity such as on_click.
1547 pub element_id: Option<ElementId>,
1548 /// Whether the element was clicked. This will only be present after layout.
1549 pub active: Option<bool>,
1550 /// Whether the element was hovered. This will only be present after paint if an hitbox
1551 /// was created for the interactive element.
1552 pub hovered: Option<bool>,
1553 pub(crate) tooltip_id: Option<TooltipId>,
1554 pub(crate) content_size: Size<Pixels>,
1555 pub(crate) key_context: Option<KeyContext>,
1556 pub(crate) focusable: bool,
1557 pub(crate) tracked_focus_handle: Option<FocusHandle>,
1558 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
1559 pub(crate) scroll_anchor: Option<ScrollAnchor>,
1560 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
1561 pub(crate) group: Option<SharedString>,
1562 /// The base style of the element, before any modifications are applied
1563 /// by focus, active, etc.
1564 pub base_style: Box<StyleRefinement>,
1565 pub(crate) focus_style: Option<Box<StyleRefinement>>,
1566 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
1567 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
1568 pub(crate) hover_style: Option<Box<StyleRefinement>>,
1569 pub(crate) group_hover_style: Option<GroupStyle>,
1570 pub(crate) active_style: Option<Box<StyleRefinement>>,
1571 pub(crate) group_active_style: Option<GroupStyle>,
1572 pub(crate) drag_over_styles: Vec<(
1573 TypeId,
1574 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
1575 )>,
1576 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
1577 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
1578 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
1579 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
1580 pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
1581 pub(crate) key_down_listeners: Vec<KeyDownListener>,
1582 pub(crate) key_up_listeners: Vec<KeyUpListener>,
1583 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
1584 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
1585 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
1586 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
1587 pub(crate) click_listeners: Vec<ClickListener>,
1588 pub(crate) drag_listener: Option<(Arc<dyn Any>, DragListener)>,
1589 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
1590 pub(crate) container_queries: Vec<Box<dyn Fn(Pixels, StyleRefinement) -> StyleRefinement>>,
1591 pub(crate) tooltip_builder: Option<TooltipBuilder>,
1592 pub(crate) window_control: Option<WindowControlArea>,
1593 pub(crate) hitbox_behavior: HitboxBehavior,
1594 pub(crate) tab_index: Option<isize>,
1595 pub(crate) tab_group: bool,
1596 pub(crate) tab_stop: bool,
1597
1598 #[cfg(any(feature = "inspector", debug_assertions))]
1599 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
1600
1601 #[cfg(any(test, feature = "test-support"))]
1602 pub(crate) debug_selector: Option<String>,
1603}
1604
1605impl Interactivity {
1606 /// Layout this element according to this interactivity state's configured styles
1607 pub fn request_layout(
1608 &mut self,
1609 global_id: Option<&GlobalElementId>,
1610 _inspector_id: Option<&InspectorElementId>,
1611 window: &mut Window,
1612 cx: &mut App,
1613 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
1614 ) -> LayoutId {
1615 #[cfg(any(feature = "inspector", debug_assertions))]
1616 window.with_inspector_state(
1617 _inspector_id,
1618 cx,
1619 |inspector_state: &mut Option<DivInspectorState>, _window| {
1620 if let Some(inspector_state) = inspector_state {
1621 self.base_style = inspector_state.base_style.clone();
1622 } else {
1623 *inspector_state = Some(DivInspectorState {
1624 base_style: self.base_style.clone(),
1625 bounds: Default::default(),
1626 content_size: Default::default(),
1627 })
1628 }
1629 },
1630 );
1631
1632 window.with_optional_element_state::<InteractiveElementState, _>(
1633 global_id,
1634 |element_state, window| {
1635 let mut element_state =
1636 element_state.map(|element_state| element_state.unwrap_or_default());
1637
1638 if let Some(element_state) = element_state.as_ref()
1639 && cx.has_active_drag()
1640 {
1641 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
1642 *pending_mouse_down.borrow_mut() = None;
1643 }
1644 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1645 *clicked_state.borrow_mut() = ElementClickedState::default();
1646 }
1647 }
1648
1649 // Ensure we store a focus handle in our element state if we're focusable.
1650 // If there's an explicit focus handle we're tracking, use that. Otherwise
1651 // create a new handle and store it in the element state, which lives for as
1652 // as frames contain an element with this id.
1653 if self.focusable
1654 && self.tracked_focus_handle.is_none()
1655 && let Some(element_state) = element_state.as_mut()
1656 {
1657 let mut handle = element_state
1658 .focus_handle
1659 .get_or_insert_with(|| cx.focus_handle())
1660 .clone()
1661 .tab_stop(self.tab_stop);
1662
1663 if let Some(index) = self.tab_index {
1664 handle = handle.tab_index(index);
1665 }
1666
1667 self.tracked_focus_handle = Some(handle);
1668 }
1669
1670 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
1671 self.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
1672 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
1673 || self.base_style.overflow.y == Some(Overflow::Scroll))
1674 && let Some(element_state) = element_state.as_mut()
1675 {
1676 self.scroll_offset = Some(
1677 element_state
1678 .scroll_offset
1679 .get_or_insert_with(Rc::default)
1680 .clone(),
1681 );
1682 }
1683
1684 let mut style =
1685 self.compute_style_internal(None, element_state.as_mut(), window, cx);
1686
1687 let mut style_refinement = StyleRefinement::default();
1688
1689 if let Some(element_state) = element_state.as_ref()
1690 && let Some(bounds) = element_state.cached_bounds
1691 {
1692 let current_width = bounds.size.width;
1693
1694 for query in self.container_queries.iter() {
1695 style_refinement = query(current_width, style_refinement);
1696 }
1697
1698 style.refine(&style_refinement);
1699 }
1700 let layout_id = f(style, window, cx);
1701 (layout_id, element_state)
1702 },
1703 )
1704 }
1705
1706 /// Commit the bounds of this element according to this interactivity state's configured styles.
1707 pub fn prepaint<R>(
1708 &mut self,
1709 global_id: Option<&GlobalElementId>,
1710 _inspector_id: Option<&InspectorElementId>,
1711 bounds: Bounds<Pixels>,
1712 content_size: Size<Pixels>,
1713 window: &mut Window,
1714 cx: &mut App,
1715 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
1716 ) -> R {
1717 self.content_size = content_size;
1718
1719 #[cfg(any(feature = "inspector", debug_assertions))]
1720 window.with_inspector_state(
1721 _inspector_id,
1722 cx,
1723 |inspector_state: &mut Option<DivInspectorState>, _window| {
1724 if let Some(inspector_state) = inspector_state {
1725 inspector_state.bounds = bounds;
1726 inspector_state.content_size = content_size;
1727 }
1728 },
1729 );
1730
1731 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1732 window.set_focus_handle(focus_handle, cx);
1733 }
1734 window.with_optional_element_state::<InteractiveElementState, _>(
1735 global_id,
1736 |element_state, window| {
1737 let mut element_state =
1738 element_state.map(|element_state| element_state.unwrap_or_default());
1739 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
1740
1741 if let Some(element_state) = element_state.as_mut() {
1742 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1743 let clicked_state = clicked_state.borrow();
1744 self.active = Some(clicked_state.element);
1745 }
1746 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
1747 if self.tooltip_builder.is_some() {
1748 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
1749 } else {
1750 // If there is no longer a tooltip builder, remove the active tooltip.
1751 element_state.active_tooltip.take();
1752 }
1753 }
1754 }
1755
1756 window.with_text_style(style.text_style().cloned(), |window| {
1757 window.with_content_mask(
1758 style.overflow_mask(bounds, window.rem_size()),
1759 |window| {
1760 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
1761 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
1762 } else {
1763 None
1764 };
1765
1766 let scroll_offset =
1767 self.clamp_scroll_position(bounds, &style, window, cx);
1768 let result = f(&style, scroll_offset, hitbox, window, cx);
1769 (result, element_state)
1770 },
1771 )
1772 })
1773 },
1774 )
1775 }
1776
1777 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
1778 self.hitbox_behavior != HitboxBehavior::Normal
1779 || self.window_control.is_some()
1780 || style.mouse_cursor.is_some()
1781 || self.group.is_some()
1782 || self.scroll_offset.is_some()
1783 || self.tracked_focus_handle.is_some()
1784 || self.hover_style.is_some()
1785 || self.group_hover_style.is_some()
1786 || self.hover_listener.is_some()
1787 || !self.mouse_up_listeners.is_empty()
1788 || !self.mouse_down_listeners.is_empty()
1789 || !self.mouse_move_listeners.is_empty()
1790 || !self.click_listeners.is_empty()
1791 || !self.scroll_wheel_listeners.is_empty()
1792 || self.drag_listener.is_some()
1793 || !self.drop_listeners.is_empty()
1794 || self.tooltip_builder.is_some()
1795 || window.is_inspector_picking(cx)
1796 }
1797
1798 fn clamp_scroll_position(
1799 &self,
1800 bounds: Bounds<Pixels>,
1801 style: &Style,
1802 window: &mut Window,
1803 _cx: &mut App,
1804 ) -> Point<Pixels> {
1805 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
1806 const ROUNDING_FACTOR: f32 = 100.0;
1807 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
1808 }
1809
1810 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
1811 let mut scroll_to_bottom = false;
1812 let mut tracked_scroll_handle = self
1813 .tracked_scroll_handle
1814 .as_ref()
1815 .map(|handle| handle.0.borrow_mut());
1816 if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
1817 scroll_handle_state.overflow = style.overflow;
1818 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
1819 }
1820
1821 let rem_size = window.rem_size();
1822 let padding = style.padding.to_pixels(bounds.size.into(), rem_size);
1823 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
1824 // The floating point values produced by Taffy and ours often vary
1825 // slightly after ~5 decimal places. This can lead to cases where after
1826 // subtracting these, the container becomes scrollable for less than
1827 // 0.00000x pixels. As we generally don't benefit from a precision that
1828 // high for the maximum scroll, we round the scroll max to 2 decimal
1829 // places here.
1830 let padded_content_size = self.content_size + padding_size;
1831 let scroll_max = (padded_content_size - bounds.size)
1832 .map(round_to_two_decimals)
1833 .max(&Default::default());
1834 // Clamp scroll offset in case scroll max is smaller now (e.g., if children
1835 // were removed or the bounds became larger).
1836 let mut scroll_offset = scroll_offset.borrow_mut();
1837
1838 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.width, px(0.));
1839 if scroll_to_bottom {
1840 scroll_offset.y = -scroll_max.height;
1841 } else {
1842 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.height, px(0.));
1843 }
1844
1845 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
1846 scroll_handle_state.max_offset = scroll_max;
1847 scroll_handle_state.bounds = bounds;
1848 }
1849
1850 *scroll_offset
1851 } else {
1852 Point::default()
1853 }
1854 }
1855
1856 /// Paint this element according to this interactivity state's configured styles
1857 /// and bind the element's mouse and keyboard events.
1858 ///
1859 /// content_size is the size of the content of the element, which may be larger than the
1860 /// element's bounds if the element is scrollable.
1861 ///
1862 /// the final computed style will be passed to the provided function, along
1863 /// with the current scroll offset
1864 pub fn paint(
1865 &mut self,
1866 global_id: Option<&GlobalElementId>,
1867 _inspector_id: Option<&InspectorElementId>,
1868 bounds: Bounds<Pixels>,
1869 hitbox: Option<&Hitbox>,
1870 window: &mut Window,
1871 cx: &mut App,
1872 f: impl FnOnce(&Style, &mut Window, &mut App),
1873 ) {
1874 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
1875 window.with_optional_element_state::<InteractiveElementState, _>(
1876 global_id,
1877 |element_state, window| {
1878 let mut element_state =
1879 element_state.map(|element_state| element_state.unwrap_or_default());
1880
1881 if let Some(element_state) = element_state.as_mut() {
1882 element_state.cached_bounds = Some(bounds);
1883 }
1884
1885 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
1886
1887 #[cfg(any(feature = "test-support", test))]
1888 if let Some(debug_selector) = &self.debug_selector {
1889 window
1890 .next_frame
1891 .debug_bounds
1892 .insert(debug_selector.clone(), bounds);
1893 }
1894
1895 self.paint_hover_group_handler(window, cx);
1896
1897 if style.visibility == Visibility::Hidden {
1898 return ((), element_state);
1899 }
1900
1901 let mut tab_group = None;
1902 if self.tab_group {
1903 tab_group = self.tab_index;
1904 }
1905 if let Some(focus_handle) = &self.tracked_focus_handle {
1906 window.next_frame.tab_stops.insert(focus_handle);
1907 }
1908
1909 window.with_element_opacity(style.opacity, |window| {
1910 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
1911 window.with_text_style(style.text_style().cloned(), |window| {
1912 window.with_content_mask(
1913 style.overflow_mask(bounds, window.rem_size()),
1914 |window| {
1915 window.with_tab_group(tab_group, |window| {
1916 if let Some(hitbox) = hitbox {
1917 #[cfg(debug_assertions)]
1918 self.paint_debug_info(
1919 global_id, hitbox, &style, window, cx,
1920 );
1921
1922 if let Some(drag) = cx.active_drag.as_ref() {
1923 if let Some(mouse_cursor) = drag.cursor_style {
1924 window.set_window_cursor_style(mouse_cursor);
1925 }
1926 } else {
1927 if let Some(mouse_cursor) = style.mouse_cursor {
1928 window.set_cursor_style(mouse_cursor, hitbox);
1929 }
1930 }
1931
1932 if let Some(group) = self.group.clone() {
1933 GroupHitboxes::push(group, hitbox.id, cx);
1934 }
1935
1936 if let Some(area) = self.window_control {
1937 window.insert_window_control_hitbox(
1938 area,
1939 hitbox.clone(),
1940 );
1941 }
1942
1943 self.paint_mouse_listeners(
1944 hitbox,
1945 element_state.as_mut(),
1946 window,
1947 cx,
1948 );
1949 self.paint_scroll_listener(hitbox, &style, window, cx);
1950 }
1951
1952 self.paint_keyboard_listeners(window, cx);
1953 f(&style, window, cx);
1954
1955 if let Some(_hitbox) = hitbox {
1956 #[cfg(any(feature = "inspector", debug_assertions))]
1957 window.insert_inspector_hitbox(
1958 _hitbox.id,
1959 _inspector_id,
1960 cx,
1961 );
1962
1963 if let Some(group) = self.group.as_ref() {
1964 GroupHitboxes::pop(group, cx);
1965 }
1966 }
1967 })
1968 },
1969 );
1970 });
1971 });
1972 });
1973
1974 ((), element_state)
1975 },
1976 );
1977 }
1978
1979 #[cfg(debug_assertions)]
1980 fn paint_debug_info(
1981 &self,
1982 global_id: Option<&GlobalElementId>,
1983 hitbox: &Hitbox,
1984 style: &Style,
1985 window: &mut Window,
1986 cx: &mut App,
1987 ) {
1988 use crate::{BorderStyle, TextAlign};
1989
1990 if global_id.is_some()
1991 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
1992 && hitbox.is_hovered(window)
1993 {
1994 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
1995 let element_id = format!("{:?}", global_id.unwrap());
1996 let str_len = element_id.len();
1997
1998 let render_debug_text = |window: &mut Window| {
1999 if let Some(text) = window
2000 .text_system()
2001 .shape_text(
2002 element_id.into(),
2003 FONT_SIZE,
2004 &[window.text_style().to_run(str_len)],
2005 None,
2006 None,
2007 )
2008 .ok()
2009 .and_then(|mut text| text.pop())
2010 {
2011 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2012 .ok();
2013
2014 let text_bounds = crate::Bounds {
2015 origin: hitbox.origin,
2016 size: text.size(FONT_SIZE),
2017 };
2018 if self.source_location.is_some()
2019 && text_bounds.contains(&window.mouse_position())
2020 && window.modifiers().secondary()
2021 {
2022 let secondary_held = window.modifiers().secondary();
2023 window.on_key_event({
2024 move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2025 if e.modifiers.secondary() != secondary_held
2026 && text_bounds.contains(&window.mouse_position())
2027 {
2028 window.refresh();
2029 }
2030 }
2031 });
2032
2033 let was_hovered = hitbox.is_hovered(window);
2034 let current_view = window.current_view();
2035 window.on_mouse_event({
2036 let hitbox = hitbox.clone();
2037 move |_: &MouseMoveEvent, phase, window, cx| {
2038 if phase == DispatchPhase::Capture {
2039 let hovered = hitbox.is_hovered(window);
2040 if hovered != was_hovered {
2041 cx.notify(current_view)
2042 }
2043 }
2044 }
2045 });
2046
2047 window.on_mouse_event({
2048 let hitbox = hitbox.clone();
2049 let location = self.source_location.unwrap();
2050 move |e: &crate::MouseDownEvent, phase, window, cx| {
2051 if text_bounds.contains(&e.position)
2052 && phase.capture()
2053 && hitbox.is_hovered(window)
2054 {
2055 cx.stop_propagation();
2056 let Ok(dir) = std::env::current_dir() else {
2057 return;
2058 };
2059
2060 eprintln!(
2061 "This element was created at:\n{}:{}:{}",
2062 dir.join(location.file()).to_string_lossy(),
2063 location.line(),
2064 location.column()
2065 );
2066 }
2067 }
2068 });
2069 window.paint_quad(crate::outline(
2070 crate::Bounds {
2071 origin: hitbox.origin
2072 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2073 size: crate::Size {
2074 width: text_bounds.size.width,
2075 height: crate::px(1.),
2076 },
2077 },
2078 crate::red(),
2079 BorderStyle::default(),
2080 ))
2081 }
2082 }
2083 };
2084
2085 window.with_text_style(
2086 Some(crate::TextStyleRefinement {
2087 color: Some(crate::red()),
2088 line_height: Some(FONT_SIZE.into()),
2089 background_color: Some(crate::white()),
2090 ..Default::default()
2091 }),
2092 render_debug_text,
2093 )
2094 }
2095 }
2096
2097 fn paint_mouse_listeners(
2098 &mut self,
2099 hitbox: &Hitbox,
2100 element_state: Option<&mut InteractiveElementState>,
2101 window: &mut Window,
2102 cx: &mut App,
2103 ) {
2104 let is_focused = self
2105 .tracked_focus_handle
2106 .as_ref()
2107 .map(|handle| handle.is_focused(window))
2108 .unwrap_or(false);
2109
2110 // If this element can be focused, register a mouse down listener
2111 // that will automatically transfer focus when hitting the element.
2112 // This behavior can be suppressed by using `cx.prevent_default()`.
2113 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2114 let hitbox = hitbox.clone();
2115 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _| {
2116 if phase == DispatchPhase::Bubble
2117 && hitbox.is_hovered(window)
2118 && !window.default_prevented()
2119 {
2120 window.focus(&focus_handle);
2121 // If there is a parent that is also focusable, prevent it
2122 // from transferring focus because we already did so.
2123 window.prevent_default();
2124 }
2125 });
2126 }
2127
2128 for listener in self.mouse_down_listeners.drain(..) {
2129 let hitbox = hitbox.clone();
2130 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2131 listener(event, phase, &hitbox, window, cx);
2132 })
2133 }
2134
2135 for listener in self.mouse_up_listeners.drain(..) {
2136 let hitbox = hitbox.clone();
2137 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2138 listener(event, phase, &hitbox, window, cx);
2139 })
2140 }
2141
2142 for listener in self.mouse_move_listeners.drain(..) {
2143 let hitbox = hitbox.clone();
2144 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2145 listener(event, phase, &hitbox, window, cx);
2146 })
2147 }
2148
2149 for listener in self.scroll_wheel_listeners.drain(..) {
2150 let hitbox = hitbox.clone();
2151 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2152 listener(event, phase, &hitbox, window, cx);
2153 })
2154 }
2155
2156 if self.hover_style.is_some()
2157 || self.base_style.mouse_cursor.is_some()
2158 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2159 {
2160 let hitbox = hitbox.clone();
2161 let was_hovered = hitbox.is_hovered(window);
2162 let current_view = window.current_view();
2163 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2164 let hovered = hitbox.is_hovered(window);
2165 if phase == DispatchPhase::Capture && hovered != was_hovered {
2166 cx.notify(current_view);
2167 }
2168 });
2169 }
2170 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2171
2172 let mut drag_listener = mem::take(&mut self.drag_listener);
2173 let drop_listeners = mem::take(&mut self.drop_listeners);
2174 let click_listeners = mem::take(&mut self.click_listeners);
2175 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2176
2177 if !drop_listeners.is_empty() {
2178 let hitbox = hitbox.clone();
2179 window.on_mouse_event({
2180 move |_: &MouseUpEvent, phase, window, cx| {
2181 if let Some(drag) = &cx.active_drag
2182 && phase == DispatchPhase::Bubble
2183 && hitbox.is_hovered(window)
2184 {
2185 let drag_state_type = drag.value.as_ref().type_id();
2186 for (drop_state_type, listener) in &drop_listeners {
2187 if *drop_state_type == drag_state_type {
2188 let drag = cx
2189 .active_drag
2190 .take()
2191 .expect("checked for type drag state type above");
2192
2193 let mut can_drop = true;
2194 if let Some(predicate) = &can_drop_predicate {
2195 can_drop = predicate(drag.value.as_ref(), window, cx);
2196 }
2197
2198 if can_drop {
2199 listener(drag.value.as_ref(), window, cx);
2200 window.refresh();
2201 cx.stop_propagation();
2202 }
2203 }
2204 }
2205 }
2206 }
2207 });
2208 }
2209
2210 if let Some(element_state) = element_state {
2211 if !click_listeners.is_empty() || drag_listener.is_some() {
2212 let pending_mouse_down = element_state
2213 .pending_mouse_down
2214 .get_or_insert_with(Default::default)
2215 .clone();
2216
2217 let clicked_state = element_state
2218 .clicked_state
2219 .get_or_insert_with(Default::default)
2220 .clone();
2221
2222 window.on_mouse_event({
2223 let pending_mouse_down = pending_mouse_down.clone();
2224 let hitbox = hitbox.clone();
2225 move |event: &MouseDownEvent, phase, window, _cx| {
2226 if phase == DispatchPhase::Bubble
2227 && event.button == MouseButton::Left
2228 && hitbox.is_hovered(window)
2229 {
2230 *pending_mouse_down.borrow_mut() = Some(event.clone());
2231 window.refresh();
2232 }
2233 }
2234 });
2235
2236 window.on_mouse_event({
2237 let pending_mouse_down = pending_mouse_down.clone();
2238 let hitbox = hitbox.clone();
2239 move |event: &MouseMoveEvent, phase, window, cx| {
2240 if phase == DispatchPhase::Capture {
2241 return;
2242 }
2243
2244 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2245 if let Some(mouse_down) = pending_mouse_down.clone()
2246 && !cx.has_active_drag()
2247 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2248 && let Some((drag_value, drag_listener)) = drag_listener.take()
2249 {
2250 *clicked_state.borrow_mut() = ElementClickedState::default();
2251 let cursor_offset = event.position - hitbox.origin;
2252 let drag =
2253 (drag_listener)(drag_value.as_ref(), cursor_offset, window, cx);
2254 cx.active_drag = Some(AnyDrag {
2255 view: drag,
2256 value: drag_value,
2257 cursor_offset,
2258 cursor_style: drag_cursor_style,
2259 });
2260 pending_mouse_down.take();
2261 window.refresh();
2262 cx.stop_propagation();
2263 }
2264 }
2265 });
2266
2267 if is_focused {
2268 // Press enter, space to trigger click, when the element is focused.
2269 window.on_key_event({
2270 let click_listeners = click_listeners.clone();
2271 let hitbox = hitbox.clone();
2272 move |event: &KeyUpEvent, phase, window, cx| {
2273 if phase.bubble() && !window.default_prevented() {
2274 let stroke = &event.keystroke;
2275 let keyboard_button = if stroke.key.eq("enter") {
2276 Some(KeyboardButton::Enter)
2277 } else if stroke.key.eq("space") {
2278 Some(KeyboardButton::Space)
2279 } else {
2280 None
2281 };
2282
2283 if let Some(button) = keyboard_button
2284 && !stroke.modifiers.modified()
2285 {
2286 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2287 button,
2288 bounds: hitbox.bounds,
2289 });
2290
2291 for listener in &click_listeners {
2292 listener(&click_event, window, cx);
2293 }
2294 }
2295 }
2296 }
2297 });
2298 }
2299
2300 window.on_mouse_event({
2301 let mut captured_mouse_down = None;
2302 let hitbox = hitbox.clone();
2303 move |event: &MouseUpEvent, phase, window, cx| match phase {
2304 // Clear the pending mouse down during the capture phase,
2305 // so that it happens even if another event handler stops
2306 // propagation.
2307 DispatchPhase::Capture => {
2308 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2309 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2310 captured_mouse_down = pending_mouse_down.take();
2311 window.refresh();
2312 } else if pending_mouse_down.is_some() {
2313 // Clear the pending mouse down event (without firing click handlers)
2314 // if the hitbox is not being hovered.
2315 // This avoids dragging elements that changed their position
2316 // immediately after being clicked.
2317 // See https://github.com/zed-industries/zed/issues/24600 for more details
2318 pending_mouse_down.take();
2319 window.refresh();
2320 }
2321 }
2322 // Fire click handlers during the bubble phase.
2323 DispatchPhase::Bubble => {
2324 if let Some(mouse_down) = captured_mouse_down.take() {
2325 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2326 down: mouse_down,
2327 up: event.clone(),
2328 });
2329 for listener in &click_listeners {
2330 listener(&mouse_click, window, cx);
2331 }
2332 }
2333 }
2334 }
2335 });
2336 }
2337
2338 if let Some(hover_listener) = self.hover_listener.take() {
2339 let hitbox = hitbox.clone();
2340 let was_hovered = element_state
2341 .hover_state
2342 .get_or_insert_with(Default::default)
2343 .clone();
2344 let has_mouse_down = element_state
2345 .pending_mouse_down
2346 .get_or_insert_with(Default::default)
2347 .clone();
2348
2349 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2350 if phase != DispatchPhase::Bubble {
2351 return;
2352 }
2353 let is_hovered = has_mouse_down.borrow().is_none()
2354 && !cx.has_active_drag()
2355 && hitbox.is_hovered(window);
2356 let mut was_hovered = was_hovered.borrow_mut();
2357
2358 if is_hovered != *was_hovered {
2359 *was_hovered = is_hovered;
2360 drop(was_hovered);
2361
2362 hover_listener(&is_hovered, window, cx);
2363 }
2364 });
2365 }
2366
2367 if let Some(tooltip_builder) = self.tooltip_builder.take() {
2368 let active_tooltip = element_state
2369 .active_tooltip
2370 .get_or_insert_with(Default::default)
2371 .clone();
2372 let pending_mouse_down = element_state
2373 .pending_mouse_down
2374 .get_or_insert_with(Default::default)
2375 .clone();
2376
2377 let tooltip_is_hoverable = tooltip_builder.hoverable;
2378 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
2379 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
2380 });
2381 // Use bounds instead of testing hitbox since this is called during prepaint.
2382 let check_is_hovered_during_prepaint = Rc::new({
2383 let pending_mouse_down = pending_mouse_down.clone();
2384 let source_bounds = hitbox.bounds;
2385 move |window: &Window| {
2386 pending_mouse_down.borrow().is_none()
2387 && source_bounds.contains(&window.mouse_position())
2388 }
2389 });
2390 let check_is_hovered = Rc::new({
2391 let hitbox = hitbox.clone();
2392 move |window: &Window| {
2393 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
2394 }
2395 });
2396 register_tooltip_mouse_handlers(
2397 &active_tooltip,
2398 self.tooltip_id,
2399 build_tooltip,
2400 check_is_hovered,
2401 check_is_hovered_during_prepaint,
2402 window,
2403 );
2404 }
2405
2406 let active_state = element_state
2407 .clicked_state
2408 .get_or_insert_with(Default::default)
2409 .clone();
2410 if active_state.borrow().is_clicked() {
2411 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
2412 if phase == DispatchPhase::Capture {
2413 *active_state.borrow_mut() = ElementClickedState::default();
2414 window.refresh();
2415 }
2416 });
2417 } else {
2418 let active_group_hitbox = self
2419 .group_active_style
2420 .as_ref()
2421 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
2422 let hitbox = hitbox.clone();
2423 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
2424 if phase == DispatchPhase::Bubble && !window.default_prevented() {
2425 let group_hovered = active_group_hitbox
2426 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
2427 let element_hovered = hitbox.is_hovered(window);
2428 if group_hovered || element_hovered {
2429 *active_state.borrow_mut() = ElementClickedState {
2430 group: group_hovered,
2431 element: element_hovered,
2432 };
2433 window.refresh();
2434 }
2435 }
2436 });
2437 }
2438 }
2439 }
2440
2441 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
2442 let key_down_listeners = mem::take(&mut self.key_down_listeners);
2443 let key_up_listeners = mem::take(&mut self.key_up_listeners);
2444 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
2445 let action_listeners = mem::take(&mut self.action_listeners);
2446 if let Some(context) = self.key_context.clone() {
2447 window.set_key_context(context);
2448 }
2449
2450 for listener in key_down_listeners {
2451 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
2452 listener(event, phase, window, cx);
2453 })
2454 }
2455
2456 for listener in key_up_listeners {
2457 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
2458 listener(event, phase, window, cx);
2459 })
2460 }
2461
2462 for listener in modifiers_changed_listeners {
2463 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
2464 listener(event, window, cx);
2465 })
2466 }
2467
2468 for (action_type, listener) in action_listeners {
2469 window.on_action(action_type, listener)
2470 }
2471 }
2472
2473 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
2474 let group_hitbox = self
2475 .group_hover_style
2476 .as_ref()
2477 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
2478
2479 if let Some(group_hitbox) = group_hitbox {
2480 let was_hovered = group_hitbox.is_hovered(window);
2481 let current_view = window.current_view();
2482 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2483 let hovered = group_hitbox.is_hovered(window);
2484 if phase == DispatchPhase::Capture && hovered != was_hovered {
2485 cx.notify(current_view);
2486 }
2487 });
2488 }
2489 }
2490
2491 fn paint_scroll_listener(
2492 &self,
2493 hitbox: &Hitbox,
2494 style: &Style,
2495 window: &mut Window,
2496 _cx: &mut App,
2497 ) {
2498 if let Some(scroll_offset) = self.scroll_offset.clone() {
2499 let overflow = style.overflow;
2500 let allow_concurrent_scroll = style.allow_concurrent_scroll;
2501 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
2502 let line_height = window.line_height();
2503 let hitbox = hitbox.clone();
2504 let current_view = window.current_view();
2505 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2506 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
2507 let mut scroll_offset = scroll_offset.borrow_mut();
2508 let old_scroll_offset = *scroll_offset;
2509 let delta = event.delta.pixel_delta(line_height);
2510
2511 let mut delta_x = Pixels::ZERO;
2512 if overflow.x == Overflow::Scroll {
2513 if !delta.x.is_zero() {
2514 delta_x = delta.x;
2515 } else if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll {
2516 delta_x = delta.y;
2517 }
2518 }
2519 let mut delta_y = Pixels::ZERO;
2520 if overflow.y == Overflow::Scroll {
2521 if !delta.y.is_zero() {
2522 delta_y = delta.y;
2523 } else if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll {
2524 delta_y = delta.x;
2525 }
2526 }
2527 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
2528 if delta_x.abs() > delta_y.abs() {
2529 delta_y = Pixels::ZERO;
2530 } else {
2531 delta_x = Pixels::ZERO;
2532 }
2533 }
2534 scroll_offset.y += delta_y;
2535 scroll_offset.x += delta_x;
2536 if *scroll_offset != old_scroll_offset {
2537 cx.notify(current_view);
2538 }
2539 }
2540 });
2541 }
2542 }
2543
2544 /// Compute the visual style for this element, based on the current bounds and the element's state.
2545 pub fn compute_style(
2546 &self,
2547 global_id: Option<&GlobalElementId>,
2548 hitbox: Option<&Hitbox>,
2549 window: &mut Window,
2550 cx: &mut App,
2551 ) -> Style {
2552 window.with_optional_element_state(global_id, |element_state, window| {
2553 let mut element_state =
2554 element_state.map(|element_state| element_state.unwrap_or_default());
2555 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2556 (style, element_state)
2557 })
2558 }
2559
2560 /// Called from internal methods that have already called with_element_state.
2561 fn compute_style_internal(
2562 &self,
2563 hitbox: Option<&Hitbox>,
2564 element_state: Option<&mut InteractiveElementState>,
2565 window: &mut Window,
2566 cx: &mut App,
2567 ) -> Style {
2568 let mut style = Style::default();
2569 style.refine(&self.base_style);
2570
2571 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2572 if let Some(in_focus_style) = self.in_focus_style.as_ref()
2573 && focus_handle.within_focused(window, cx)
2574 {
2575 style.refine(in_focus_style);
2576 }
2577
2578 if let Some(focus_style) = self.focus_style.as_ref()
2579 && focus_handle.is_focused(window)
2580 {
2581 style.refine(focus_style);
2582 }
2583
2584 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
2585 && focus_handle.is_focused(window)
2586 && window.last_input_was_keyboard()
2587 {
2588 style.refine(focus_visible_style);
2589 }
2590 }
2591
2592 if let Some(hitbox) = hitbox {
2593 if !cx.has_active_drag() {
2594 if let Some(group_hover) = self.group_hover_style.as_ref()
2595 && let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx)
2596 && group_hitbox_id.is_hovered(window)
2597 {
2598 style.refine(&group_hover.style);
2599 }
2600
2601 if let Some(hover_style) = self.hover_style.as_ref()
2602 && hitbox.is_hovered(window)
2603 {
2604 style.refine(hover_style);
2605 }
2606 }
2607
2608 if let Some(drag) = cx.active_drag.take() {
2609 let mut can_drop = true;
2610 if let Some(can_drop_predicate) = &self.can_drop_predicate {
2611 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
2612 }
2613
2614 if can_drop {
2615 for (state_type, group_drag_style) in &self.group_drag_over_styles {
2616 if let Some(group_hitbox_id) =
2617 GroupHitboxes::get(&group_drag_style.group, cx)
2618 && *state_type == drag.value.as_ref().type_id()
2619 && group_hitbox_id.is_hovered(window)
2620 {
2621 style.refine(&group_drag_style.style);
2622 }
2623 }
2624
2625 for (state_type, build_drag_over_style) in &self.drag_over_styles {
2626 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
2627 {
2628 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
2629 }
2630 }
2631 }
2632
2633 style.mouse_cursor = drag.cursor_style;
2634 cx.active_drag = Some(drag);
2635 }
2636 }
2637
2638 if let Some(element_state) = element_state {
2639 let clicked_state = element_state
2640 .clicked_state
2641 .get_or_insert_with(Default::default)
2642 .borrow();
2643 if clicked_state.group
2644 && let Some(group) = self.group_active_style.as_ref()
2645 {
2646 style.refine(&group.style)
2647 }
2648
2649 if let Some(active_style) = self.active_style.as_ref()
2650 && clicked_state.element
2651 {
2652 style.refine(active_style)
2653 }
2654 }
2655
2656 style
2657 }
2658}
2659
2660/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks
2661/// and scroll offsets.
2662#[derive(Default)]
2663pub struct InteractiveElementState {
2664 pub(crate) focus_handle: Option<FocusHandle>,
2665 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
2666 pub(crate) hover_state: Option<Rc<RefCell<bool>>>,
2667 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
2668 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2669 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
2670 pub(crate) cached_bounds: Option<Bounds<Pixels>>,
2671}
2672
2673/// Whether or not the element or a group that contains it is clicked by the mouse.
2674#[derive(Copy, Clone, Default, Eq, PartialEq)]
2675pub struct ElementClickedState {
2676 /// True if this element's group has been clicked, false otherwise
2677 pub group: bool,
2678
2679 /// True if this element has been clicked, false otherwise
2680 pub element: bool,
2681}
2682
2683impl ElementClickedState {
2684 fn is_clicked(&self) -> bool {
2685 self.group || self.element
2686 }
2687}
2688
2689pub(crate) enum ActiveTooltip {
2690 /// Currently delaying before showing the tooltip.
2691 WaitingForShow { _task: Task<()> },
2692 /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
2693 Visible {
2694 tooltip: AnyTooltip,
2695 is_hoverable: bool,
2696 },
2697 /// Tooltip is visible and hoverable, but the mouse is no longer hovering. Currently delaying
2698 /// before hiding it.
2699 WaitingForHide {
2700 tooltip: AnyTooltip,
2701 _task: Task<()>,
2702 },
2703}
2704
2705pub(crate) fn clear_active_tooltip(
2706 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2707 window: &mut Window,
2708) {
2709 match active_tooltip.borrow_mut().take() {
2710 None => {}
2711 Some(ActiveTooltip::WaitingForShow { .. }) => {}
2712 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
2713 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
2714 }
2715}
2716
2717pub(crate) fn clear_active_tooltip_if_not_hoverable(
2718 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2719 window: &mut Window,
2720) {
2721 let should_clear = match active_tooltip.borrow().as_ref() {
2722 None => false,
2723 Some(ActiveTooltip::WaitingForShow { .. }) => false,
2724 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
2725 Some(ActiveTooltip::WaitingForHide { .. }) => false,
2726 };
2727 if should_clear {
2728 active_tooltip.borrow_mut().take();
2729 window.refresh();
2730 }
2731}
2732
2733pub(crate) fn set_tooltip_on_window(
2734 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2735 window: &mut Window,
2736) -> Option<TooltipId> {
2737 let tooltip = match active_tooltip.borrow().as_ref() {
2738 None => return None,
2739 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
2740 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
2741 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
2742 };
2743 Some(window.set_tooltip(tooltip))
2744}
2745
2746pub(crate) fn register_tooltip_mouse_handlers(
2747 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2748 tooltip_id: Option<TooltipId>,
2749 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
2750 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
2751 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
2752 window: &mut Window,
2753) {
2754 window.on_mouse_event({
2755 let active_tooltip = active_tooltip.clone();
2756 let build_tooltip = build_tooltip.clone();
2757 let check_is_hovered = check_is_hovered.clone();
2758 move |_: &MouseMoveEvent, phase, window, cx| {
2759 handle_tooltip_mouse_move(
2760 &active_tooltip,
2761 &build_tooltip,
2762 &check_is_hovered,
2763 &check_is_hovered_during_prepaint,
2764 phase,
2765 window,
2766 cx,
2767 )
2768 }
2769 });
2770
2771 window.on_mouse_event({
2772 let active_tooltip = active_tooltip.clone();
2773 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
2774 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
2775 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
2776 }
2777 }
2778 });
2779
2780 window.on_mouse_event({
2781 let active_tooltip = active_tooltip.clone();
2782 move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
2783 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
2784 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
2785 }
2786 }
2787 });
2788}
2789
2790/// Handles displaying tooltips when an element is hovered.
2791///
2792/// The mouse hovering logic also relies on being called from window prepaint in order to handle the
2793/// case where the element the tooltip is on is not rendered - in that case its mouse listeners are
2794/// also not registered. During window prepaint, the hitbox information is not available, so
2795/// `check_is_hovered_during_prepaint` is used which bases the check off of the absolute bounds of
2796/// the element.
2797///
2798/// TODO: There's a minor bug due to the use of absolute bounds while checking during prepaint - it
2799/// does not know if the hitbox is occluded. In the case where a tooltip gets displayed and then
2800/// gets occluded after display, it will stick around until the mouse exits the hover bounds.
2801fn handle_tooltip_mouse_move(
2802 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2803 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
2804 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
2805 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
2806 phase: DispatchPhase,
2807 window: &mut Window,
2808 cx: &mut App,
2809) {
2810 // Separates logic for what mutation should occur from applying it, to avoid overlapping
2811 // RefCell borrows.
2812 enum Action {
2813 None,
2814 CancelShow,
2815 ScheduleShow,
2816 }
2817
2818 let action = match active_tooltip.borrow().as_ref() {
2819 None => {
2820 let is_hovered = check_is_hovered(window);
2821 if is_hovered && phase.bubble() {
2822 Action::ScheduleShow
2823 } else {
2824 Action::None
2825 }
2826 }
2827 Some(ActiveTooltip::WaitingForShow { .. }) => {
2828 let is_hovered = check_is_hovered(window);
2829 if is_hovered {
2830 Action::None
2831 } else {
2832 Action::CancelShow
2833 }
2834 }
2835 // These are handled in check_visible_and_update.
2836 Some(ActiveTooltip::Visible { .. }) | Some(ActiveTooltip::WaitingForHide { .. }) => {
2837 Action::None
2838 }
2839 };
2840
2841 match action {
2842 Action::None => {}
2843 Action::CancelShow => {
2844 // Cancel waiting to show tooltip when it is no longer hovered.
2845 active_tooltip.borrow_mut().take();
2846 }
2847 Action::ScheduleShow => {
2848 let delayed_show_task = window.spawn(cx, {
2849 let active_tooltip = active_tooltip.clone();
2850 let build_tooltip = build_tooltip.clone();
2851 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
2852 async move |cx| {
2853 cx.background_executor().timer(TOOLTIP_SHOW_DELAY).await;
2854 cx.update(|window, cx| {
2855 let new_tooltip =
2856 build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
2857 let active_tooltip = active_tooltip.clone();
2858 ActiveTooltip::Visible {
2859 tooltip: AnyTooltip {
2860 view,
2861 mouse_position: window.mouse_position(),
2862 check_visible_and_update: Rc::new(
2863 move |tooltip_bounds, window, cx| {
2864 handle_tooltip_check_visible_and_update(
2865 &active_tooltip,
2866 tooltip_is_hoverable,
2867 &check_is_hovered_during_prepaint,
2868 tooltip_bounds,
2869 window,
2870 cx,
2871 )
2872 },
2873 ),
2874 },
2875 is_hoverable: tooltip_is_hoverable,
2876 }
2877 });
2878 *active_tooltip.borrow_mut() = new_tooltip;
2879 window.refresh();
2880 })
2881 .ok();
2882 }
2883 });
2884 active_tooltip
2885 .borrow_mut()
2886 .replace(ActiveTooltip::WaitingForShow {
2887 _task: delayed_show_task,
2888 });
2889 }
2890 }
2891}
2892
2893/// Returns a callback which will be called by window prepaint to update tooltip visibility. The
2894/// purpose of doing this logic here instead of the mouse move handler is that the mouse move
2895/// handler won't get called when the element is not painted (e.g. via use of `visible_on_hover`).
2896fn handle_tooltip_check_visible_and_update(
2897 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2898 tooltip_is_hoverable: bool,
2899 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
2900 tooltip_bounds: Bounds<Pixels>,
2901 window: &mut Window,
2902 cx: &mut App,
2903) -> bool {
2904 // Separates logic for what mutation should occur from applying it, to avoid overlapping RefCell
2905 // borrows.
2906 enum Action {
2907 None,
2908 Hide,
2909 ScheduleHide(AnyTooltip),
2910 CancelHide(AnyTooltip),
2911 }
2912
2913 let is_hovered = check_is_hovered(window)
2914 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
2915 let action = match active_tooltip.borrow().as_ref() {
2916 Some(ActiveTooltip::Visible { tooltip, .. }) => {
2917 if is_hovered {
2918 Action::None
2919 } else {
2920 if tooltip_is_hoverable {
2921 Action::ScheduleHide(tooltip.clone())
2922 } else {
2923 Action::Hide
2924 }
2925 }
2926 }
2927 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
2928 if is_hovered {
2929 Action::CancelHide(tooltip.clone())
2930 } else {
2931 Action::None
2932 }
2933 }
2934 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
2935 };
2936
2937 match action {
2938 Action::None => {}
2939 Action::Hide => clear_active_tooltip(active_tooltip, window),
2940 Action::ScheduleHide(tooltip) => {
2941 let delayed_hide_task = window.spawn(cx, {
2942 let active_tooltip = active_tooltip.clone();
2943 async move |cx| {
2944 cx.background_executor()
2945 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
2946 .await;
2947 if active_tooltip.borrow_mut().take().is_some() {
2948 cx.update(|window, _cx| window.refresh()).ok();
2949 }
2950 }
2951 });
2952 active_tooltip
2953 .borrow_mut()
2954 .replace(ActiveTooltip::WaitingForHide {
2955 tooltip,
2956 _task: delayed_hide_task,
2957 });
2958 }
2959 Action::CancelHide(tooltip) => {
2960 // Cancel waiting to hide tooltip when it becomes hovered.
2961 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
2962 tooltip,
2963 is_hoverable: true,
2964 });
2965 }
2966 }
2967
2968 active_tooltip.borrow().is_some()
2969}
2970
2971#[derive(Default)]
2972pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
2973
2974impl Global for GroupHitboxes {}
2975
2976impl GroupHitboxes {
2977 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
2978 cx.default_global::<Self>()
2979 .0
2980 .get(name)
2981 .and_then(|bounds_stack| bounds_stack.last())
2982 .cloned()
2983 }
2984
2985 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
2986 cx.default_global::<Self>()
2987 .0
2988 .entry(name)
2989 .or_default()
2990 .push(hitbox_id);
2991 }
2992
2993 pub fn pop(name: &SharedString, cx: &mut App) {
2994 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
2995 }
2996}
2997
2998/// A wrapper around an element that can store state, produced after assigning an ElementId.
2999pub struct Stateful<E> {
3000 pub(crate) element: E,
3001}
3002
3003impl<E> Styled for Stateful<E>
3004where
3005 E: Styled,
3006{
3007 fn style(&mut self) -> &mut StyleRefinement {
3008 self.element.style()
3009 }
3010}
3011
3012impl<E> StatefulInteractiveElement for Stateful<E>
3013where
3014 E: Element,
3015 Self: InteractiveElement,
3016{
3017}
3018
3019impl<E> InteractiveElement for Stateful<E>
3020where
3021 E: InteractiveElement,
3022{
3023 fn interactivity(&mut self) -> &mut Interactivity {
3024 self.element.interactivity()
3025 }
3026}
3027
3028impl<E> Element for Stateful<E>
3029where
3030 E: Element,
3031{
3032 type RequestLayoutState = E::RequestLayoutState;
3033 type PrepaintState = E::PrepaintState;
3034
3035 fn id(&self) -> Option<ElementId> {
3036 self.element.id()
3037 }
3038
3039 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3040 self.element.source_location()
3041 }
3042
3043 fn request_layout(
3044 &mut self,
3045 id: Option<&GlobalElementId>,
3046 inspector_id: Option<&InspectorElementId>,
3047 window: &mut Window,
3048 cx: &mut App,
3049 ) -> (LayoutId, Self::RequestLayoutState) {
3050 self.element.request_layout(id, inspector_id, window, cx)
3051 }
3052
3053 fn prepaint(
3054 &mut self,
3055 id: Option<&GlobalElementId>,
3056 inspector_id: Option<&InspectorElementId>,
3057 bounds: Bounds<Pixels>,
3058 state: &mut Self::RequestLayoutState,
3059 window: &mut Window,
3060 cx: &mut App,
3061 ) -> E::PrepaintState {
3062 self.element
3063 .prepaint(id, inspector_id, bounds, state, window, cx)
3064 }
3065
3066 fn paint(
3067 &mut self,
3068 id: Option<&GlobalElementId>,
3069 inspector_id: Option<&InspectorElementId>,
3070 bounds: Bounds<Pixels>,
3071 request_layout: &mut Self::RequestLayoutState,
3072 prepaint: &mut Self::PrepaintState,
3073 window: &mut Window,
3074 cx: &mut App,
3075 ) {
3076 self.element.paint(
3077 id,
3078 inspector_id,
3079 bounds,
3080 request_layout,
3081 prepaint,
3082 window,
3083 cx,
3084 );
3085 }
3086}
3087
3088impl<E> IntoElement for Stateful<E>
3089where
3090 E: Element,
3091{
3092 type Element = Self;
3093
3094 fn into_element(self) -> Self::Element {
3095 self
3096 }
3097}
3098
3099impl<E> ParentElement for Stateful<E>
3100where
3101 E: ParentElement,
3102{
3103 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
3104 self.element.extend(elements)
3105 }
3106}
3107
3108/// Represents an element that can be scrolled *to* in its parent element.
3109/// Contrary to [ScrollHandle::scroll_to_active_item], an anchored element does not have to be an immediate child of the parent.
3110#[derive(Clone)]
3111pub struct ScrollAnchor {
3112 handle: ScrollHandle,
3113 last_origin: Rc<RefCell<Point<Pixels>>>,
3114}
3115
3116impl ScrollAnchor {
3117 /// Creates a [ScrollAnchor] associated with a given [ScrollHandle].
3118 pub fn for_handle(handle: ScrollHandle) -> Self {
3119 Self {
3120 handle,
3121 last_origin: Default::default(),
3122 }
3123 }
3124 /// Request scroll to this item on the next frame.
3125 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
3126 let this = self.clone();
3127
3128 window.on_next_frame(move |_, _| {
3129 let viewport_bounds = this.handle.bounds();
3130 let self_bounds = *this.last_origin.borrow();
3131 this.handle.set_offset(viewport_bounds.origin - self_bounds);
3132 });
3133 }
3134}
3135
3136#[derive(Default, Debug)]
3137struct ScrollHandleState {
3138 offset: Rc<RefCell<Point<Pixels>>>,
3139 bounds: Bounds<Pixels>,
3140 max_offset: Size<Pixels>,
3141 child_bounds: Vec<Bounds<Pixels>>,
3142 scroll_to_bottom: bool,
3143 overflow: Point<Overflow>,
3144 active_item: Option<ScrollActiveItem>,
3145}
3146
3147#[derive(Default, Debug, Clone, Copy)]
3148struct ScrollActiveItem {
3149 index: usize,
3150 strategy: ScrollStrategy,
3151}
3152
3153#[derive(Default, Debug, Clone, Copy)]
3154enum ScrollStrategy {
3155 #[default]
3156 FirstVisible,
3157 Top,
3158}
3159
3160/// A handle to the scrollable aspects of an element.
3161/// Used for accessing scroll state, like the current scroll offset,
3162/// and for mutating the scroll state, like scrolling to a specific child.
3163#[derive(Clone, Debug)]
3164pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
3165
3166impl Default for ScrollHandle {
3167 fn default() -> Self {
3168 Self::new()
3169 }
3170}
3171
3172impl ScrollHandle {
3173 /// Construct a new scroll handle.
3174 pub fn new() -> Self {
3175 Self(Rc::default())
3176 }
3177
3178 /// Get the current scroll offset.
3179 pub fn offset(&self) -> Point<Pixels> {
3180 *self.0.borrow().offset.borrow()
3181 }
3182
3183 /// Get the maximum scroll offset.
3184 pub fn max_offset(&self) -> Size<Pixels> {
3185 self.0.borrow().max_offset
3186 }
3187
3188 /// Get the top child that's scrolled into view.
3189 pub fn top_item(&self) -> usize {
3190 let state = self.0.borrow();
3191 let top = state.bounds.top() - state.offset.borrow().y;
3192
3193 match state.child_bounds.binary_search_by(|bounds| {
3194 if top < bounds.top() {
3195 Ordering::Greater
3196 } else if top > bounds.bottom() {
3197 Ordering::Less
3198 } else {
3199 Ordering::Equal
3200 }
3201 }) {
3202 Ok(ix) => ix,
3203 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
3204 }
3205 }
3206
3207 /// Get the bottom child that's scrolled into view.
3208 pub fn bottom_item(&self) -> usize {
3209 let state = self.0.borrow();
3210 let bottom = state.bounds.bottom() - state.offset.borrow().y;
3211
3212 match state.child_bounds.binary_search_by(|bounds| {
3213 if bottom < bounds.top() {
3214 Ordering::Greater
3215 } else if bottom > bounds.bottom() {
3216 Ordering::Less
3217 } else {
3218 Ordering::Equal
3219 }
3220 }) {
3221 Ok(ix) => ix,
3222 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
3223 }
3224 }
3225
3226 /// Return the bounds into which this child is painted
3227 pub fn bounds(&self) -> Bounds<Pixels> {
3228 self.0.borrow().bounds
3229 }
3230
3231 /// Get the bounds for a specific child.
3232 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
3233 self.0.borrow().child_bounds.get(ix).cloned()
3234 }
3235
3236 /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
3237 pub fn scroll_to_item(&self, ix: usize) {
3238 let mut state = self.0.borrow_mut();
3239 state.active_item = Some(ScrollActiveItem {
3240 index: ix,
3241 strategy: ScrollStrategy::default(),
3242 });
3243 }
3244
3245 /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
3246 /// This scrolls the minimal amount to ensure that the child is the first visible element
3247 pub fn scroll_to_top_of_item(&self, ix: usize) {
3248 let mut state = self.0.borrow_mut();
3249 state.active_item = Some(ScrollActiveItem {
3250 index: ix,
3251 strategy: ScrollStrategy::Top,
3252 });
3253 }
3254
3255 /// Scrolls the minimal amount to either ensure that the child is
3256 /// fully visible or the top element of the view depends on the
3257 /// scroll strategy
3258 fn scroll_to_active_item(&self) {
3259 let mut state = self.0.borrow_mut();
3260
3261 let Some(active_item) = state.active_item else {
3262 return;
3263 };
3264
3265 let active_item = match state.child_bounds.get(active_item.index) {
3266 Some(bounds) => {
3267 let mut scroll_offset = state.offset.borrow_mut();
3268
3269 match active_item.strategy {
3270 ScrollStrategy::FirstVisible => {
3271 if state.overflow.y == Overflow::Scroll {
3272 if bounds.top() + scroll_offset.y < state.bounds.top() {
3273 scroll_offset.y = state.bounds.top() - bounds.top();
3274 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
3275 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
3276 }
3277 }
3278 }
3279 ScrollStrategy::Top => {
3280 scroll_offset.y = state.bounds.top() - bounds.top();
3281 }
3282 }
3283
3284 if state.overflow.x == Overflow::Scroll {
3285 if bounds.left() + scroll_offset.x < state.bounds.left() {
3286 scroll_offset.x = state.bounds.left() - bounds.left();
3287 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
3288 scroll_offset.x = state.bounds.right() - bounds.right();
3289 }
3290 }
3291 None
3292 }
3293 None => Some(active_item),
3294 };
3295 state.active_item = active_item;
3296 }
3297
3298 /// Scrolls to the bottom.
3299 pub fn scroll_to_bottom(&self) {
3300 let mut state = self.0.borrow_mut();
3301 state.scroll_to_bottom = true;
3302 }
3303
3304 /// Set the offset explicitly. The offset is the distance from the top left of the
3305 /// parent container to the top left of the first child.
3306 /// As you scroll further down the offset becomes more negative.
3307 pub fn set_offset(&self, mut position: Point<Pixels>) {
3308 let state = self.0.borrow();
3309 *state.offset.borrow_mut() = position;
3310 }
3311
3312 /// Get the logical scroll top, based on a child index and a pixel offset.
3313 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
3314 let ix = self.top_item();
3315 let state = self.0.borrow();
3316
3317 if let Some(child_bounds) = state.child_bounds.get(ix) {
3318 (
3319 ix,
3320 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
3321 )
3322 } else {
3323 (ix, px(0.))
3324 }
3325 }
3326
3327 /// Get the logical scroll bottom, based on a child index and a pixel offset.
3328 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
3329 let ix = self.bottom_item();
3330 let state = self.0.borrow();
3331
3332 if let Some(child_bounds) = state.child_bounds.get(ix) {
3333 (
3334 ix,
3335 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
3336 )
3337 } else {
3338 (ix, px(0.))
3339 }
3340 }
3341
3342 /// Get the count of children for scrollable item.
3343 pub fn children_count(&self) -> usize {
3344 self.0.borrow().child_bounds.len()
3345 }
3346}