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