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 = Interactivity {
1012 location: Some(*core::panic::Location::caller()),
1013 ..Default::default()
1014 };
1015
1016 #[cfg(not(debug_assertions))]
1017 let interactivity = Interactivity::default();
1018
1019 Div {
1020 interactivity,
1021 children: SmallVec::default(),
1022 }
1023}
1024
1025/// A [`Div`] element, the all-in-one element for building complex UIs in GPUI
1026pub struct Div {
1027 interactivity: Interactivity,
1028 children: SmallVec<[AnyElement; 2]>,
1029}
1030
1031impl Styled for Div {
1032 fn style(&mut self) -> &mut StyleRefinement {
1033 &mut self.interactivity.base_style
1034 }
1035}
1036
1037impl InteractiveElement for Div {
1038 fn interactivity(&mut self) -> &mut Interactivity {
1039 &mut self.interactivity
1040 }
1041}
1042
1043impl ParentElement for Div {
1044 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1045 self.children.extend(elements)
1046 }
1047}
1048
1049impl Element for Div {
1050 type State = DivState;
1051
1052 fn request_layout(
1053 &mut self,
1054 element_state: Option<Self::State>,
1055 cx: &mut ElementContext,
1056 ) -> (LayoutId, Self::State) {
1057 let mut child_layout_ids = SmallVec::new();
1058 let (layout_id, interactive_state) = self.interactivity.layout(
1059 element_state.map(|s| s.interactive_state),
1060 cx,
1061 |style, cx| {
1062 cx.with_text_style(style.text_style().cloned(), |cx| {
1063 child_layout_ids = self
1064 .children
1065 .iter_mut()
1066 .map(|child| child.request_layout(cx))
1067 .collect::<SmallVec<_>>();
1068 cx.request_layout(&style, child_layout_ids.iter().copied())
1069 })
1070 },
1071 );
1072 (
1073 layout_id,
1074 DivState {
1075 interactive_state,
1076 child_layout_ids,
1077 },
1078 )
1079 }
1080
1081 fn paint(
1082 &mut self,
1083 bounds: Bounds<Pixels>,
1084 element_state: &mut Self::State,
1085 cx: &mut ElementContext,
1086 ) {
1087 let mut child_min = point(Pixels::MAX, Pixels::MAX);
1088 let mut child_max = Point::default();
1089 let content_size = if element_state.child_layout_ids.is_empty() {
1090 bounds.size
1091 } else if let Some(scroll_handle) = self.interactivity.scroll_handle.as_ref() {
1092 let mut state = scroll_handle.0.borrow_mut();
1093 state.child_bounds = Vec::with_capacity(element_state.child_layout_ids.len());
1094 state.bounds = bounds;
1095 let requested = state.requested_scroll_top.take();
1096
1097 for (ix, child_layout_id) in element_state.child_layout_ids.iter().enumerate() {
1098 let child_bounds = cx.layout_bounds(*child_layout_id);
1099 child_min = child_min.min(&child_bounds.origin);
1100 child_max = child_max.max(&child_bounds.lower_right());
1101 state.child_bounds.push(child_bounds);
1102
1103 if let Some(requested) = requested.as_ref() {
1104 if requested.0 == ix {
1105 *state.offset.borrow_mut() =
1106 bounds.origin - (child_bounds.origin - point(px(0.), requested.1));
1107 }
1108 }
1109 }
1110 (child_max - child_min).into()
1111 } else {
1112 for child_layout_id in &element_state.child_layout_ids {
1113 let child_bounds = cx.layout_bounds(*child_layout_id);
1114 child_min = child_min.min(&child_bounds.origin);
1115 child_max = child_max.max(&child_bounds.lower_right());
1116 }
1117 (child_max - child_min).into()
1118 };
1119
1120 self.interactivity.paint(
1121 bounds,
1122 content_size,
1123 &mut element_state.interactive_state,
1124 cx,
1125 |_style, scroll_offset, cx| {
1126 cx.with_element_offset(scroll_offset, |cx| {
1127 for child in &mut self.children {
1128 child.paint(cx);
1129 }
1130 })
1131 },
1132 );
1133 }
1134}
1135
1136impl IntoElement for Div {
1137 type Element = Self;
1138
1139 fn element_id(&self) -> Option<ElementId> {
1140 self.interactivity.element_id.clone()
1141 }
1142
1143 fn into_element(self) -> Self::Element {
1144 self
1145 }
1146}
1147
1148/// The state a div needs to keep track of between frames.
1149pub struct DivState {
1150 child_layout_ids: SmallVec<[LayoutId; 2]>,
1151 interactive_state: InteractiveElementState,
1152}
1153
1154impl DivState {
1155 /// Is the div currently being clicked on?
1156 pub fn is_active(&self) -> bool {
1157 self.interactive_state
1158 .pending_mouse_down
1159 .as_ref()
1160 .map_or(false, |pending| pending.borrow().is_some())
1161 }
1162}
1163
1164/// The interactivity struct. Powers all of the general-purpose
1165/// interactivity in the `Div` element.
1166#[derive(Default)]
1167pub struct Interactivity {
1168 /// The element ID of the element
1169 pub element_id: Option<ElementId>,
1170 pub(crate) key_context: Option<KeyContext>,
1171 pub(crate) focusable: bool,
1172 pub(crate) tracked_focus_handle: Option<FocusHandle>,
1173 pub(crate) scroll_handle: Option<ScrollHandle>,
1174 pub(crate) group: Option<SharedString>,
1175 /// The base style of the element, before any modifications are applied
1176 /// by focus, active, etc.
1177 pub base_style: Box<StyleRefinement>,
1178 pub(crate) focus_style: Option<Box<StyleRefinement>>,
1179 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
1180 pub(crate) hover_style: Option<Box<StyleRefinement>>,
1181 pub(crate) group_hover_style: Option<GroupStyle>,
1182 pub(crate) active_style: Option<Box<StyleRefinement>>,
1183 pub(crate) group_active_style: Option<GroupStyle>,
1184 pub(crate) drag_over_styles: Vec<(TypeId, StyleRefinement)>,
1185 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
1186 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
1187 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
1188 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
1189 pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
1190 pub(crate) key_down_listeners: Vec<KeyDownListener>,
1191 pub(crate) key_up_listeners: Vec<KeyUpListener>,
1192 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
1193 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
1194 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
1195 pub(crate) click_listeners: Vec<ClickListener>,
1196 pub(crate) drag_listener: Option<(Box<dyn Any>, DragListener)>,
1197 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut WindowContext)>>,
1198 pub(crate) tooltip_builder: Option<TooltipBuilder>,
1199 pub(crate) block_mouse: bool,
1200
1201 #[cfg(debug_assertions)]
1202 pub(crate) location: Option<core::panic::Location<'static>>,
1203
1204 #[cfg(any(test, feature = "test-support"))]
1205 pub(crate) debug_selector: Option<String>,
1206}
1207
1208/// The bounds and depth of an element in the computed element tree.
1209#[derive(Clone, Debug)]
1210pub struct InteractiveBounds {
1211 /// The 2D bounds of the element
1212 pub bounds: Bounds<Pixels>,
1213 /// The 'stacking order', or depth, for this element
1214 pub stacking_order: StackingOrder,
1215}
1216
1217impl InteractiveBounds {
1218 /// Checks whether this point was inside these bounds, and that these bounds where the topmost layer
1219 pub fn visibly_contains(&self, point: &Point<Pixels>, cx: &WindowContext) -> bool {
1220 self.bounds.contains(point) && cx.was_top_layer(point, &self.stacking_order)
1221 }
1222
1223 /// Checks whether this point was inside these bounds, and that these bounds where the topmost layer
1224 /// under an active drag
1225 pub fn drag_target_contains(&self, point: &Point<Pixels>, cx: &WindowContext) -> bool {
1226 self.bounds.contains(point)
1227 && cx.was_top_layer_under_active_drag(point, &self.stacking_order)
1228 }
1229}
1230
1231impl Interactivity {
1232 /// Layout this element according to this interactivity state's configured styles
1233 pub fn layout(
1234 &mut self,
1235 element_state: Option<InteractiveElementState>,
1236 cx: &mut ElementContext,
1237 f: impl FnOnce(Style, &mut ElementContext) -> LayoutId,
1238 ) -> (LayoutId, InteractiveElementState) {
1239 let mut element_state = element_state.unwrap_or_default();
1240
1241 if cx.has_active_drag() {
1242 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
1243 *pending_mouse_down.borrow_mut() = None;
1244 }
1245 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1246 *clicked_state.borrow_mut() = ElementClickedState::default();
1247 }
1248 }
1249
1250 // Ensure we store a focus handle in our element state if we're focusable.
1251 // If there's an explicit focus handle we're tracking, use that. Otherwise
1252 // create a new handle and store it in the element state, which lives for as
1253 // as frames contain an element with this id.
1254 if self.focusable {
1255 element_state.focus_handle.get_or_insert_with(|| {
1256 self.tracked_focus_handle
1257 .clone()
1258 .unwrap_or_else(|| cx.focus_handle())
1259 });
1260 }
1261
1262 if let Some(scroll_handle) = self.scroll_handle.as_ref() {
1263 element_state.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
1264 }
1265
1266 let style = self.compute_style(None, &mut element_state, cx);
1267 let layout_id = f(style, cx);
1268 (layout_id, element_state)
1269 }
1270
1271 /// Paint this element according to this interactivity state's configured styles
1272 /// and bind the element's mouse and keyboard events.
1273 ///
1274 /// content_size is the size of the content of the element, which may be larger than the
1275 /// element's bounds if the element is scrollable.
1276 ///
1277 /// the final computed style will be passed to the provided function, along
1278 /// with the current scroll offset
1279 pub fn paint(
1280 &mut self,
1281 bounds: Bounds<Pixels>,
1282 content_size: Size<Pixels>,
1283 element_state: &mut InteractiveElementState,
1284 cx: &mut ElementContext,
1285 f: impl FnOnce(&Style, Point<Pixels>, &mut ElementContext),
1286 ) {
1287 let style = self.compute_style(Some(bounds), element_state, cx);
1288 let z_index = style.z_index.unwrap_or(0);
1289
1290 #[cfg(any(feature = "test-support", test))]
1291 if let Some(debug_selector) = &self.debug_selector {
1292 cx.window
1293 .next_frame
1294 .debug_bounds
1295 .insert(debug_selector.clone(), bounds);
1296 }
1297
1298 let paint_hover_group_handler = |cx: &mut ElementContext| {
1299 let hover_group_bounds = self
1300 .group_hover_style
1301 .as_ref()
1302 .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
1303
1304 if let Some(group_bounds) = hover_group_bounds {
1305 let hovered = group_bounds.contains(&cx.mouse_position());
1306 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1307 if phase == DispatchPhase::Capture
1308 && group_bounds.contains(&event.position) != hovered
1309 {
1310 cx.refresh();
1311 }
1312 });
1313 }
1314 };
1315
1316 if style.visibility == Visibility::Hidden {
1317 cx.with_z_index(z_index, |cx| paint_hover_group_handler(cx));
1318 return;
1319 }
1320
1321 cx.with_z_index(z_index, |cx| {
1322 style.paint(bounds, cx, |cx: &mut ElementContext| {
1323 cx.with_text_style(style.text_style().cloned(), |cx| {
1324 cx.with_content_mask(style.overflow_mask(bounds, cx.rem_size()), |cx| {
1325 #[cfg(debug_assertions)]
1326 if self.element_id.is_some()
1327 && (style.debug
1328 || style.debug_below
1329 || cx.has_global::<crate::DebugBelow>())
1330 && bounds.contains(&cx.mouse_position())
1331 {
1332 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
1333 let element_id = format!("{:?}", self.element_id.as_ref().unwrap());
1334 let str_len = element_id.len();
1335
1336 let render_debug_text = |cx: &mut ElementContext| {
1337 if let Some(text) = cx
1338 .text_system()
1339 .shape_text(
1340 element_id.into(),
1341 FONT_SIZE,
1342 &[cx.text_style().to_run(str_len)],
1343 None,
1344 )
1345 .ok()
1346 .and_then(|mut text| text.pop())
1347 {
1348 text.paint(bounds.origin, FONT_SIZE, cx).ok();
1349
1350 let text_bounds = crate::Bounds {
1351 origin: bounds.origin,
1352 size: text.size(FONT_SIZE),
1353 };
1354 if self.location.is_some()
1355 && text_bounds.contains(&cx.mouse_position())
1356 && cx.modifiers().command
1357 {
1358 let command_held = cx.modifiers().command;
1359 cx.on_key_event({
1360 move |e: &crate::ModifiersChangedEvent, _phase, cx| {
1361 if e.modifiers.command != command_held
1362 && text_bounds.contains(&cx.mouse_position())
1363 {
1364 cx.refresh();
1365 }
1366 }
1367 });
1368
1369 let hovered = bounds.contains(&cx.mouse_position());
1370 cx.on_mouse_event(
1371 move |event: &MouseMoveEvent, phase, cx| {
1372 if phase == DispatchPhase::Capture
1373 && bounds.contains(&event.position) != hovered
1374 {
1375 cx.refresh();
1376 }
1377 },
1378 );
1379
1380 cx.on_mouse_event({
1381 let location = self.location.unwrap();
1382 move |e: &crate::MouseDownEvent, phase, cx| {
1383 if text_bounds.contains(&e.position)
1384 && phase.capture()
1385 {
1386 cx.stop_propagation();
1387 let Ok(dir) = std::env::current_dir() else {
1388 return;
1389 };
1390
1391 eprintln!(
1392 "This element was created at:\n{}:{}:{}",
1393 dir.join(location.file()).to_string_lossy(),
1394 location.line(),
1395 location.column()
1396 );
1397 }
1398 }
1399 });
1400 cx.paint_quad(crate::outline(
1401 crate::Bounds {
1402 origin: bounds.origin
1403 + crate::point(
1404 crate::px(0.),
1405 FONT_SIZE - px(2.),
1406 ),
1407 size: crate::Size {
1408 width: text_bounds.size.width,
1409 height: crate::px(1.),
1410 },
1411 },
1412 crate::red(),
1413 ))
1414 }
1415 }
1416 };
1417
1418 cx.with_z_index(1, |cx| {
1419 cx.with_text_style(
1420 Some(crate::TextStyleRefinement {
1421 color: Some(crate::red()),
1422 line_height: Some(FONT_SIZE.into()),
1423 background_color: Some(crate::white()),
1424 ..Default::default()
1425 }),
1426 render_debug_text,
1427 )
1428 });
1429 }
1430
1431 let interactive_bounds = InteractiveBounds {
1432 bounds: bounds.intersect(&cx.content_mask().bounds),
1433 stacking_order: cx.stacking_order().clone(),
1434 };
1435
1436 if self.block_mouse
1437 || style.background.as_ref().is_some_and(|fill| {
1438 fill.color().is_some_and(|color| !color.is_transparent())
1439 })
1440 {
1441 cx.add_opaque_layer(interactive_bounds.bounds);
1442 }
1443
1444 if !cx.has_active_drag() {
1445 if let Some(mouse_cursor) = style.mouse_cursor {
1446 let mouse_position = &cx.mouse_position();
1447 let hovered =
1448 interactive_bounds.visibly_contains(mouse_position, cx);
1449 if hovered {
1450 cx.set_cursor_style(mouse_cursor);
1451 }
1452 }
1453 }
1454
1455 // If this element can be focused, register a mouse down listener
1456 // that will automatically transfer focus when hitting the element.
1457 // This behavior can be suppressed by using `cx.prevent_default()`.
1458 if let Some(focus_handle) = element_state.focus_handle.clone() {
1459 cx.on_mouse_event({
1460 let interactive_bounds = interactive_bounds.clone();
1461 move |event: &MouseDownEvent, phase, cx| {
1462 if phase == DispatchPhase::Bubble
1463 && !cx.default_prevented()
1464 && interactive_bounds.visibly_contains(&event.position, cx)
1465 {
1466 cx.focus(&focus_handle);
1467 // If there is a parent that is also focusable, prevent it
1468 // from transferring focus because we already did so.
1469 cx.prevent_default();
1470 }
1471 }
1472 });
1473 }
1474
1475 for listener in self.mouse_down_listeners.drain(..) {
1476 let interactive_bounds = interactive_bounds.clone();
1477 cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
1478 listener(event, &interactive_bounds, phase, cx);
1479 })
1480 }
1481
1482 for listener in self.mouse_up_listeners.drain(..) {
1483 let interactive_bounds = interactive_bounds.clone();
1484 cx.on_mouse_event(move |event: &MouseUpEvent, phase, cx| {
1485 listener(event, &interactive_bounds, phase, cx);
1486 })
1487 }
1488
1489 for listener in self.mouse_move_listeners.drain(..) {
1490 let interactive_bounds = interactive_bounds.clone();
1491 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1492 listener(event, &interactive_bounds, phase, cx);
1493 })
1494 }
1495
1496 for listener in self.scroll_wheel_listeners.drain(..) {
1497 let interactive_bounds = interactive_bounds.clone();
1498 cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1499 listener(event, &interactive_bounds, phase, cx);
1500 })
1501 }
1502
1503 paint_hover_group_handler(cx);
1504
1505 if self.hover_style.is_some()
1506 || self.base_style.mouse_cursor.is_some()
1507 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
1508 {
1509 let bounds = bounds.intersect(&cx.content_mask().bounds);
1510 let hovered = bounds.contains(&cx.mouse_position());
1511 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1512 if phase == DispatchPhase::Capture
1513 && bounds.contains(&event.position) != hovered
1514 {
1515 cx.refresh();
1516 }
1517 });
1518 }
1519
1520 let mut drag_listener = mem::take(&mut self.drag_listener);
1521 let drop_listeners = mem::take(&mut self.drop_listeners);
1522 let click_listeners = mem::take(&mut self.click_listeners);
1523 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
1524
1525 if !drop_listeners.is_empty() {
1526 cx.on_mouse_event({
1527 let interactive_bounds = interactive_bounds.clone();
1528 move |event: &MouseUpEvent, phase, cx| {
1529 if let Some(drag) = &cx.active_drag {
1530 if phase == DispatchPhase::Bubble
1531 && interactive_bounds
1532 .drag_target_contains(&event.position, cx)
1533 {
1534 let drag_state_type = drag.value.as_ref().type_id();
1535 for (drop_state_type, listener) in &drop_listeners {
1536 if *drop_state_type == drag_state_type {
1537 let drag = cx.active_drag.take().expect(
1538 "checked for type drag state type above",
1539 );
1540
1541 let mut can_drop = true;
1542 if let Some(predicate) = &can_drop_predicate {
1543 can_drop = predicate(
1544 drag.value.as_ref(),
1545 cx.deref_mut(),
1546 );
1547 }
1548
1549 if can_drop {
1550 listener(
1551 drag.value.as_ref(),
1552 cx.deref_mut(),
1553 );
1554 cx.refresh();
1555 cx.stop_propagation();
1556 }
1557 }
1558 }
1559 }
1560 }
1561 }
1562 });
1563 }
1564
1565 if !click_listeners.is_empty() || drag_listener.is_some() {
1566 let pending_mouse_down = element_state
1567 .pending_mouse_down
1568 .get_or_insert_with(Default::default)
1569 .clone();
1570
1571 let clicked_state = element_state
1572 .clicked_state
1573 .get_or_insert_with(Default::default)
1574 .clone();
1575
1576 cx.on_mouse_event({
1577 let interactive_bounds = interactive_bounds.clone();
1578 let pending_mouse_down = pending_mouse_down.clone();
1579 move |event: &MouseDownEvent, phase, cx| {
1580 if phase == DispatchPhase::Bubble
1581 && event.button == MouseButton::Left
1582 && interactive_bounds.visibly_contains(&event.position, cx)
1583 {
1584 *pending_mouse_down.borrow_mut() = Some(event.clone());
1585 cx.refresh();
1586 }
1587 }
1588 });
1589
1590 cx.on_mouse_event({
1591 let pending_mouse_down = pending_mouse_down.clone();
1592 move |event: &MouseMoveEvent, phase, cx| {
1593 if phase == DispatchPhase::Capture {
1594 return;
1595 }
1596
1597 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
1598 if let Some(mouse_down) = pending_mouse_down.clone() {
1599 if !cx.has_active_drag()
1600 && (event.position - mouse_down.position).magnitude()
1601 > DRAG_THRESHOLD
1602 {
1603 if let Some((drag_value, drag_listener)) =
1604 drag_listener.take()
1605 {
1606 *clicked_state.borrow_mut() =
1607 ElementClickedState::default();
1608 let cursor_offset = event.position - bounds.origin;
1609 let drag = (drag_listener)(drag_value.as_ref(), cx);
1610 cx.active_drag = Some(AnyDrag {
1611 view: drag,
1612 value: drag_value,
1613 cursor_offset,
1614 });
1615 pending_mouse_down.take();
1616 cx.refresh();
1617 cx.stop_propagation();
1618 }
1619 }
1620 }
1621 }
1622 });
1623
1624 cx.on_mouse_event({
1625 let interactive_bounds = interactive_bounds.clone();
1626 let mut captured_mouse_down = None;
1627 move |event: &MouseUpEvent, phase, cx| match phase {
1628 // Clear the pending mouse down during the capture phase,
1629 // so that it happens even if another event handler stops
1630 // propagation.
1631 DispatchPhase::Capture => {
1632 let mut pending_mouse_down =
1633 pending_mouse_down.borrow_mut();
1634 if pending_mouse_down.is_some() {
1635 captured_mouse_down = pending_mouse_down.take();
1636 cx.refresh();
1637 }
1638 }
1639 // Fire click handlers during the bubble phase.
1640 DispatchPhase::Bubble => {
1641 if let Some(mouse_down) = captured_mouse_down.take() {
1642 if interactive_bounds
1643 .visibly_contains(&event.position, cx)
1644 {
1645 let mouse_click = ClickEvent {
1646 down: mouse_down,
1647 up: event.clone(),
1648 };
1649 for listener in &click_listeners {
1650 listener(&mouse_click, cx);
1651 }
1652 }
1653 }
1654 }
1655 }
1656 });
1657 }
1658
1659 if let Some(hover_listener) = self.hover_listener.take() {
1660 let was_hovered = element_state
1661 .hover_state
1662 .get_or_insert_with(Default::default)
1663 .clone();
1664 let has_mouse_down = element_state
1665 .pending_mouse_down
1666 .get_or_insert_with(Default::default)
1667 .clone();
1668 let interactive_bounds = interactive_bounds.clone();
1669
1670 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1671 if phase != DispatchPhase::Bubble {
1672 return;
1673 }
1674 let is_hovered = interactive_bounds
1675 .visibly_contains(&event.position, cx)
1676 && has_mouse_down.borrow().is_none()
1677 && !cx.has_active_drag();
1678 let mut was_hovered = was_hovered.borrow_mut();
1679
1680 if is_hovered != *was_hovered {
1681 *was_hovered = is_hovered;
1682 drop(was_hovered);
1683
1684 hover_listener(&is_hovered, cx.deref_mut());
1685 }
1686 });
1687 }
1688
1689 if let Some(tooltip_builder) = self.tooltip_builder.take() {
1690 let active_tooltip = element_state
1691 .active_tooltip
1692 .get_or_insert_with(Default::default)
1693 .clone();
1694 let pending_mouse_down = element_state
1695 .pending_mouse_down
1696 .get_or_insert_with(Default::default)
1697 .clone();
1698 let interactive_bounds = interactive_bounds.clone();
1699
1700 cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| {
1701 let is_hovered = interactive_bounds
1702 .visibly_contains(&event.position, cx)
1703 && pending_mouse_down.borrow().is_none();
1704 if !is_hovered {
1705 active_tooltip.borrow_mut().take();
1706 return;
1707 }
1708
1709 if phase != DispatchPhase::Bubble {
1710 return;
1711 }
1712
1713 if active_tooltip.borrow().is_none() {
1714 let task = cx.spawn({
1715 let active_tooltip = active_tooltip.clone();
1716 let tooltip_builder = tooltip_builder.clone();
1717
1718 move |mut cx| async move {
1719 cx.background_executor().timer(TOOLTIP_DELAY).await;
1720 cx.update(|cx| {
1721 active_tooltip.borrow_mut().replace(
1722 ActiveTooltip {
1723 tooltip: Some(AnyTooltip {
1724 view: tooltip_builder(cx),
1725 cursor_offset: cx.mouse_position(),
1726 }),
1727 _task: None,
1728 },
1729 );
1730 cx.refresh();
1731 })
1732 .ok();
1733 }
1734 });
1735 active_tooltip.borrow_mut().replace(ActiveTooltip {
1736 tooltip: None,
1737 _task: Some(task),
1738 });
1739 }
1740 });
1741
1742 let active_tooltip = element_state
1743 .active_tooltip
1744 .get_or_insert_with(Default::default)
1745 .clone();
1746 cx.on_mouse_event(move |_: &MouseDownEvent, _, _| {
1747 active_tooltip.borrow_mut().take();
1748 });
1749
1750 if let Some(active_tooltip) = element_state
1751 .active_tooltip
1752 .get_or_insert_with(Default::default)
1753 .borrow()
1754 .as_ref()
1755 {
1756 if let Some(tooltip) = active_tooltip.tooltip.clone() {
1757 cx.set_tooltip(tooltip);
1758 }
1759 }
1760 }
1761
1762 let active_state = element_state
1763 .clicked_state
1764 .get_or_insert_with(Default::default)
1765 .clone();
1766 if active_state.borrow().is_clicked() {
1767 cx.on_mouse_event(move |_: &MouseUpEvent, phase, cx| {
1768 if phase == DispatchPhase::Capture {
1769 *active_state.borrow_mut() = ElementClickedState::default();
1770 cx.refresh();
1771 }
1772 });
1773 } else {
1774 let active_group_bounds = self
1775 .group_active_style
1776 .as_ref()
1777 .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
1778 let interactive_bounds = interactive_bounds.clone();
1779 cx.on_mouse_event(move |down: &MouseDownEvent, phase, cx| {
1780 if phase == DispatchPhase::Bubble && !cx.default_prevented() {
1781 let group = active_group_bounds
1782 .map_or(false, |bounds| bounds.contains(&down.position));
1783 let element =
1784 interactive_bounds.visibly_contains(&down.position, cx);
1785 if group || element {
1786 *active_state.borrow_mut() =
1787 ElementClickedState { group, element };
1788 cx.refresh();
1789 }
1790 }
1791 });
1792 }
1793
1794 let overflow = style.overflow;
1795 if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
1796 if let Some(scroll_handle) = &self.scroll_handle {
1797 scroll_handle.0.borrow_mut().overflow = overflow;
1798 }
1799
1800 let scroll_offset = element_state
1801 .scroll_offset
1802 .get_or_insert_with(Rc::default)
1803 .clone();
1804 let line_height = cx.line_height();
1805 let rem_size = cx.rem_size();
1806 let padding_size = size(
1807 style
1808 .padding
1809 .left
1810 .to_pixels(bounds.size.width.into(), rem_size)
1811 + style
1812 .padding
1813 .right
1814 .to_pixels(bounds.size.width.into(), rem_size),
1815 style
1816 .padding
1817 .top
1818 .to_pixels(bounds.size.height.into(), rem_size)
1819 + style
1820 .padding
1821 .bottom
1822 .to_pixels(bounds.size.height.into(), rem_size),
1823 );
1824 let scroll_max =
1825 (content_size + padding_size - bounds.size).max(&Size::default());
1826 // Clamp scroll offset in case scroll max is smaller now (e.g., if children
1827 // were removed or the bounds became larger).
1828 {
1829 let mut scroll_offset = scroll_offset.borrow_mut();
1830 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.width, px(0.));
1831 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.height, px(0.));
1832 }
1833
1834 let interactive_bounds = interactive_bounds.clone();
1835 cx.on_mouse_event(move |event: &ScrollWheelEvent, phase, cx| {
1836 if phase == DispatchPhase::Bubble
1837 && interactive_bounds.visibly_contains(&event.position, cx)
1838 {
1839 let mut scroll_offset = scroll_offset.borrow_mut();
1840 let old_scroll_offset = *scroll_offset;
1841 let delta = event.delta.pixel_delta(line_height);
1842
1843 if overflow.x == Overflow::Scroll {
1844 let mut delta_x = Pixels::ZERO;
1845 if !delta.x.is_zero() {
1846 delta_x = delta.x;
1847 } else if overflow.y != Overflow::Scroll {
1848 delta_x = delta.y;
1849 }
1850
1851 scroll_offset.x = (scroll_offset.x + delta_x)
1852 .clamp(-scroll_max.width, px(0.));
1853 }
1854
1855 if overflow.y == Overflow::Scroll {
1856 let mut delta_y = Pixels::ZERO;
1857 if !delta.y.is_zero() {
1858 delta_y = delta.y;
1859 } else if overflow.x != Overflow::Scroll {
1860 delta_y = delta.x;
1861 }
1862
1863 scroll_offset.y = (scroll_offset.y + delta_y)
1864 .clamp(-scroll_max.height, px(0.));
1865 }
1866
1867 if *scroll_offset != old_scroll_offset {
1868 cx.refresh();
1869 cx.stop_propagation();
1870 }
1871 }
1872 });
1873 }
1874
1875 if let Some(group) = self.group.clone() {
1876 GroupBounds::push(group, bounds, cx);
1877 }
1878
1879 let scroll_offset = element_state
1880 .scroll_offset
1881 .as_ref()
1882 .map(|scroll_offset| *scroll_offset.borrow());
1883
1884 let key_down_listeners = mem::take(&mut self.key_down_listeners);
1885 let key_up_listeners = mem::take(&mut self.key_up_listeners);
1886 let action_listeners = mem::take(&mut self.action_listeners);
1887 cx.with_key_dispatch(
1888 self.key_context.clone(),
1889 element_state.focus_handle.clone(),
1890 |_, cx| {
1891 for listener in key_down_listeners {
1892 cx.on_key_event(move |event: &KeyDownEvent, phase, cx| {
1893 listener(event, phase, cx);
1894 })
1895 }
1896
1897 for listener in key_up_listeners {
1898 cx.on_key_event(move |event: &KeyUpEvent, phase, cx| {
1899 listener(event, phase, cx);
1900 })
1901 }
1902
1903 for (action_type, listener) in action_listeners {
1904 cx.on_action(action_type, listener)
1905 }
1906
1907 f(&style, scroll_offset.unwrap_or_default(), cx)
1908 },
1909 );
1910
1911 if let Some(group) = self.group.as_ref() {
1912 GroupBounds::pop(group, cx);
1913 }
1914 });
1915 });
1916 });
1917 });
1918 }
1919
1920 /// Compute the visual style for this element, based on the current bounds and the element's state.
1921 pub fn compute_style(
1922 &self,
1923 bounds: Option<Bounds<Pixels>>,
1924 element_state: &mut InteractiveElementState,
1925 cx: &mut ElementContext,
1926 ) -> Style {
1927 let mut style = Style::default();
1928 style.refine(&self.base_style);
1929
1930 cx.with_z_index(style.z_index.unwrap_or(0), |cx| {
1931 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1932 if let Some(in_focus_style) = self.in_focus_style.as_ref() {
1933 if focus_handle.within_focused(cx) {
1934 style.refine(in_focus_style);
1935 }
1936 }
1937
1938 if let Some(focus_style) = self.focus_style.as_ref() {
1939 if focus_handle.is_focused(cx) {
1940 style.refine(focus_style);
1941 }
1942 }
1943 }
1944
1945 if let Some(bounds) = bounds {
1946 let mouse_position = cx.mouse_position();
1947 if !cx.has_active_drag() {
1948 if let Some(group_hover) = self.group_hover_style.as_ref() {
1949 if let Some(group_bounds) =
1950 GroupBounds::get(&group_hover.group, cx.deref_mut())
1951 {
1952 if group_bounds.contains(&mouse_position)
1953 && cx.was_top_layer(&mouse_position, cx.stacking_order())
1954 {
1955 style.refine(&group_hover.style);
1956 }
1957 }
1958 }
1959
1960 if let Some(hover_style) = self.hover_style.as_ref() {
1961 if bounds
1962 .intersect(&cx.content_mask().bounds)
1963 .contains(&mouse_position)
1964 && cx.was_top_layer(&mouse_position, cx.stacking_order())
1965 {
1966 style.refine(hover_style);
1967 }
1968 }
1969 }
1970
1971 if let Some(drag) = cx.active_drag.take() {
1972 let mut can_drop = true;
1973 if let Some(can_drop_predicate) = &self.can_drop_predicate {
1974 can_drop = can_drop_predicate(drag.value.as_ref(), cx.deref_mut());
1975 }
1976
1977 if can_drop {
1978 for (state_type, group_drag_style) in &self.group_drag_over_styles {
1979 if let Some(group_bounds) =
1980 GroupBounds::get(&group_drag_style.group, cx.deref_mut())
1981 {
1982 if *state_type == drag.value.as_ref().type_id()
1983 && group_bounds.contains(&mouse_position)
1984 {
1985 style.refine(&group_drag_style.style);
1986 }
1987 }
1988 }
1989
1990 for (state_type, drag_over_style) in &self.drag_over_styles {
1991 if *state_type == drag.value.as_ref().type_id()
1992 && bounds
1993 .intersect(&cx.content_mask().bounds)
1994 .contains(&mouse_position)
1995 && cx.was_top_layer_under_active_drag(
1996 &mouse_position,
1997 cx.stacking_order(),
1998 )
1999 {
2000 style.refine(drag_over_style);
2001 }
2002 }
2003 }
2004
2005 cx.active_drag = Some(drag);
2006 }
2007 }
2008
2009 let clicked_state = element_state
2010 .clicked_state
2011 .get_or_insert_with(Default::default)
2012 .borrow();
2013 if clicked_state.group {
2014 if let Some(group) = self.group_active_style.as_ref() {
2015 style.refine(&group.style)
2016 }
2017 }
2018
2019 if let Some(active_style) = self.active_style.as_ref() {
2020 if clicked_state.element {
2021 style.refine(active_style)
2022 }
2023 }
2024 });
2025
2026 style
2027 }
2028}
2029
2030/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks
2031/// and scroll offsets.
2032#[derive(Default)]
2033pub struct InteractiveElementState {
2034 pub(crate) focus_handle: Option<FocusHandle>,
2035 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
2036 pub(crate) hover_state: Option<Rc<RefCell<bool>>>,
2037 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
2038 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2039 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
2040}
2041
2042/// The current active tooltip
2043pub struct ActiveTooltip {
2044 pub(crate) tooltip: Option<AnyTooltip>,
2045 pub(crate) _task: Option<Task<()>>,
2046}
2047
2048/// Whether or not the element or a group that contains it is clicked by the mouse.
2049#[derive(Copy, Clone, Default, Eq, PartialEq)]
2050pub struct ElementClickedState {
2051 /// True if this element's group has been clicked, false otherwise
2052 pub group: bool,
2053
2054 /// True if this element has been clicked, false otherwise
2055 pub element: bool,
2056}
2057
2058impl ElementClickedState {
2059 fn is_clicked(&self) -> bool {
2060 self.group || self.element
2061 }
2062}
2063
2064#[derive(Default)]
2065pub(crate) struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
2066
2067impl GroupBounds {
2068 pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
2069 cx.default_global::<Self>()
2070 .0
2071 .get(name)
2072 .and_then(|bounds_stack| bounds_stack.last())
2073 .cloned()
2074 }
2075
2076 pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
2077 cx.default_global::<Self>()
2078 .0
2079 .entry(name)
2080 .or_default()
2081 .push(bounds);
2082 }
2083
2084 pub fn pop(name: &SharedString, cx: &mut AppContext) {
2085 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
2086 }
2087}
2088
2089/// A wrapper around an element that can be focused.
2090pub struct Focusable<E> {
2091 /// The element that is focusable
2092 pub element: E,
2093}
2094
2095impl<E: InteractiveElement> FocusableElement for Focusable<E> {}
2096
2097impl<E> InteractiveElement for Focusable<E>
2098where
2099 E: InteractiveElement,
2100{
2101 fn interactivity(&mut self) -> &mut Interactivity {
2102 self.element.interactivity()
2103 }
2104}
2105
2106impl<E: StatefulInteractiveElement> StatefulInteractiveElement for Focusable<E> {}
2107
2108impl<E> Styled for Focusable<E>
2109where
2110 E: Styled,
2111{
2112 fn style(&mut self) -> &mut StyleRefinement {
2113 self.element.style()
2114 }
2115}
2116
2117impl<E> Element for Focusable<E>
2118where
2119 E: Element,
2120{
2121 type State = E::State;
2122
2123 fn request_layout(
2124 &mut self,
2125 state: Option<Self::State>,
2126 cx: &mut ElementContext,
2127 ) -> (LayoutId, Self::State) {
2128 self.element.request_layout(state, cx)
2129 }
2130
2131 fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut ElementContext) {
2132 self.element.paint(bounds, state, cx)
2133 }
2134}
2135
2136impl<E> IntoElement for Focusable<E>
2137where
2138 E: IntoElement,
2139{
2140 type Element = E::Element;
2141
2142 fn element_id(&self) -> Option<ElementId> {
2143 self.element.element_id()
2144 }
2145
2146 fn into_element(self) -> Self::Element {
2147 self.element.into_element()
2148 }
2149}
2150
2151impl<E> ParentElement for Focusable<E>
2152where
2153 E: ParentElement,
2154{
2155 fn extend(&mut self, elements: impl Iterator<Item = AnyElement>) {
2156 self.element.extend(elements)
2157 }
2158}
2159
2160/// A wrapper around an element that can store state, produced after assigning an ElementId.
2161pub struct Stateful<E> {
2162 element: E,
2163}
2164
2165impl<E> Styled for Stateful<E>
2166where
2167 E: Styled,
2168{
2169 fn style(&mut self) -> &mut StyleRefinement {
2170 self.element.style()
2171 }
2172}
2173
2174impl<E> StatefulInteractiveElement for Stateful<E>
2175where
2176 E: Element,
2177 Self: InteractiveElement,
2178{
2179}
2180
2181impl<E> InteractiveElement for Stateful<E>
2182where
2183 E: InteractiveElement,
2184{
2185 fn interactivity(&mut self) -> &mut Interactivity {
2186 self.element.interactivity()
2187 }
2188}
2189
2190impl<E: FocusableElement> FocusableElement for Stateful<E> {}
2191
2192impl<E> Element for Stateful<E>
2193where
2194 E: Element,
2195{
2196 type State = E::State;
2197
2198 fn request_layout(
2199 &mut self,
2200 state: Option<Self::State>,
2201 cx: &mut ElementContext,
2202 ) -> (LayoutId, Self::State) {
2203 self.element.request_layout(state, cx)
2204 }
2205
2206 fn paint(&mut self, bounds: Bounds<Pixels>, state: &mut Self::State, cx: &mut ElementContext) {
2207 self.element.paint(bounds, state, cx)
2208 }
2209}
2210
2211impl<E> IntoElement for Stateful<E>
2212where
2213 E: Element,
2214{
2215 type Element = Self;
2216
2217 fn element_id(&self) -> Option<ElementId> {
2218 self.element.element_id()
2219 }
2220
2221 fn into_element(self) -> Self::Element {
2222 self
2223 }
2224}
2225
2226impl<E> ParentElement for Stateful<E>
2227where
2228 E: ParentElement,
2229{
2230 fn extend(&mut self, elements: impl Iterator<Item = AnyElement>) {
2231 self.element.extend(elements)
2232 }
2233}
2234
2235#[derive(Default)]
2236struct ScrollHandleState {
2237 offset: Rc<RefCell<Point<Pixels>>>,
2238 bounds: Bounds<Pixels>,
2239 child_bounds: Vec<Bounds<Pixels>>,
2240 requested_scroll_top: Option<(usize, Pixels)>,
2241 overflow: Point<Overflow>,
2242}
2243
2244/// A handle to the scrollable aspects of an element.
2245/// Used for accessing scroll state, like the current scroll offset,
2246/// and for mutating the scroll state, like scrolling to a specific child.
2247#[derive(Clone)]
2248pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
2249
2250impl Default for ScrollHandle {
2251 fn default() -> Self {
2252 Self::new()
2253 }
2254}
2255
2256impl ScrollHandle {
2257 /// Construct a new scroll handle.
2258 pub fn new() -> Self {
2259 Self(Rc::default())
2260 }
2261
2262 /// Get the current scroll offset.
2263 pub fn offset(&self) -> Point<Pixels> {
2264 *self.0.borrow().offset.borrow()
2265 }
2266
2267 /// Get the top child that's scrolled into view.
2268 pub fn top_item(&self) -> usize {
2269 let state = self.0.borrow();
2270 let top = state.bounds.top() - state.offset.borrow().y;
2271
2272 match state.child_bounds.binary_search_by(|bounds| {
2273 if top < bounds.top() {
2274 Ordering::Greater
2275 } else if top > bounds.bottom() {
2276 Ordering::Less
2277 } else {
2278 Ordering::Equal
2279 }
2280 }) {
2281 Ok(ix) => ix,
2282 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
2283 }
2284 }
2285
2286 /// Get the bounds for a specific child.
2287 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
2288 self.0.borrow().child_bounds.get(ix).cloned()
2289 }
2290
2291 /// scroll_to_item scrolls the minimal amount to ensure that the child is
2292 /// fully visible
2293 pub fn scroll_to_item(&self, ix: usize) {
2294 let state = self.0.borrow();
2295
2296 let Some(bounds) = state.child_bounds.get(ix) else {
2297 return;
2298 };
2299
2300 let mut scroll_offset = state.offset.borrow_mut();
2301
2302 if state.overflow.y == Overflow::Scroll {
2303 if bounds.top() + scroll_offset.y < state.bounds.top() {
2304 scroll_offset.y = state.bounds.top() - bounds.top();
2305 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
2306 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
2307 }
2308 }
2309
2310 if state.overflow.x == Overflow::Scroll {
2311 if bounds.left() + scroll_offset.x < state.bounds.left() {
2312 scroll_offset.x = state.bounds.left() - bounds.left();
2313 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
2314 scroll_offset.x = state.bounds.right() - bounds.right();
2315 }
2316 }
2317 }
2318
2319 /// Get the logical scroll top, based on a child index and a pixel offset.
2320 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
2321 let ix = self.top_item();
2322 let state = self.0.borrow();
2323
2324 if let Some(child_bounds) = state.child_bounds.get(ix) {
2325 (
2326 ix,
2327 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
2328 )
2329 } else {
2330 (ix, px(0.))
2331 }
2332 }
2333
2334 /// Set the logical scroll top, based on a child index and a pixel offset.
2335 pub fn set_logical_scroll_top(&self, ix: usize, px: Pixels) {
2336 self.0.borrow_mut().requested_scroll_top = Some((ix, px));
2337 }
2338}