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