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 point, px, size, Action, AnyDrag, AnyElement, AnyTooltip, AnyView, AppContext, Bounds,
20 ClickEvent, DispatchPhase, Element, ElementId, FocusHandle, Global, GlobalElementId, Hitbox,
21 HitboxId, IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, LayoutId,
22 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
23 ParentElement, Pixels, Point, Render, ScrollWheelEvent, SharedString, Size, Style,
24 StyleRefinement, Styled, Task, TooltipId, View, Visibility, WindowContext,
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 ops::DerefMut,
37 rc::Rc,
38 time::Duration,
39};
40use taffy::style::Overflow;
41use util::ResultExt;
42
43const DRAG_THRESHOLD: f64 = 2.;
44pub(crate) const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
45
46/// The styling information for a given group.
47pub struct GroupStyle {
48 /// The identifier for this group.
49 pub group: SharedString,
50
51 /// The specific style refinement that this group would apply
52 /// to its children.
53 pub style: Box<StyleRefinement>,
54}
55
56/// An event for when a drag is moving over this element, with the given state type.
57pub struct DragMoveEvent<T> {
58 /// The mouse move event that triggered this drag move event.
59 pub event: MouseMoveEvent,
60
61 /// The bounds of this element.
62 pub bounds: Bounds<Pixels>,
63 drag: PhantomData<T>,
64}
65
66impl<T: 'static> DragMoveEvent<T> {
67 /// Returns the drag state for this event.
68 pub fn drag<'b>(&self, cx: &'b AppContext) -> &'b T {
69 cx.active_drag
70 .as_ref()
71 .and_then(|drag| drag.value.downcast_ref::<T>())
72 .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
73 }
74}
75
76impl Interactivity {
77 /// Bind the given callback to the mouse down event for the given mouse button, during the bubble phase
78 /// The imperative API equivalent of [`InteractiveElement::on_mouse_down`]
79 ///
80 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to the view state from this callback.
81 pub fn on_mouse_down(
82 &mut self,
83 button: MouseButton,
84 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
85 ) {
86 self.mouse_down_listeners
87 .push(Box::new(move |event, phase, hitbox, cx| {
88 if phase == DispatchPhase::Bubble && event.button == button && hitbox.is_hovered(cx)
89 {
90 (listener)(event, cx)
91 }
92 }));
93 }
94
95 /// Bind the given callback to the mouse down event for any button, during the capture phase
96 /// The imperative API equivalent of [`InteractiveElement::capture_any_mouse_down`]
97 ///
98 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
99 pub fn capture_any_mouse_down(
100 &mut self,
101 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
102 ) {
103 self.mouse_down_listeners
104 .push(Box::new(move |event, phase, hitbox, cx| {
105 if phase == DispatchPhase::Capture && hitbox.is_hovered(cx) {
106 (listener)(event, cx)
107 }
108 }));
109 }
110
111 /// Bind the given callback to the mouse down event for any button, during the bubble phase
112 /// the imperative API equivalent to [`InteractiveElement::on_any_mouse_down`]
113 ///
114 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
115 pub fn on_any_mouse_down(
116 &mut self,
117 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
118 ) {
119 self.mouse_down_listeners
120 .push(Box::new(move |event, phase, hitbox, cx| {
121 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
122 (listener)(event, cx)
123 }
124 }));
125 }
126
127 /// Bind the given callback to the mouse up event for the given button, during the bubble phase
128 /// the imperative API equivalent to [`InteractiveElement::on_mouse_up`]
129 ///
130 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
131 pub fn on_mouse_up(
132 &mut self,
133 button: MouseButton,
134 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
135 ) {
136 self.mouse_up_listeners
137 .push(Box::new(move |event, phase, hitbox, cx| {
138 if phase == DispatchPhase::Bubble && event.button == button && hitbox.is_hovered(cx)
139 {
140 (listener)(event, cx)
141 }
142 }));
143 }
144
145 /// Bind the given callback to the mouse up event for any button, during the capture phase
146 /// the imperative API equivalent to [`InteractiveElement::capture_any_mouse_up`]
147 ///
148 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
149 pub fn capture_any_mouse_up(
150 &mut self,
151 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
152 ) {
153 self.mouse_up_listeners
154 .push(Box::new(move |event, phase, hitbox, cx| {
155 if phase == DispatchPhase::Capture && hitbox.is_hovered(cx) {
156 (listener)(event, cx)
157 }
158 }));
159 }
160
161 /// Bind the given callback to the mouse up event for any button, during the bubble phase
162 /// the imperative API equivalent to [`Interactivity::on_any_mouse_up`]
163 ///
164 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
165 pub fn on_any_mouse_up(
166 &mut self,
167 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
168 ) {
169 self.mouse_up_listeners
170 .push(Box::new(move |event, phase, hitbox, cx| {
171 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
172 (listener)(event, cx)
173 }
174 }));
175 }
176
177 /// Bind the given callback to the mouse down event, on any button, during the capture phase,
178 /// when the mouse is outside of the bounds of this element.
179 /// The imperative API equivalent to [`InteractiveElement::on_mouse_down_out`]
180 ///
181 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
182 pub fn on_mouse_down_out(
183 &mut self,
184 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
185 ) {
186 self.mouse_down_listeners
187 .push(Box::new(move |event, phase, hitbox, cx| {
188 if phase == DispatchPhase::Capture && !hitbox.contains(&cx.mouse_position()) {
189 (listener)(event, cx)
190 }
191 }));
192 }
193
194 /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
195 /// when the mouse is outside of the bounds of this element.
196 /// The imperative API equivalent to [`InteractiveElement::on_mouse_up_out`]
197 ///
198 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
199 pub fn on_mouse_up_out(
200 &mut self,
201 button: MouseButton,
202 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
203 ) {
204 self.mouse_up_listeners
205 .push(Box::new(move |event, phase, hitbox, cx| {
206 if phase == DispatchPhase::Capture
207 && event.button == button
208 && !hitbox.is_hovered(cx)
209 {
210 (listener)(event, cx);
211 }
212 }));
213 }
214
215 /// Bind the given callback to the mouse move event, during the bubble phase
216 /// The imperative API equivalent to [`InteractiveElement::on_mouse_move`]
217 ///
218 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
219 pub fn on_mouse_move(
220 &mut self,
221 listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static,
222 ) {
223 self.mouse_move_listeners
224 .push(Box::new(move |event, phase, hitbox, cx| {
225 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
226 (listener)(event, cx);
227 }
228 }));
229 }
230
231 /// Bind the given callback to the mouse drag event of the given type. Note that this
232 /// will be called for all move events, inside or outside of this element, as long as the
233 /// drag was started with this element under the mouse. Useful for implementing draggable
234 /// UIs that don't conform to a drag and drop style interaction, like resizing.
235 /// The imperative API equivalent to [`InteractiveElement::on_drag_move`]
236 ///
237 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
238 pub fn on_drag_move<T>(
239 &mut self,
240 listener: impl Fn(&DragMoveEvent<T>, &mut WindowContext) + 'static,
241 ) where
242 T: 'static,
243 {
244 self.mouse_move_listeners
245 .push(Box::new(move |event, phase, hitbox, cx| {
246 if phase == DispatchPhase::Capture
247 && cx
248 .active_drag
249 .as_ref()
250 .is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::<T>())
251 {
252 (listener)(
253 &DragMoveEvent {
254 event: event.clone(),
255 bounds: hitbox.bounds,
256 drag: PhantomData,
257 },
258 cx,
259 );
260 }
261 }));
262 }
263
264 /// Bind the given callback to scroll wheel events during the bubble phase
265 /// The imperative API equivalent to [`InteractiveElement::on_scroll_wheel`]
266 ///
267 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
268 pub fn on_scroll_wheel(
269 &mut self,
270 listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static,
271 ) {
272 self.scroll_wheel_listeners
273 .push(Box::new(move |event, phase, hitbox, cx| {
274 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
275 (listener)(event, cx);
276 }
277 }));
278 }
279
280 /// Bind the given callback to an action dispatch during the capture phase
281 /// The imperative API equivalent to [`InteractiveElement::capture_action`]
282 ///
283 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
284 pub fn capture_action<A: Action>(
285 &mut self,
286 listener: impl Fn(&A, &mut WindowContext) + 'static,
287 ) {
288 self.action_listeners.push((
289 TypeId::of::<A>(),
290 Box::new(move |action, phase, cx| {
291 let action = action.downcast_ref().unwrap();
292 if phase == DispatchPhase::Capture {
293 (listener)(action, cx)
294 } else {
295 cx.propagate();
296 }
297 }),
298 ));
299 }
300
301 /// Bind the given callback to an action dispatch during the bubble phase
302 /// The imperative API equivalent to [`InteractiveElement::on_action`]
303 ///
304 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
305 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) {
306 self.action_listeners.push((
307 TypeId::of::<A>(),
308 Box::new(move |action, phase, cx| {
309 let action = action.downcast_ref().unwrap();
310 if phase == DispatchPhase::Bubble {
311 (listener)(action, cx)
312 }
313 }),
314 ));
315 }
316
317 /// Bind the given callback to an action dispatch, based on a dynamic action parameter
318 /// instead of a type parameter. Useful for component libraries that want to expose
319 /// action bindings to their users.
320 /// The imperative API equivalent to [`InteractiveElement::on_boxed_action`]
321 ///
322 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
323 pub fn on_boxed_action(
324 &mut self,
325 action: &dyn Action,
326 listener: impl Fn(&dyn Action, &mut WindowContext) + 'static,
327 ) {
328 let action = action.boxed_clone();
329 self.action_listeners.push((
330 (*action).type_id(),
331 Box::new(move |_, phase, cx| {
332 if phase == DispatchPhase::Bubble {
333 (listener)(&*action, cx)
334 }
335 }),
336 ));
337 }
338
339 /// Bind the given callback to key down events during the bubble phase
340 /// The imperative API equivalent to [`InteractiveElement::on_key_down`]
341 ///
342 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
343 pub fn on_key_down(&mut self, listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static) {
344 self.key_down_listeners
345 .push(Box::new(move |event, phase, cx| {
346 if phase == DispatchPhase::Bubble {
347 (listener)(event, cx)
348 }
349 }));
350 }
351
352 /// Bind the given callback to key down events during the capture phase
353 /// The imperative API equivalent to [`InteractiveElement::capture_key_down`]
354 ///
355 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
356 pub fn capture_key_down(
357 &mut self,
358 listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static,
359 ) {
360 self.key_down_listeners
361 .push(Box::new(move |event, phase, cx| {
362 if phase == DispatchPhase::Capture {
363 listener(event, cx)
364 }
365 }));
366 }
367
368 /// Bind the given callback to key up events during the bubble phase
369 /// The imperative API equivalent to [`InteractiveElement::on_key_up`]
370 ///
371 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
372 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) {
373 self.key_up_listeners
374 .push(Box::new(move |event, phase, cx| {
375 if phase == DispatchPhase::Bubble {
376 listener(event, cx)
377 }
378 }));
379 }
380
381 /// Bind the given callback to key up events during the capture phase
382 /// The imperative API equivalent to [`InteractiveElement::on_key_up`]
383 ///
384 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
385 pub fn capture_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) {
386 self.key_up_listeners
387 .push(Box::new(move |event, phase, cx| {
388 if phase == DispatchPhase::Capture {
389 listener(event, cx)
390 }
391 }));
392 }
393
394 /// Bind the given callback to modifiers changing events.
395 /// The imperative API equivalent to [`InteractiveElement::on_modifiers_changed`]
396 ///
397 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
398 pub fn on_modifiers_changed(
399 &mut self,
400 listener: impl Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static,
401 ) {
402 self.modifiers_changed_listeners
403 .push(Box::new(move |event, cx| listener(event, cx)));
404 }
405
406 /// Bind the given callback to drop events of the given type, whether or not the drag started on this element
407 /// The imperative API equivalent to [`InteractiveElement::on_drop`]
408 ///
409 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
410 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut WindowContext) + 'static) {
411 self.drop_listeners.push((
412 TypeId::of::<T>(),
413 Box::new(move |dragged_value, cx| {
414 listener(dragged_value.downcast_ref().unwrap(), cx);
415 }),
416 ));
417 }
418
419 /// Use the given predicate to determine whether or not a drop event should be dispatched to this element
420 /// The imperative API equivalent to [`InteractiveElement::can_drop`]
421 pub fn can_drop(&mut self, predicate: impl Fn(&dyn Any, &mut WindowContext) -> bool + 'static) {
422 self.can_drop_predicate = Some(Box::new(predicate));
423 }
424
425 /// Bind the given callback to click events of this element
426 /// The imperative API equivalent to [`StatefulInteractiveElement::on_click`]
427 ///
428 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
429 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static)
430 where
431 Self: Sized,
432 {
433 self.click_listeners
434 .push(Box::new(move |event, cx| listener(event, cx)));
435 }
436
437 /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
438 /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
439 /// the [`Self::on_drag_move`] API
440 /// The imperative API equivalent to [`StatefulInteractiveElement::on_drag`]
441 ///
442 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
443 pub fn on_drag<T, W>(
444 &mut self,
445 value: T,
446 constructor: impl Fn(&T, &mut WindowContext) -> View<W> + 'static,
447 ) where
448 Self: Sized,
449 T: 'static,
450 W: 'static + Render,
451 {
452 debug_assert!(
453 self.drag_listener.is_none(),
454 "calling on_drag more than once on the same element is not supported"
455 );
456 self.drag_listener = Some((
457 Box::new(value),
458 Box::new(move |value, cx| constructor(value.downcast_ref().unwrap(), cx).into()),
459 ));
460 }
461
462 /// Bind the given callback on the hover start and end events of this element. Note that the boolean
463 /// passed to the callback is true when the hover starts and false when it ends.
464 /// The imperative API equivalent to [`StatefulInteractiveElement::on_drag`]
465 ///
466 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
467 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut WindowContext) + 'static)
468 where
469 Self: Sized,
470 {
471 debug_assert!(
472 self.hover_listener.is_none(),
473 "calling on_hover more than once on the same element is not supported"
474 );
475 self.hover_listener = Some(Box::new(listener));
476 }
477
478 /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
479 /// The imperative API equivalent to [`InteractiveElement::tooltip`]
480 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static)
481 where
482 Self: Sized,
483 {
484 debug_assert!(
485 self.tooltip_builder.is_none(),
486 "calling tooltip more than once on the same element is not supported"
487 );
488 self.tooltip_builder = Some(TooltipBuilder {
489 build: Rc::new(build_tooltip),
490 hoverable: false,
491 });
492 }
493
494 /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
495 /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
496 /// the tooltip. The imperative API equivalent to [`InteractiveElement::hoverable_tooltip`]
497 pub fn hoverable_tooltip(
498 &mut self,
499 build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static,
500 ) where
501 Self: Sized,
502 {
503 debug_assert!(
504 self.tooltip_builder.is_none(),
505 "calling tooltip more than once on the same element is not supported"
506 );
507 self.tooltip_builder = Some(TooltipBuilder {
508 build: Rc::new(build_tooltip),
509 hoverable: true,
510 });
511 }
512
513 /// Block the mouse from interacting with this element or any of its children
514 /// The imperative API equivalent to [`InteractiveElement::block_mouse`]
515 pub fn occlude_mouse(&mut self) {
516 self.occlude_mouse = true;
517 }
518}
519
520/// A trait for elements that want to use the standard GPUI event handlers that don't
521/// require any state.
522pub trait InteractiveElement: Sized {
523 /// Retrieve the interactivity state associated with this element
524 fn interactivity(&mut self) -> &mut Interactivity;
525
526 /// Assign this element to a group of elements that can be styled together
527 fn group(mut self, group: impl Into<SharedString>) -> Self {
528 self.interactivity().group = Some(group.into());
529 self
530 }
531
532 /// Assign this element an ID, so that it can be used with interactivity
533 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
534 self.interactivity().element_id = Some(id.into());
535
536 Stateful { element: self }
537 }
538
539 /// Track the focus state of the given focus handle on this element.
540 /// If the focus handle is focused by the application, this element will
541 /// apply its focused styles.
542 fn track_focus(mut self, focus_handle: &FocusHandle) -> Focusable<Self> {
543 self.interactivity().focusable = true;
544 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
545 Focusable { element: self }
546 }
547
548 /// Set the keymap context for this element. This will be used to determine
549 /// which action to dispatch from the keymap.
550 fn key_context<C, E>(mut self, key_context: C) -> Self
551 where
552 C: TryInto<KeyContext, Error = E>,
553 E: Debug,
554 {
555 if let Some(key_context) = key_context.try_into().log_err() {
556 self.interactivity().key_context = Some(key_context);
557 }
558 self
559 }
560
561 /// Apply the given style to this element when the mouse hovers over it
562 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
563 debug_assert!(
564 self.interactivity().hover_style.is_none(),
565 "hover style already set"
566 );
567 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
568 self
569 }
570
571 /// Apply the given style to this element when the mouse hovers over a group member
572 fn group_hover(
573 mut self,
574 group_name: impl Into<SharedString>,
575 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
576 ) -> Self {
577 self.interactivity().group_hover_style = Some(GroupStyle {
578 group: group_name.into(),
579 style: Box::new(f(StyleRefinement::default())),
580 });
581 self
582 }
583
584 /// Bind the given callback to the mouse down event for the given mouse button,
585 /// the fluent API equivalent to [`Interactivity::on_mouse_down`]
586 ///
587 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to the view state from this callback.
588 fn on_mouse_down(
589 mut self,
590 button: MouseButton,
591 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
592 ) -> Self {
593 self.interactivity().on_mouse_down(button, listener);
594 self
595 }
596
597 #[cfg(any(test, feature = "test-support"))]
598 /// Set a key that can be used to look up this element's bounds
599 /// in the [`VisualTestContext::debug_bounds`] map
600 /// This is a noop in release builds
601 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
602 self.interactivity().debug_selector = Some(f());
603 self
604 }
605
606 #[cfg(not(any(test, feature = "test-support")))]
607 /// Set a key that can be used to look up this element's bounds
608 /// in the [`VisualTestContext::debug_bounds`] map
609 /// This is a noop in release builds
610 #[inline]
611 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
612 self
613 }
614
615 /// Bind the given callback to the mouse down event for any button, during the capture phase
616 /// the fluent API equivalent to [`Interactivity::capture_any_mouse_down`]
617 ///
618 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
619 fn capture_any_mouse_down(
620 mut self,
621 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
622 ) -> Self {
623 self.interactivity().capture_any_mouse_down(listener);
624 self
625 }
626
627 /// Bind the given callback to the mouse down event for any button, during the capture phase
628 /// the fluent API equivalent to [`Interactivity::on_any_mouse_down`]
629 ///
630 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
631 fn on_any_mouse_down(
632 mut self,
633 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
634 ) -> Self {
635 self.interactivity().on_any_mouse_down(listener);
636 self
637 }
638
639 /// Bind the given callback to the mouse up event for the given button, during the bubble phase
640 /// the fluent API equivalent to [`Interactivity::on_mouse_up`]
641 ///
642 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
643 fn on_mouse_up(
644 mut self,
645 button: MouseButton,
646 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
647 ) -> Self {
648 self.interactivity().on_mouse_up(button, listener);
649 self
650 }
651
652 /// Bind the given callback to the mouse up event for any button, during the capture phase
653 /// the fluent API equivalent to [`Interactivity::capture_any_mouse_up`]
654 ///
655 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
656 fn capture_any_mouse_up(
657 mut self,
658 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
659 ) -> Self {
660 self.interactivity().capture_any_mouse_up(listener);
661 self
662 }
663
664 /// Bind the given callback to the mouse down event, on any button, during the capture phase,
665 /// when the mouse is outside of the bounds of this element.
666 /// The fluent API equivalent to [`Interactivity::on_mouse_down_out`]
667 ///
668 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
669 fn on_mouse_down_out(
670 mut self,
671 listener: impl Fn(&MouseDownEvent, &mut WindowContext) + 'static,
672 ) -> Self {
673 self.interactivity().on_mouse_down_out(listener);
674 self
675 }
676
677 /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
678 /// when the mouse is outside of the bounds of this element.
679 /// The fluent API equivalent to [`Interactivity::on_mouse_up_out`]
680 ///
681 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
682 fn on_mouse_up_out(
683 mut self,
684 button: MouseButton,
685 listener: impl Fn(&MouseUpEvent, &mut WindowContext) + 'static,
686 ) -> Self {
687 self.interactivity().on_mouse_up_out(button, listener);
688 self
689 }
690
691 /// Bind the given callback to the mouse move event, during the bubble phase
692 /// The fluent API equivalent to [`Interactivity::on_mouse_move`]
693 ///
694 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
695 fn on_mouse_move(
696 mut self,
697 listener: impl Fn(&MouseMoveEvent, &mut WindowContext) + 'static,
698 ) -> Self {
699 self.interactivity().on_mouse_move(listener);
700 self
701 }
702
703 /// Bind the given callback to the mouse drag event of the given type. Note that this
704 /// will be called for all move events, inside or outside of this element, as long as the
705 /// drag was started with this element under the mouse. Useful for implementing draggable
706 /// UIs that don't conform to a drag and drop style interaction, like resizing.
707 /// The fluent API equivalent to [`Interactivity::on_drag_move`]
708 ///
709 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
710 fn on_drag_move<T: 'static>(
711 mut self,
712 listener: impl Fn(&DragMoveEvent<T>, &mut WindowContext) + 'static,
713 ) -> Self {
714 self.interactivity().on_drag_move(listener);
715 self
716 }
717
718 /// Bind the given callback to scroll wheel events during the bubble phase
719 /// The fluent API equivalent to [`Interactivity::on_scroll_wheel`]
720 ///
721 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
722 fn on_scroll_wheel(
723 mut self,
724 listener: impl Fn(&ScrollWheelEvent, &mut WindowContext) + 'static,
725 ) -> Self {
726 self.interactivity().on_scroll_wheel(listener);
727 self
728 }
729
730 /// Capture the given action, before normal action dispatch can fire
731 /// The fluent API equivalent to [`Interactivity::on_scroll_wheel`]
732 ///
733 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
734 fn capture_action<A: Action>(
735 mut self,
736 listener: impl Fn(&A, &mut WindowContext) + 'static,
737 ) -> Self {
738 self.interactivity().capture_action(listener);
739 self
740 }
741
742 /// Bind the given callback to an action dispatch during the bubble phase
743 /// The fluent API equivalent to [`Interactivity::on_action`]
744 ///
745 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
746 fn on_action<A: Action>(mut self, listener: impl Fn(&A, &mut WindowContext) + 'static) -> Self {
747 self.interactivity().on_action(listener);
748 self
749 }
750
751 /// Bind the given callback to an action dispatch, based on a dynamic action parameter
752 /// instead of a type parameter. Useful for component libraries that want to expose
753 /// action bindings to their users.
754 /// The fluent API equivalent to [`Interactivity::on_boxed_action`]
755 ///
756 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
757 fn on_boxed_action(
758 mut self,
759 action: &dyn Action,
760 listener: impl Fn(&dyn Action, &mut WindowContext) + 'static,
761 ) -> Self {
762 self.interactivity().on_boxed_action(action, listener);
763 self
764 }
765
766 /// Bind the given callback to key down events during the bubble phase
767 /// The fluent API equivalent to [`Interactivity::on_key_down`]
768 ///
769 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
770 fn on_key_down(
771 mut self,
772 listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static,
773 ) -> Self {
774 self.interactivity().on_key_down(listener);
775 self
776 }
777
778 /// Bind the given callback to key down events during the capture phase
779 /// The fluent API equivalent to [`Interactivity::capture_key_down`]
780 ///
781 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
782 fn capture_key_down(
783 mut self,
784 listener: impl Fn(&KeyDownEvent, &mut WindowContext) + 'static,
785 ) -> Self {
786 self.interactivity().capture_key_down(listener);
787 self
788 }
789
790 /// Bind the given callback to key up events during the bubble phase
791 /// The fluent API equivalent to [`Interactivity::on_key_up`]
792 ///
793 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
794 fn on_key_up(mut self, listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static) -> Self {
795 self.interactivity().on_key_up(listener);
796 self
797 }
798
799 /// Bind the given callback to key up events during the capture phase
800 /// The fluent API equivalent to [`Interactivity::capture_key_up`]
801 ///
802 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
803 fn capture_key_up(
804 mut self,
805 listener: impl Fn(&KeyUpEvent, &mut WindowContext) + 'static,
806 ) -> Self {
807 self.interactivity().capture_key_up(listener);
808 self
809 }
810
811 /// Bind the given callback to modifiers changing events.
812 /// The fluent API equivalent to [`Interactivity::on_modifiers_changed`]
813 ///
814 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
815 fn on_modifiers_changed(
816 mut self,
817 listener: impl Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static,
818 ) -> Self {
819 self.interactivity().on_modifiers_changed(listener);
820 self
821 }
822
823 /// Apply the given style when the given data type is dragged over this element
824 fn drag_over<S: 'static>(
825 mut self,
826 f: impl 'static + Fn(StyleRefinement, &S, &WindowContext) -> StyleRefinement,
827 ) -> Self {
828 self.interactivity().drag_over_styles.push((
829 TypeId::of::<S>(),
830 Box::new(move |currently_dragged: &dyn Any, cx| {
831 f(
832 StyleRefinement::default(),
833 currently_dragged.downcast_ref::<S>().unwrap(),
834 cx,
835 )
836 }),
837 ));
838 self
839 }
840
841 /// Apply the given style when the given data type is dragged over this element's group
842 fn group_drag_over<S: 'static>(
843 mut self,
844 group_name: impl Into<SharedString>,
845 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
846 ) -> Self {
847 self.interactivity().group_drag_over_styles.push((
848 TypeId::of::<S>(),
849 GroupStyle {
850 group: group_name.into(),
851 style: Box::new(f(StyleRefinement::default())),
852 },
853 ));
854 self
855 }
856
857 /// Bind the given callback to drop events of the given type, whether or not the drag started on this element
858 /// The fluent API equivalent to [`Interactivity::on_drop`]
859 ///
860 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
861 fn on_drop<T: 'static>(mut self, listener: impl Fn(&T, &mut WindowContext) + 'static) -> Self {
862 self.interactivity().on_drop(listener);
863 self
864 }
865
866 /// Use the given predicate to determine whether or not a drop event should be dispatched to this element
867 /// The fluent API equivalent to [`Interactivity::can_drop`]
868 fn can_drop(
869 mut self,
870 predicate: impl Fn(&dyn Any, &mut WindowContext) -> bool + 'static,
871 ) -> Self {
872 self.interactivity().can_drop(predicate);
873 self
874 }
875
876 /// Block the mouse from interacting with this element or any of its children
877 /// The fluent API equivalent to [`Interactivity::block_mouse`]
878 fn occlude(mut self) -> Self {
879 self.interactivity().occlude_mouse();
880 self
881 }
882}
883
884/// A trait for elements that want to use the standard GPUI interactivity features
885/// that require state.
886pub trait StatefulInteractiveElement: InteractiveElement {
887 /// Set this element to focusable.
888 fn focusable(mut self) -> Focusable<Self> {
889 self.interactivity().focusable = true;
890 Focusable { element: self }
891 }
892
893 /// Set the overflow x and y to scroll.
894 fn overflow_scroll(mut self) -> Self {
895 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
896 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
897 self
898 }
899
900 /// Set the overflow x to scroll.
901 fn overflow_x_scroll(mut self) -> Self {
902 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
903 self
904 }
905
906 /// Set the overflow y to scroll.
907 fn overflow_y_scroll(mut self) -> Self {
908 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
909 self
910 }
911
912 /// Track the scroll state of this element with the given handle.
913 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
914 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
915 self
916 }
917
918 /// Set the given styles to be applied when this element is active.
919 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
920 where
921 Self: Sized,
922 {
923 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
924 self
925 }
926
927 /// Set the given styles to be applied when this element's group is active.
928 fn group_active(
929 mut self,
930 group_name: impl Into<SharedString>,
931 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
932 ) -> Self
933 where
934 Self: Sized,
935 {
936 self.interactivity().group_active_style = Some(GroupStyle {
937 group: group_name.into(),
938 style: Box::new(f(StyleRefinement::default())),
939 });
940 self
941 }
942
943 /// Bind the given callback to click events of this element
944 /// The fluent API equivalent to [`Interactivity::on_click`]
945 ///
946 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
947 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut WindowContext) + 'static) -> Self
948 where
949 Self: Sized,
950 {
951 self.interactivity().on_click(listener);
952 self
953 }
954
955 /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
956 /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
957 /// the [`Self::on_drag_move`] API
958 /// The fluent API equivalent to [`Interactivity::on_drag`]
959 ///
960 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
961 fn on_drag<T, W>(
962 mut self,
963 value: T,
964 constructor: impl Fn(&T, &mut WindowContext) -> View<W> + 'static,
965 ) -> Self
966 where
967 Self: Sized,
968 T: 'static,
969 W: 'static + Render,
970 {
971 self.interactivity().on_drag(value, constructor);
972 self
973 }
974
975 /// Bind the given callback on the hover start and end events of this element. Note that the boolean
976 /// passed to the callback is true when the hover starts and false when it ends.
977 /// The fluent API equivalent to [`Interactivity::on_hover`]
978 ///
979 /// See [`ViewContext::listener`](crate::ViewContext::listener) to get access to a view's state from this callback.
980 fn on_hover(mut self, listener: impl Fn(&bool, &mut WindowContext) + 'static) -> Self
981 where
982 Self: Sized,
983 {
984 self.interactivity().on_hover(listener);
985 self
986 }
987
988 /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
989 /// The fluent API equivalent to [`Interactivity::tooltip`]
990 fn tooltip(mut self, build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static) -> Self
991 where
992 Self: Sized,
993 {
994 self.interactivity().tooltip(build_tooltip);
995 self
996 }
997
998 /// Use the given callback to construct a new tooltip view when the mouse hovers over this element.
999 /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
1000 /// the tooltip. The fluent API equivalent to [`Interactivity::hoverable_tooltip`]
1001 fn hoverable_tooltip(
1002 mut self,
1003 build_tooltip: impl Fn(&mut WindowContext) -> AnyView + 'static,
1004 ) -> Self
1005 where
1006 Self: Sized,
1007 {
1008 self.interactivity().hoverable_tooltip(build_tooltip);
1009 self
1010 }
1011}
1012
1013/// A trait for providing focus related APIs to interactive elements
1014pub trait FocusableElement: InteractiveElement {
1015 /// Set the given styles to be applied when this element, specifically, is focused.
1016 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1017 where
1018 Self: Sized,
1019 {
1020 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1021 self
1022 }
1023
1024 /// Set the given styles to be applied when this element is inside another element that is focused.
1025 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1026 where
1027 Self: Sized,
1028 {
1029 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1030 self
1031 }
1032}
1033
1034pub(crate) type MouseDownListener =
1035 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut WindowContext) + 'static>;
1036pub(crate) type MouseUpListener =
1037 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut WindowContext) + 'static>;
1038
1039pub(crate) type MouseMoveListener =
1040 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut WindowContext) + 'static>;
1041
1042pub(crate) type ScrollWheelListener =
1043 Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut WindowContext) + 'static>;
1044
1045pub(crate) type ClickListener = Box<dyn Fn(&ClickEvent, &mut WindowContext) + 'static>;
1046
1047pub(crate) type DragListener = Box<dyn Fn(&dyn Any, &mut WindowContext) -> AnyView + 'static>;
1048
1049type DropListener = Box<dyn Fn(&dyn Any, &mut WindowContext) + 'static>;
1050
1051type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut WindowContext) -> bool + 'static>;
1052
1053pub(crate) struct TooltipBuilder {
1054 build: Rc<dyn Fn(&mut WindowContext) -> AnyView + 'static>,
1055 hoverable: bool,
1056}
1057
1058pub(crate) type KeyDownListener =
1059 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut WindowContext) + 'static>;
1060
1061pub(crate) type KeyUpListener =
1062 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut WindowContext) + 'static>;
1063
1064pub(crate) type ModifiersChangedListener =
1065 Box<dyn Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static>;
1066
1067pub(crate) type ActionListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
1068
1069/// Construct a new [`Div`] element
1070#[track_caller]
1071pub fn div() -> Div {
1072 #[cfg(debug_assertions)]
1073 let interactivity = Interactivity {
1074 location: Some(*core::panic::Location::caller()),
1075 ..Default::default()
1076 };
1077
1078 #[cfg(not(debug_assertions))]
1079 let interactivity = Interactivity::default();
1080
1081 Div {
1082 interactivity,
1083 children: SmallVec::default(),
1084 }
1085}
1086
1087/// A [`Div`] element, the all-in-one element for building complex UIs in GPUI
1088pub struct Div {
1089 interactivity: Interactivity,
1090 children: SmallVec<[AnyElement; 2]>,
1091}
1092
1093/// A frame state for a `Div` element, which contains layout IDs for its children.
1094///
1095/// This struct is used internally by the `Div` element to manage the layout state of its children
1096/// during the UI update cycle. It holds a small vector of `LayoutId` values, each corresponding to
1097/// a child element of the `Div`. These IDs are used to query the layout engine for the computed
1098/// bounds of the children after the layout phase is complete.
1099pub struct DivFrameState {
1100 child_layout_ids: SmallVec<[LayoutId; 2]>,
1101}
1102
1103impl Styled for Div {
1104 fn style(&mut self) -> &mut StyleRefinement {
1105 &mut self.interactivity.base_style
1106 }
1107}
1108
1109impl InteractiveElement for Div {
1110 fn interactivity(&mut self) -> &mut Interactivity {
1111 &mut self.interactivity
1112 }
1113}
1114
1115impl ParentElement for Div {
1116 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1117 self.children.extend(elements)
1118 }
1119}
1120
1121impl Element for Div {
1122 type RequestLayoutState = DivFrameState;
1123 type PrepaintState = Option<Hitbox>;
1124
1125 fn id(&self) -> Option<ElementId> {
1126 self.interactivity.element_id.clone()
1127 }
1128
1129 fn request_layout(
1130 &mut self,
1131 global_id: Option<&GlobalElementId>,
1132 cx: &mut WindowContext,
1133 ) -> (LayoutId, Self::RequestLayoutState) {
1134 let mut child_layout_ids = SmallVec::new();
1135 let layout_id = self
1136 .interactivity
1137 .request_layout(global_id, cx, |style, cx| {
1138 cx.with_text_style(style.text_style().cloned(), |cx| {
1139 child_layout_ids = self
1140 .children
1141 .iter_mut()
1142 .map(|child| child.request_layout(cx))
1143 .collect::<SmallVec<_>>();
1144 cx.request_layout(style, child_layout_ids.iter().copied())
1145 })
1146 });
1147 (layout_id, DivFrameState { child_layout_ids })
1148 }
1149
1150 fn prepaint(
1151 &mut self,
1152 global_id: Option<&GlobalElementId>,
1153 bounds: Bounds<Pixels>,
1154 request_layout: &mut Self::RequestLayoutState,
1155 cx: &mut WindowContext,
1156 ) -> Option<Hitbox> {
1157 let mut child_min = point(Pixels::MAX, Pixels::MAX);
1158 let mut child_max = Point::default();
1159 let content_size = if request_layout.child_layout_ids.is_empty() {
1160 bounds.size
1161 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1162 let mut state = scroll_handle.0.borrow_mut();
1163 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1164 state.bounds = bounds;
1165 let requested = state.requested_scroll_top.take();
1166
1167 for (ix, child_layout_id) in request_layout.child_layout_ids.iter().enumerate() {
1168 let child_bounds = cx.layout_bounds(*child_layout_id);
1169 child_min = child_min.min(&child_bounds.origin);
1170 child_max = child_max.max(&child_bounds.lower_right());
1171 state.child_bounds.push(child_bounds);
1172
1173 if let Some(requested) = requested.as_ref() {
1174 if requested.0 == ix {
1175 *state.offset.borrow_mut() =
1176 bounds.origin - (child_bounds.origin - point(px(0.), requested.1));
1177 }
1178 }
1179 }
1180 (child_max - child_min).into()
1181 } else {
1182 for child_layout_id in &request_layout.child_layout_ids {
1183 let child_bounds = cx.layout_bounds(*child_layout_id);
1184 child_min = child_min.min(&child_bounds.origin);
1185 child_max = child_max.max(&child_bounds.lower_right());
1186 }
1187 (child_max - child_min).into()
1188 };
1189
1190 self.interactivity.prepaint(
1191 global_id,
1192 bounds,
1193 content_size,
1194 cx,
1195 |_style, scroll_offset, hitbox, cx| {
1196 cx.with_element_offset(scroll_offset, |cx| {
1197 for child in &mut self.children {
1198 child.prepaint(cx);
1199 }
1200 });
1201 hitbox
1202 },
1203 )
1204 }
1205
1206 fn paint(
1207 &mut self,
1208 global_id: Option<&GlobalElementId>,
1209 bounds: Bounds<Pixels>,
1210 _request_layout: &mut Self::RequestLayoutState,
1211 hitbox: &mut Option<Hitbox>,
1212 cx: &mut WindowContext,
1213 ) {
1214 self.interactivity
1215 .paint(global_id, bounds, hitbox.as_ref(), cx, |_style, cx| {
1216 for child in &mut self.children {
1217 child.paint(cx);
1218 }
1219 });
1220 }
1221}
1222
1223impl IntoElement for Div {
1224 type Element = Self;
1225
1226 fn into_element(self) -> Self::Element {
1227 self
1228 }
1229}
1230
1231/// The interactivity struct. Powers all of the general-purpose
1232/// interactivity in the `Div` element.
1233#[derive(Default)]
1234pub struct Interactivity {
1235 /// The element ID of the element. In id is required to support a stateful subset of the interactivity such as on_click.
1236 pub element_id: Option<ElementId>,
1237 /// Whether the element was clicked. This will only be present after layout.
1238 pub active: Option<bool>,
1239 /// Whether the element was hovered. This will only be present after paint if an hitbox
1240 /// was created for the interactive element.
1241 pub hovered: Option<bool>,
1242 pub(crate) tooltip_id: Option<TooltipId>,
1243 pub(crate) content_size: Size<Pixels>,
1244 pub(crate) key_context: Option<KeyContext>,
1245 pub(crate) focusable: bool,
1246 pub(crate) tracked_focus_handle: Option<FocusHandle>,
1247 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
1248 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
1249 pub(crate) group: Option<SharedString>,
1250 /// The base style of the element, before any modifications are applied
1251 /// by focus, active, etc.
1252 pub base_style: Box<StyleRefinement>,
1253 pub(crate) focus_style: Option<Box<StyleRefinement>>,
1254 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
1255 pub(crate) hover_style: Option<Box<StyleRefinement>>,
1256 pub(crate) group_hover_style: Option<GroupStyle>,
1257 pub(crate) active_style: Option<Box<StyleRefinement>>,
1258 pub(crate) group_active_style: Option<GroupStyle>,
1259 pub(crate) drag_over_styles: Vec<(
1260 TypeId,
1261 Box<dyn Fn(&dyn Any, &mut WindowContext) -> StyleRefinement>,
1262 )>,
1263 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
1264 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
1265 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
1266 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
1267 pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
1268 pub(crate) key_down_listeners: Vec<KeyDownListener>,
1269 pub(crate) key_up_listeners: Vec<KeyUpListener>,
1270 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
1271 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
1272 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
1273 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
1274 pub(crate) click_listeners: Vec<ClickListener>,
1275 pub(crate) drag_listener: Option<(Box<dyn Any>, DragListener)>,
1276 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut WindowContext)>>,
1277 pub(crate) tooltip_builder: Option<TooltipBuilder>,
1278 pub(crate) occlude_mouse: bool,
1279
1280 #[cfg(debug_assertions)]
1281 pub(crate) location: Option<core::panic::Location<'static>>,
1282
1283 #[cfg(any(test, feature = "test-support"))]
1284 pub(crate) debug_selector: Option<String>,
1285}
1286
1287impl Interactivity {
1288 /// Layout this element according to this interactivity state's configured styles
1289 pub fn request_layout(
1290 &mut self,
1291 global_id: Option<&GlobalElementId>,
1292 cx: &mut WindowContext,
1293 f: impl FnOnce(Style, &mut WindowContext) -> LayoutId,
1294 ) -> LayoutId {
1295 cx.with_optional_element_state::<InteractiveElementState, _>(
1296 global_id,
1297 |element_state, cx| {
1298 let mut element_state =
1299 element_state.map(|element_state| element_state.unwrap_or_default());
1300
1301 if let Some(element_state) = element_state.as_ref() {
1302 if cx.has_active_drag() {
1303 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref()
1304 {
1305 *pending_mouse_down.borrow_mut() = None;
1306 }
1307 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1308 *clicked_state.borrow_mut() = ElementClickedState::default();
1309 }
1310 }
1311 }
1312
1313 // Ensure we store a focus handle in our element state if we're focusable.
1314 // If there's an explicit focus handle we're tracking, use that. Otherwise
1315 // create a new handle and store it in the element state, which lives for as
1316 // as frames contain an element with this id.
1317 if self.focusable {
1318 if self.tracked_focus_handle.is_none() {
1319 if let Some(element_state) = element_state.as_mut() {
1320 self.tracked_focus_handle = Some(
1321 element_state
1322 .focus_handle
1323 .get_or_insert_with(|| cx.focus_handle())
1324 .clone(),
1325 );
1326 }
1327 }
1328 }
1329
1330 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
1331 self.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
1332 } else if self.base_style.overflow.x == Some(Overflow::Scroll)
1333 || self.base_style.overflow.y == Some(Overflow::Scroll)
1334 {
1335 if let Some(element_state) = element_state.as_mut() {
1336 self.scroll_offset = Some(
1337 element_state
1338 .scroll_offset
1339 .get_or_insert_with(|| Rc::default())
1340 .clone(),
1341 );
1342 }
1343 }
1344
1345 let style = self.compute_style_internal(None, element_state.as_mut(), cx);
1346 let layout_id = f(style, cx);
1347 (layout_id, element_state)
1348 },
1349 )
1350 }
1351
1352 /// Commit the bounds of this element according to this interactivity state's configured styles.
1353 pub fn prepaint<R>(
1354 &mut self,
1355 global_id: Option<&GlobalElementId>,
1356 bounds: Bounds<Pixels>,
1357 content_size: Size<Pixels>,
1358 cx: &mut WindowContext,
1359 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut WindowContext) -> R,
1360 ) -> R {
1361 self.content_size = content_size;
1362 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1363 cx.set_focus_handle(&focus_handle);
1364 }
1365 cx.with_optional_element_state::<InteractiveElementState, _>(
1366 global_id,
1367 |element_state, cx| {
1368 let mut element_state =
1369 element_state.map(|element_state| element_state.unwrap_or_default());
1370 let style = self.compute_style_internal(None, element_state.as_mut(), cx);
1371
1372 if let Some(element_state) = element_state.as_ref() {
1373 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1374 let clicked_state = clicked_state.borrow();
1375 self.active = Some(clicked_state.element);
1376 }
1377
1378 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
1379 if let Some(active_tooltip) = active_tooltip.borrow().as_ref() {
1380 if let Some(tooltip) = active_tooltip.tooltip.clone() {
1381 self.tooltip_id = Some(cx.set_tooltip(tooltip));
1382 }
1383 }
1384 }
1385 }
1386
1387 cx.with_text_style(style.text_style().cloned(), |cx| {
1388 cx.with_content_mask(style.overflow_mask(bounds, cx.rem_size()), |cx| {
1389 let hitbox = if self.should_insert_hitbox(&style) {
1390 Some(cx.insert_hitbox(bounds, self.occlude_mouse))
1391 } else {
1392 None
1393 };
1394
1395 let scroll_offset = self.clamp_scroll_position(bounds, &style, cx);
1396 let result = f(&style, scroll_offset, hitbox, cx);
1397 (result, element_state)
1398 })
1399 })
1400 },
1401 )
1402 }
1403
1404 fn should_insert_hitbox(&self, style: &Style) -> bool {
1405 self.occlude_mouse
1406 || style.mouse_cursor.is_some()
1407 || self.group.is_some()
1408 || self.scroll_offset.is_some()
1409 || self.tracked_focus_handle.is_some()
1410 || self.hover_style.is_some()
1411 || self.group_hover_style.is_some()
1412 || !self.mouse_up_listeners.is_empty()
1413 || !self.mouse_down_listeners.is_empty()
1414 || !self.mouse_move_listeners.is_empty()
1415 || !self.click_listeners.is_empty()
1416 || !self.scroll_wheel_listeners.is_empty()
1417 || self.drag_listener.is_some()
1418 || !self.drop_listeners.is_empty()
1419 || self.tooltip_builder.is_some()
1420 }
1421
1422 fn clamp_scroll_position(
1423 &mut self,
1424 bounds: Bounds<Pixels>,
1425 style: &Style,
1426 cx: &mut WindowContext,
1427 ) -> Point<Pixels> {
1428 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
1429 if let Some(scroll_handle) = &self.tracked_scroll_handle {
1430 scroll_handle.0.borrow_mut().overflow = style.overflow;
1431 }
1432
1433 let rem_size = cx.rem_size();
1434 let padding_size = size(
1435 style
1436 .padding
1437 .left
1438 .to_pixels(bounds.size.width.into(), rem_size)
1439 + style
1440 .padding
1441 .right
1442 .to_pixels(bounds.size.width.into(), rem_size),
1443 style
1444 .padding
1445 .top
1446 .to_pixels(bounds.size.height.into(), rem_size)
1447 + style
1448 .padding
1449 .bottom
1450 .to_pixels(bounds.size.height.into(), rem_size),
1451 );
1452 let scroll_max = (self.content_size + padding_size - bounds.size).max(&Size::default());
1453 // Clamp scroll offset in case scroll max is smaller now (e.g., if children
1454 // were removed or the bounds became larger).
1455 let mut scroll_offset = scroll_offset.borrow_mut();
1456 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.width, px(0.));
1457 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.height, px(0.));
1458 *scroll_offset
1459 } else {
1460 Point::default()
1461 }
1462 }
1463
1464 /// Paint this element according to this interactivity state's configured styles
1465 /// and bind the element's mouse and keyboard events.
1466 ///
1467 /// content_size is the size of the content of the element, which may be larger than the
1468 /// element's bounds if the element is scrollable.
1469 ///
1470 /// the final computed style will be passed to the provided function, along
1471 /// with the current scroll offset
1472 pub fn paint(
1473 &mut self,
1474 global_id: Option<&GlobalElementId>,
1475 bounds: Bounds<Pixels>,
1476 hitbox: Option<&Hitbox>,
1477 cx: &mut WindowContext,
1478 f: impl FnOnce(&Style, &mut WindowContext),
1479 ) {
1480 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(cx));
1481 cx.with_optional_element_state::<InteractiveElementState, _>(
1482 global_id,
1483 |element_state, cx| {
1484 let mut element_state =
1485 element_state.map(|element_state| element_state.unwrap_or_default());
1486
1487 let style = self.compute_style_internal(hitbox, element_state.as_mut(), cx);
1488
1489 #[cfg(any(feature = "test-support", test))]
1490 if let Some(debug_selector) = &self.debug_selector {
1491 cx.window
1492 .next_frame
1493 .debug_bounds
1494 .insert(debug_selector.clone(), bounds);
1495 }
1496
1497 self.paint_hover_group_handler(cx);
1498
1499 if style.visibility == Visibility::Hidden {
1500 return ((), element_state);
1501 }
1502
1503 style.paint(bounds, cx, |cx: &mut WindowContext| {
1504 cx.with_text_style(style.text_style().cloned(), |cx| {
1505 cx.with_content_mask(style.overflow_mask(bounds, cx.rem_size()), |cx| {
1506 if let Some(hitbox) = hitbox {
1507 #[cfg(debug_assertions)]
1508 self.paint_debug_info(global_id, hitbox, &style, cx);
1509
1510 if !cx.has_active_drag() {
1511 if let Some(mouse_cursor) = style.mouse_cursor {
1512 cx.set_cursor_style(mouse_cursor, hitbox);
1513 }
1514 }
1515
1516 if let Some(group) = self.group.clone() {
1517 GroupHitboxes::push(group, hitbox.id, cx);
1518 }
1519
1520 self.paint_mouse_listeners(hitbox, element_state.as_mut(), cx);
1521 self.paint_scroll_listener(hitbox, &style, cx);
1522 }
1523
1524 self.paint_keyboard_listeners(cx);
1525 f(&style, cx);
1526
1527 if hitbox.is_some() {
1528 if let Some(group) = self.group.as_ref() {
1529 GroupHitboxes::pop(group, cx);
1530 }
1531 }
1532 });
1533 });
1534 });
1535
1536 ((), element_state)
1537 },
1538 );
1539 }
1540
1541 #[cfg(debug_assertions)]
1542 fn paint_debug_info(
1543 &mut self,
1544 global_id: Option<&GlobalElementId>,
1545 hitbox: &Hitbox,
1546 style: &Style,
1547 cx: &mut WindowContext,
1548 ) {
1549 if global_id.is_some()
1550 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
1551 && hitbox.is_hovered(cx)
1552 {
1553 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
1554 let element_id = format!("{:?}", global_id.unwrap());
1555 let str_len = element_id.len();
1556
1557 let render_debug_text = |cx: &mut WindowContext| {
1558 if let Some(text) = cx
1559 .text_system()
1560 .shape_text(
1561 element_id.into(),
1562 FONT_SIZE,
1563 &[cx.text_style().to_run(str_len)],
1564 None,
1565 )
1566 .ok()
1567 .and_then(|mut text| text.pop())
1568 {
1569 text.paint(hitbox.origin, FONT_SIZE, cx).ok();
1570
1571 let text_bounds = crate::Bounds {
1572 origin: hitbox.origin,
1573 size: text.size(FONT_SIZE),
1574 };
1575 if self.location.is_some()
1576 && text_bounds.contains(&cx.mouse_position())
1577 && cx.modifiers().secondary()
1578 {
1579 let secondary_held = cx.modifiers().secondary();
1580 cx.on_key_event({
1581 move |e: &crate::ModifiersChangedEvent, _phase, cx| {
1582 if e.modifiers.secondary() != secondary_held
1583 && text_bounds.contains(&cx.mouse_position())
1584 {
1585 cx.refresh();
1586 }
1587 }
1588 });
1589
1590 let was_hovered = hitbox.is_hovered(cx);
1591 cx.on_mouse_event({
1592 let hitbox = hitbox.clone();
1593 move |_: &MouseMoveEvent, phase, cx| {
1594 if phase == DispatchPhase::Capture {
1595 let hovered = hitbox.is_hovered(cx);
1596 if hovered != was_hovered {
1597 cx.refresh();
1598 }
1599 }
1600 }
1601 });
1602
1603 cx.on_mouse_event({
1604 let hitbox = hitbox.clone();
1605 let location = self.location.unwrap();
1606 move |e: &crate::MouseDownEvent, phase, cx| {
1607 if text_bounds.contains(&e.position)
1608 && phase.capture()
1609 && hitbox.is_hovered(cx)
1610 {
1611 cx.stop_propagation();
1612 let Ok(dir) = std::env::current_dir() else {
1613 return;
1614 };
1615
1616 eprintln!(
1617 "This element was created at:\n{}:{}:{}",
1618 dir.join(location.file()).to_string_lossy(),
1619 location.line(),
1620 location.column()
1621 );
1622 }
1623 }
1624 });
1625 cx.paint_quad(crate::outline(
1626 crate::Bounds {
1627 origin: hitbox.origin
1628 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
1629 size: crate::Size {
1630 width: text_bounds.size.width,
1631 height: crate::px(1.),
1632 },
1633 },
1634 crate::red(),
1635 ))
1636 }
1637 }
1638 };
1639
1640 cx.with_text_style(
1641 Some(crate::TextStyleRefinement {
1642 color: Some(crate::red()),
1643 line_height: Some(FONT_SIZE.into()),
1644 background_color: Some(crate::white()),
1645 ..Default::default()
1646 }),
1647 render_debug_text,
1648 )
1649 }
1650 }
1651
1652 fn paint_mouse_listeners(
1653 &mut self,
1654 hitbox: &Hitbox,
1655 element_state: Option<&mut InteractiveElementState>,
1656 cx: &mut WindowContext,
1657 ) {
1658 // If this element can be focused, register a mouse down listener
1659 // that will automatically transfer focus when hitting the element.
1660 // This behavior can be suppressed by using `cx.prevent_default()`.
1661 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
1662 let hitbox = hitbox.clone();
1663 cx.on_mouse_event(move |_: &MouseDownEvent, phase, cx| {
1664 if phase == DispatchPhase::Bubble
1665 && hitbox.is_hovered(cx)
1666 && !cx.default_prevented()
1667 {
1668 cx.focus(&focus_handle);
1669 // If there is a parent that is also focusable, prevent it
1670 // from transferring focus because we already did so.
1671 cx.prevent_default();
1672 }
1673 });
1674 }
1675
1676 for listener in self.mouse_down_listeners.drain(..) {
1677 let hitbox = hitbox.clone();
1678 cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
1679 listener(event, phase, &hitbox, cx);
1680 })
1681 }
1682
1683 for listener in self.mouse_up_listeners.drain(..) {
1684 let hitbox = hitbox.clone();
1685 cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
1686 listener(event, phase, &hitbox, cx);
1687 })
1688 }
1689
1690 for listener in self.mouse_move_listeners.drain(..) {
1691 let hitbox = hitbox.clone();
1692 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1693 listener(event, phase, &hitbox, cx);
1694 })
1695 }
1696
1697 for listener in self.scroll_wheel_listeners.drain(..) {
1698 let hitbox = hitbox.clone();
1699 cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1700 listener(event, phase, &hitbox, cx);
1701 })
1702 }
1703
1704 if self.hover_style.is_some()
1705 || self.base_style.mouse_cursor.is_some()
1706 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
1707 {
1708 let hitbox = hitbox.clone();
1709 let was_hovered = hitbox.is_hovered(cx);
1710 cx.on_mouse_event(move |_: &MouseMoveEvent, phase, cx| {
1711 let hovered = hitbox.is_hovered(cx);
1712 if phase == DispatchPhase::Capture && hovered != was_hovered {
1713 cx.refresh();
1714 }
1715 });
1716 }
1717
1718 let mut drag_listener = mem::take(&mut self.drag_listener);
1719 let drop_listeners = mem::take(&mut self.drop_listeners);
1720 let click_listeners = mem::take(&mut self.click_listeners);
1721 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
1722
1723 if !drop_listeners.is_empty() {
1724 let hitbox = hitbox.clone();
1725 cx.on_mouse_event({
1726 move |_: &MouseUpEvent, phase, cx| {
1727 if let Some(drag) = &cx.active_drag {
1728 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
1729 let drag_state_type = drag.value.as_ref().type_id();
1730 for (drop_state_type, listener) in &drop_listeners {
1731 if *drop_state_type == drag_state_type {
1732 let drag = cx
1733 .active_drag
1734 .take()
1735 .expect("checked for type drag state type above");
1736
1737 let mut can_drop = true;
1738 if let Some(predicate) = &can_drop_predicate {
1739 can_drop = predicate(drag.value.as_ref(), cx);
1740 }
1741
1742 if can_drop {
1743 listener(drag.value.as_ref(), cx);
1744 cx.refresh();
1745 cx.stop_propagation();
1746 }
1747 }
1748 }
1749 }
1750 }
1751 }
1752 });
1753 }
1754
1755 if let Some(element_state) = element_state {
1756 if !click_listeners.is_empty() || drag_listener.is_some() {
1757 let pending_mouse_down = element_state
1758 .pending_mouse_down
1759 .get_or_insert_with(Default::default)
1760 .clone();
1761
1762 let clicked_state = element_state
1763 .clicked_state
1764 .get_or_insert_with(Default::default)
1765 .clone();
1766
1767 cx.on_mouse_event({
1768 let pending_mouse_down = pending_mouse_down.clone();
1769 let hitbox = hitbox.clone();
1770 move |event: &MouseDownEvent, phase, cx| {
1771 if phase == DispatchPhase::Bubble
1772 && event.button == MouseButton::Left
1773 && hitbox.is_hovered(cx)
1774 {
1775 *pending_mouse_down.borrow_mut() = Some(event.clone());
1776 cx.refresh();
1777 }
1778 }
1779 });
1780
1781 cx.on_mouse_event({
1782 let pending_mouse_down = pending_mouse_down.clone();
1783 let hitbox = hitbox.clone();
1784 move |event: &MouseMoveEvent, phase, cx| {
1785 if phase == DispatchPhase::Capture {
1786 return;
1787 }
1788
1789 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
1790 if let Some(mouse_down) = pending_mouse_down.clone() {
1791 if !cx.has_active_drag()
1792 && (event.position - mouse_down.position).magnitude()
1793 > DRAG_THRESHOLD
1794 {
1795 if let Some((drag_value, drag_listener)) = drag_listener.take() {
1796 *clicked_state.borrow_mut() = ElementClickedState::default();
1797 let cursor_offset = event.position - hitbox.origin;
1798 let drag = (drag_listener)(drag_value.as_ref(), cx);
1799 cx.active_drag = Some(AnyDrag {
1800 view: drag,
1801 value: drag_value,
1802 cursor_offset,
1803 });
1804 pending_mouse_down.take();
1805 cx.refresh();
1806 cx.stop_propagation();
1807 }
1808 }
1809 }
1810 }
1811 });
1812
1813 cx.on_mouse_event({
1814 let mut captured_mouse_down = None;
1815 let hitbox = hitbox.clone();
1816 move |event: &MouseUpEvent, phase, cx| match phase {
1817 // Clear the pending mouse down during the capture phase,
1818 // so that it happens even if another event handler stops
1819 // propagation.
1820 DispatchPhase::Capture => {
1821 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
1822 if pending_mouse_down.is_some() && hitbox.is_hovered(cx) {
1823 captured_mouse_down = pending_mouse_down.take();
1824 cx.refresh();
1825 }
1826 }
1827 // Fire click handlers during the bubble phase.
1828 DispatchPhase::Bubble => {
1829 if let Some(mouse_down) = captured_mouse_down.take() {
1830 let mouse_click = ClickEvent {
1831 down: mouse_down,
1832 up: event.clone(),
1833 };
1834 for listener in &click_listeners {
1835 listener(&mouse_click, cx);
1836 }
1837 }
1838 }
1839 }
1840 });
1841 }
1842
1843 if let Some(hover_listener) = self.hover_listener.take() {
1844 let hitbox = hitbox.clone();
1845 let was_hovered = element_state
1846 .hover_state
1847 .get_or_insert_with(Default::default)
1848 .clone();
1849 let has_mouse_down = element_state
1850 .pending_mouse_down
1851 .get_or_insert_with(Default::default)
1852 .clone();
1853
1854 cx.on_mouse_event(move |_: &MouseMoveEvent, phase, cx| {
1855 if phase != DispatchPhase::Bubble {
1856 return;
1857 }
1858 let is_hovered = has_mouse_down.borrow().is_none()
1859 && !cx.has_active_drag()
1860 && hitbox.is_hovered(cx);
1861 let mut was_hovered = was_hovered.borrow_mut();
1862
1863 if is_hovered != *was_hovered {
1864 *was_hovered = is_hovered;
1865 drop(was_hovered);
1866
1867 hover_listener(&is_hovered, cx);
1868 }
1869 });
1870 }
1871
1872 // Ensure to remove active tooltip if tooltip builder is none
1873 if self.tooltip_builder.is_none() {
1874 element_state.active_tooltip.take();
1875 }
1876
1877 if let Some(tooltip_builder) = self.tooltip_builder.take() {
1878 let tooltip_is_hoverable = tooltip_builder.hoverable;
1879 let active_tooltip = element_state
1880 .active_tooltip
1881 .get_or_insert_with(Default::default)
1882 .clone();
1883 let pending_mouse_down = element_state
1884 .pending_mouse_down
1885 .get_or_insert_with(Default::default)
1886 .clone();
1887
1888 cx.on_mouse_event({
1889 let active_tooltip = active_tooltip.clone();
1890 let hitbox = hitbox.clone();
1891 let tooltip_id = self.tooltip_id;
1892 move |_: &MouseMoveEvent, phase, cx| {
1893 let is_hovered =
1894 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(cx);
1895 let tooltip_is_hovered =
1896 tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(cx));
1897 if !is_hovered && (!tooltip_is_hoverable || !tooltip_is_hovered) {
1898 if active_tooltip.borrow_mut().take().is_some() {
1899 cx.refresh();
1900 }
1901
1902 return;
1903 }
1904
1905 if phase != DispatchPhase::Bubble {
1906 return;
1907 }
1908
1909 if active_tooltip.borrow().is_none() {
1910 let task = cx.spawn({
1911 let active_tooltip = active_tooltip.clone();
1912 let build_tooltip = tooltip_builder.build.clone();
1913 move |mut cx| async move {
1914 cx.background_executor().timer(TOOLTIP_DELAY).await;
1915 cx.update(|cx| {
1916 active_tooltip.borrow_mut().replace(ActiveTooltip {
1917 tooltip: Some(AnyTooltip {
1918 view: build_tooltip(cx),
1919 mouse_position: cx.mouse_position(),
1920 }),
1921 _task: None,
1922 });
1923 cx.refresh();
1924 })
1925 .ok();
1926 }
1927 });
1928 active_tooltip.borrow_mut().replace(ActiveTooltip {
1929 tooltip: None,
1930 _task: Some(task),
1931 });
1932 }
1933 }
1934 });
1935
1936 cx.on_mouse_event({
1937 let active_tooltip = active_tooltip.clone();
1938 let tooltip_id = self.tooltip_id;
1939 move |_: &MouseDownEvent, _, cx| {
1940 let tooltip_is_hovered =
1941 tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(cx));
1942
1943 if !tooltip_is_hoverable || !tooltip_is_hovered {
1944 if active_tooltip.borrow_mut().take().is_some() {
1945 cx.refresh();
1946 }
1947 }
1948 }
1949 });
1950
1951 cx.on_mouse_event({
1952 let active_tooltip = active_tooltip.clone();
1953 let tooltip_id = self.tooltip_id;
1954 move |_: &ScrollWheelEvent, _, cx| {
1955 let tooltip_is_hovered =
1956 tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(cx));
1957 if !tooltip_is_hoverable || !tooltip_is_hovered {
1958 if active_tooltip.borrow_mut().take().is_some() {
1959 cx.refresh();
1960 }
1961 }
1962 }
1963 })
1964 }
1965
1966 let active_state = element_state
1967 .clicked_state
1968 .get_or_insert_with(Default::default)
1969 .clone();
1970 if active_state.borrow().is_clicked() {
1971 cx.on_mouse_event(move |_: &MouseUpEvent, phase, cx| {
1972 if phase == DispatchPhase::Capture {
1973 *active_state.borrow_mut() = ElementClickedState::default();
1974 cx.refresh();
1975 }
1976 });
1977 } else {
1978 let active_group_hitbox = self
1979 .group_active_style
1980 .as_ref()
1981 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
1982 let hitbox = hitbox.clone();
1983 cx.on_mouse_event(move |_: &MouseDownEvent, phase, cx| {
1984 if phase == DispatchPhase::Bubble && !cx.default_prevented() {
1985 let group_hovered = active_group_hitbox
1986 .map_or(false, |group_hitbox_id| group_hitbox_id.is_hovered(cx));
1987 let element_hovered = hitbox.is_hovered(cx);
1988 if group_hovered || element_hovered {
1989 *active_state.borrow_mut() = ElementClickedState {
1990 group: group_hovered,
1991 element: element_hovered,
1992 };
1993 cx.refresh();
1994 }
1995 }
1996 });
1997 }
1998 }
1999 }
2000
2001 fn paint_keyboard_listeners(&mut self, cx: &mut WindowContext) {
2002 let key_down_listeners = mem::take(&mut self.key_down_listeners);
2003 let key_up_listeners = mem::take(&mut self.key_up_listeners);
2004 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
2005 let action_listeners = mem::take(&mut self.action_listeners);
2006 if let Some(context) = self.key_context.clone() {
2007 cx.set_key_context(context);
2008 }
2009
2010 for listener in key_down_listeners {
2011 cx.on_key_event(move |event: &KeyDownEvent, phase, cx| {
2012 listener(event, phase, cx);
2013 })
2014 }
2015
2016 for listener in key_up_listeners {
2017 cx.on_key_event(move |event: &KeyUpEvent, phase, cx| {
2018 listener(event, phase, cx);
2019 })
2020 }
2021
2022 for listener in modifiers_changed_listeners {
2023 cx.on_modifiers_changed(move |event: &ModifiersChangedEvent, cx| {
2024 listener(event, cx);
2025 })
2026 }
2027
2028 for (action_type, listener) in action_listeners {
2029 cx.on_action(action_type, listener)
2030 }
2031 }
2032
2033 fn paint_hover_group_handler(&self, cx: &mut WindowContext) {
2034 let group_hitbox = self
2035 .group_hover_style
2036 .as_ref()
2037 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
2038
2039 if let Some(group_hitbox) = group_hitbox {
2040 let was_hovered = group_hitbox.is_hovered(cx);
2041 cx.on_mouse_event(move |_: &MouseMoveEvent, phase, cx| {
2042 let hovered = group_hitbox.is_hovered(cx);
2043 if phase == DispatchPhase::Capture && hovered != was_hovered {
2044 cx.refresh();
2045 }
2046 });
2047 }
2048 }
2049
2050 fn paint_scroll_listener(&self, hitbox: &Hitbox, style: &Style, cx: &mut WindowContext) {
2051 if let Some(scroll_offset) = self.scroll_offset.clone() {
2052 let overflow = style.overflow;
2053 let line_height = cx.line_height();
2054 let hitbox = hitbox.clone();
2055 cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
2056 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2057 let mut scroll_offset = scroll_offset.borrow_mut();
2058 let old_scroll_offset = *scroll_offset;
2059 let delta = event.delta.pixel_delta(line_height);
2060
2061 if overflow.x == Overflow::Scroll {
2062 let mut delta_x = Pixels::ZERO;
2063 if !delta.x.is_zero() {
2064 delta_x = delta.x;
2065 } else if overflow.y != Overflow::Scroll {
2066 delta_x = delta.y;
2067 }
2068
2069 scroll_offset.x += delta_x;
2070 }
2071
2072 if overflow.y == Overflow::Scroll {
2073 let mut delta_y = Pixels::ZERO;
2074 if !delta.y.is_zero() {
2075 delta_y = delta.y;
2076 } else if overflow.x != Overflow::Scroll {
2077 delta_y = delta.x;
2078 }
2079
2080 scroll_offset.y += delta_y;
2081 }
2082
2083 cx.stop_propagation();
2084 if *scroll_offset != old_scroll_offset {
2085 cx.refresh();
2086 }
2087 }
2088 });
2089 }
2090 }
2091
2092 /// Compute the visual style for this element, based on the current bounds and the element's state.
2093 pub fn compute_style(
2094 &self,
2095 global_id: Option<&GlobalElementId>,
2096 hitbox: Option<&Hitbox>,
2097 cx: &mut WindowContext,
2098 ) -> Style {
2099 cx.with_optional_element_state(global_id, |element_state, cx| {
2100 let mut element_state =
2101 element_state.map(|element_state| element_state.unwrap_or_default());
2102 let style = self.compute_style_internal(hitbox, element_state.as_mut(), cx);
2103 (style, element_state)
2104 })
2105 }
2106
2107 /// Called from internal methods that have already called with_element_state.
2108 fn compute_style_internal(
2109 &self,
2110 hitbox: Option<&Hitbox>,
2111 element_state: Option<&mut InteractiveElementState>,
2112 cx: &mut WindowContext,
2113 ) -> Style {
2114 let mut style = Style::default();
2115 style.refine(&self.base_style);
2116
2117 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2118 if let Some(in_focus_style) = self.in_focus_style.as_ref() {
2119 if focus_handle.within_focused(cx) {
2120 style.refine(in_focus_style);
2121 }
2122 }
2123
2124 if let Some(focus_style) = self.focus_style.as_ref() {
2125 if focus_handle.is_focused(cx) {
2126 style.refine(focus_style);
2127 }
2128 }
2129 }
2130
2131 if let Some(hitbox) = hitbox {
2132 if !cx.has_active_drag() {
2133 if let Some(group_hover) = self.group_hover_style.as_ref() {
2134 if let Some(group_hitbox_id) =
2135 GroupHitboxes::get(&group_hover.group, cx.deref_mut())
2136 {
2137 if group_hitbox_id.is_hovered(cx) {
2138 style.refine(&group_hover.style);
2139 }
2140 }
2141 }
2142
2143 if let Some(hover_style) = self.hover_style.as_ref() {
2144 if hitbox.is_hovered(cx) {
2145 style.refine(hover_style);
2146 }
2147 }
2148 }
2149
2150 if let Some(drag) = cx.active_drag.take() {
2151 let mut can_drop = true;
2152 if let Some(can_drop_predicate) = &self.can_drop_predicate {
2153 can_drop = can_drop_predicate(drag.value.as_ref(), cx);
2154 }
2155
2156 if can_drop {
2157 for (state_type, group_drag_style) in &self.group_drag_over_styles {
2158 if let Some(group_hitbox_id) =
2159 GroupHitboxes::get(&group_drag_style.group, cx.deref_mut())
2160 {
2161 if *state_type == drag.value.as_ref().type_id()
2162 && group_hitbox_id.is_hovered(cx)
2163 {
2164 style.refine(&group_drag_style.style);
2165 }
2166 }
2167 }
2168
2169 for (state_type, build_drag_over_style) in &self.drag_over_styles {
2170 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(cx) {
2171 style.refine(&build_drag_over_style(drag.value.as_ref(), cx));
2172 }
2173 }
2174 }
2175
2176 cx.active_drag = Some(drag);
2177 }
2178 }
2179
2180 if let Some(element_state) = element_state {
2181 let clicked_state = element_state
2182 .clicked_state
2183 .get_or_insert_with(Default::default)
2184 .borrow();
2185 if clicked_state.group {
2186 if let Some(group) = self.group_active_style.as_ref() {
2187 style.refine(&group.style)
2188 }
2189 }
2190
2191 if let Some(active_style) = self.active_style.as_ref() {
2192 if clicked_state.element {
2193 style.refine(active_style)
2194 }
2195 }
2196 }
2197
2198 style
2199 }
2200}
2201
2202/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks
2203/// and scroll offsets.
2204#[derive(Default)]
2205pub struct InteractiveElementState {
2206 pub(crate) focus_handle: Option<FocusHandle>,
2207 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
2208 pub(crate) hover_state: Option<Rc<RefCell<bool>>>,
2209 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
2210 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2211 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
2212}
2213
2214/// The current active tooltip
2215pub struct ActiveTooltip {
2216 pub(crate) tooltip: Option<AnyTooltip>,
2217 pub(crate) _task: Option<Task<()>>,
2218}
2219
2220/// Whether or not the element or a group that contains it is clicked by the mouse.
2221#[derive(Copy, Clone, Default, Eq, PartialEq)]
2222pub struct ElementClickedState {
2223 /// True if this element's group has been clicked, false otherwise
2224 pub group: bool,
2225
2226 /// True if this element has been clicked, false otherwise
2227 pub element: bool,
2228}
2229
2230impl ElementClickedState {
2231 fn is_clicked(&self) -> bool {
2232 self.group || self.element
2233 }
2234}
2235
2236#[derive(Default)]
2237pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
2238
2239impl Global for GroupHitboxes {}
2240
2241impl GroupHitboxes {
2242 pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<HitboxId> {
2243 cx.default_global::<Self>()
2244 .0
2245 .get(name)
2246 .and_then(|bounds_stack| bounds_stack.last())
2247 .cloned()
2248 }
2249
2250 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut AppContext) {
2251 cx.default_global::<Self>()
2252 .0
2253 .entry(name)
2254 .or_default()
2255 .push(hitbox_id);
2256 }
2257
2258 pub fn pop(name: &SharedString, cx: &mut AppContext) {
2259 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
2260 }
2261}
2262
2263/// A wrapper around an element that can be focused.
2264pub struct Focusable<E> {
2265 /// The element that is focusable
2266 pub element: E,
2267}
2268
2269impl<E: InteractiveElement> FocusableElement for Focusable<E> {}
2270
2271impl<E> InteractiveElement for Focusable<E>
2272where
2273 E: InteractiveElement,
2274{
2275 fn interactivity(&mut self) -> &mut Interactivity {
2276 self.element.interactivity()
2277 }
2278}
2279
2280impl<E: StatefulInteractiveElement> StatefulInteractiveElement for Focusable<E> {}
2281
2282impl<E> Styled for Focusable<E>
2283where
2284 E: Styled,
2285{
2286 fn style(&mut self) -> &mut StyleRefinement {
2287 self.element.style()
2288 }
2289}
2290
2291impl<E> Element for Focusable<E>
2292where
2293 E: Element,
2294{
2295 type RequestLayoutState = E::RequestLayoutState;
2296 type PrepaintState = E::PrepaintState;
2297
2298 fn id(&self) -> Option<ElementId> {
2299 self.element.id()
2300 }
2301
2302 fn request_layout(
2303 &mut self,
2304 id: Option<&GlobalElementId>,
2305 cx: &mut WindowContext,
2306 ) -> (LayoutId, Self::RequestLayoutState) {
2307 self.element.request_layout(id, cx)
2308 }
2309
2310 fn prepaint(
2311 &mut self,
2312 id: Option<&GlobalElementId>,
2313 bounds: Bounds<Pixels>,
2314 state: &mut Self::RequestLayoutState,
2315 cx: &mut WindowContext,
2316 ) -> E::PrepaintState {
2317 self.element.prepaint(id, bounds, state, cx)
2318 }
2319
2320 fn paint(
2321 &mut self,
2322 id: Option<&GlobalElementId>,
2323 bounds: Bounds<Pixels>,
2324 request_layout: &mut Self::RequestLayoutState,
2325 prepaint: &mut Self::PrepaintState,
2326 cx: &mut WindowContext,
2327 ) {
2328 self.element.paint(id, bounds, request_layout, prepaint, cx)
2329 }
2330}
2331
2332impl<E> IntoElement for Focusable<E>
2333where
2334 E: IntoElement,
2335{
2336 type Element = E::Element;
2337
2338 fn into_element(self) -> Self::Element {
2339 self.element.into_element()
2340 }
2341}
2342
2343impl<E> ParentElement for Focusable<E>
2344where
2345 E: ParentElement,
2346{
2347 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
2348 self.element.extend(elements)
2349 }
2350}
2351
2352/// A wrapper around an element that can store state, produced after assigning an ElementId.
2353pub struct Stateful<E> {
2354 element: E,
2355}
2356
2357impl<E> Styled for Stateful<E>
2358where
2359 E: Styled,
2360{
2361 fn style(&mut self) -> &mut StyleRefinement {
2362 self.element.style()
2363 }
2364}
2365
2366impl<E> StatefulInteractiveElement for Stateful<E>
2367where
2368 E: Element,
2369 Self: InteractiveElement,
2370{
2371}
2372
2373impl<E> InteractiveElement for Stateful<E>
2374where
2375 E: InteractiveElement,
2376{
2377 fn interactivity(&mut self) -> &mut Interactivity {
2378 self.element.interactivity()
2379 }
2380}
2381
2382impl<E: FocusableElement> FocusableElement for Stateful<E> {}
2383
2384impl<E> Element for Stateful<E>
2385where
2386 E: Element,
2387{
2388 type RequestLayoutState = E::RequestLayoutState;
2389 type PrepaintState = E::PrepaintState;
2390
2391 fn id(&self) -> Option<ElementId> {
2392 self.element.id()
2393 }
2394
2395 fn request_layout(
2396 &mut self,
2397 id: Option<&GlobalElementId>,
2398 cx: &mut WindowContext,
2399 ) -> (LayoutId, Self::RequestLayoutState) {
2400 self.element.request_layout(id, cx)
2401 }
2402
2403 fn prepaint(
2404 &mut self,
2405 id: Option<&GlobalElementId>,
2406 bounds: Bounds<Pixels>,
2407 state: &mut Self::RequestLayoutState,
2408 cx: &mut WindowContext,
2409 ) -> E::PrepaintState {
2410 self.element.prepaint(id, bounds, state, cx)
2411 }
2412
2413 fn paint(
2414 &mut self,
2415 id: Option<&GlobalElementId>,
2416 bounds: Bounds<Pixels>,
2417 request_layout: &mut Self::RequestLayoutState,
2418 prepaint: &mut Self::PrepaintState,
2419 cx: &mut WindowContext,
2420 ) {
2421 self.element.paint(id, bounds, request_layout, prepaint, cx);
2422 }
2423}
2424
2425impl<E> IntoElement for Stateful<E>
2426where
2427 E: Element,
2428{
2429 type Element = Self;
2430
2431 fn into_element(self) -> Self::Element {
2432 self
2433 }
2434}
2435
2436impl<E> ParentElement for Stateful<E>
2437where
2438 E: ParentElement,
2439{
2440 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
2441 self.element.extend(elements)
2442 }
2443}
2444
2445#[derive(Default, Debug)]
2446struct ScrollHandleState {
2447 offset: Rc<RefCell<Point<Pixels>>>,
2448 bounds: Bounds<Pixels>,
2449 child_bounds: Vec<Bounds<Pixels>>,
2450 requested_scroll_top: Option<(usize, Pixels)>,
2451 overflow: Point<Overflow>,
2452}
2453
2454/// A handle to the scrollable aspects of an element.
2455/// Used for accessing scroll state, like the current scroll offset,
2456/// and for mutating the scroll state, like scrolling to a specific child.
2457#[derive(Clone, Debug)]
2458pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
2459
2460impl Default for ScrollHandle {
2461 fn default() -> Self {
2462 Self::new()
2463 }
2464}
2465
2466impl ScrollHandle {
2467 /// Construct a new scroll handle.
2468 pub fn new() -> Self {
2469 Self(Rc::default())
2470 }
2471
2472 /// Get the current scroll offset.
2473 pub fn offset(&self) -> Point<Pixels> {
2474 *self.0.borrow().offset.borrow()
2475 }
2476
2477 /// Get the top child that's scrolled into view.
2478 pub fn top_item(&self) -> usize {
2479 let state = self.0.borrow();
2480 let top = state.bounds.top() - state.offset.borrow().y;
2481
2482 match state.child_bounds.binary_search_by(|bounds| {
2483 if top < bounds.top() {
2484 Ordering::Greater
2485 } else if top > bounds.bottom() {
2486 Ordering::Less
2487 } else {
2488 Ordering::Equal
2489 }
2490 }) {
2491 Ok(ix) => ix,
2492 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
2493 }
2494 }
2495
2496 /// Return the bounds into which this child is painted
2497 pub fn bounds(&self) -> Bounds<Pixels> {
2498 self.0.borrow().bounds
2499 }
2500
2501 /// Set the bounds into which this child is painted
2502 pub(super) fn set_bounds(&self, bounds: Bounds<Pixels>) {
2503 self.0.borrow_mut().bounds = bounds;
2504 }
2505
2506 /// Get the bounds for a specific child.
2507 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
2508 self.0.borrow().child_bounds.get(ix).cloned()
2509 }
2510
2511 /// scroll_to_item scrolls the minimal amount to ensure that the child is
2512 /// fully visible
2513 pub fn scroll_to_item(&self, ix: usize) {
2514 let state = self.0.borrow();
2515
2516 let Some(bounds) = state.child_bounds.get(ix) else {
2517 return;
2518 };
2519
2520 let mut scroll_offset = state.offset.borrow_mut();
2521
2522 if state.overflow.y == Overflow::Scroll {
2523 if bounds.top() + scroll_offset.y < state.bounds.top() {
2524 scroll_offset.y = state.bounds.top() - bounds.top();
2525 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
2526 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
2527 }
2528 }
2529
2530 if state.overflow.x == Overflow::Scroll {
2531 if bounds.left() + scroll_offset.x < state.bounds.left() {
2532 scroll_offset.x = state.bounds.left() - bounds.left();
2533 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
2534 scroll_offset.x = state.bounds.right() - bounds.right();
2535 }
2536 }
2537 }
2538
2539 /// Set the offset explicitly. The offset is the distance from the top left of the
2540 /// parent container to the top left of the first child.
2541 /// As you scroll further down the offset becomes more negative.
2542 pub fn set_offset(&self, mut position: Point<Pixels>) {
2543 let state = self.0.borrow();
2544 *state.offset.borrow_mut() = position;
2545 }
2546
2547 /// Get the logical scroll top, based on a child index and a pixel offset.
2548 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
2549 let ix = self.top_item();
2550 let state = self.0.borrow();
2551
2552 if let Some(child_bounds) = state.child_bounds.get(ix) {
2553 (
2554 ix,
2555 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
2556 )
2557 } else {
2558 (ix, px(0.))
2559 }
2560 }
2561
2562 /// Set the logical scroll top, based on a child index and a pixel offset.
2563 pub fn set_logical_scroll_top(&self, ix: usize, px: Pixels) {
2564 self.0.borrow_mut().requested_scroll_top = Some((ix, px));
2565 }
2566}