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