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