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