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