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