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