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