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},
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 let layout_id =
1303 window.request_layout(style, child_layout_ids.iter().copied(), cx);
1304 if let Some(global_id) = global_id.as_ref()
1305 && global_id.0.ends_with(&["api-key-editor".into()])
1306 {
1307 LAYOUT_ID_TO_DEBUG.with_borrow_mut(|layout_id_to_debug| {
1308 *layout_id_to_debug = Some(layout_id)
1309 });
1310 }
1311 if let Some(global_id) = global_id.as_ref()
1312 && global_id.0.ends_with(&["open-router-container".into()])
1313 {
1314 CONTAINER_LAYOUT_ID_TO_DEBUG.with_borrow_mut(|layout_id_to_debug| {
1315 *layout_id_to_debug = Some(layout_id)
1316 });
1317 }
1318 layout_id
1319 })
1320 },
1321 )
1322 });
1323
1324 (layout_id, DivFrameState { child_layout_ids })
1325 }
1326
1327 fn prepaint(
1328 &mut self,
1329 global_id: Option<&GlobalElementId>,
1330 inspector_id: Option<&InspectorElementId>,
1331 bounds: Bounds<Pixels>,
1332 request_layout: &mut Self::RequestLayoutState,
1333 window: &mut Window,
1334 cx: &mut App,
1335 ) -> Option<Hitbox> {
1336 let has_prepaint_listener = self.prepaint_listener.is_some();
1337 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1338 request_layout.child_layout_ids.len()
1339 } else {
1340 0
1341 });
1342
1343 let mut child_min = point(Pixels::MAX, Pixels::MAX);
1344 let mut child_max = Point::default();
1345 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1346 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1347 }
1348 let content_size = if request_layout.child_layout_ids.is_empty() {
1349 bounds.size
1350 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1351 let mut state = scroll_handle.0.borrow_mut();
1352 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1353 for child_layout_id in &request_layout.child_layout_ids {
1354 let child_bounds = window.layout_bounds(*child_layout_id);
1355 child_min = child_min.min(&child_bounds.origin);
1356 child_max = child_max.max(&child_bounds.bottom_right());
1357 state.child_bounds.push(child_bounds);
1358 }
1359 (child_max - child_min).into()
1360 } else {
1361 for child_layout_id in &request_layout.child_layout_ids {
1362 let child_bounds = window.layout_bounds(*child_layout_id);
1363 child_min = child_min.min(&child_bounds.origin);
1364 child_max = child_max.max(&child_bounds.bottom_right());
1365
1366 if has_prepaint_listener {
1367 children_bounds.push(child_bounds);
1368 }
1369 }
1370 (child_max - child_min).into()
1371 };
1372
1373 self.interactivity.prepaint(
1374 global_id,
1375 inspector_id,
1376 bounds,
1377 content_size,
1378 window,
1379 cx,
1380 |_style, scroll_offset, hitbox, window, cx| {
1381 window.with_element_offset(scroll_offset, |window| {
1382 for child in &mut self.children {
1383 child.prepaint(window, cx);
1384 }
1385 });
1386
1387 if let Some(listener) = self.prepaint_listener.as_ref() {
1388 listener(children_bounds, window, cx);
1389 }
1390
1391 hitbox
1392 },
1393 )
1394 }
1395
1396 fn paint(
1397 &mut self,
1398 global_id: Option<&GlobalElementId>,
1399 inspector_id: Option<&InspectorElementId>,
1400 bounds: Bounds<Pixels>,
1401 _request_layout: &mut Self::RequestLayoutState,
1402 hitbox: &mut Option<Hitbox>,
1403 window: &mut Window,
1404 cx: &mut App,
1405 ) {
1406 let image_cache = self
1407 .image_cache
1408 .as_mut()
1409 .map(|provider| provider.provide(window, cx));
1410
1411 window.with_image_cache(image_cache, |window| {
1412 self.interactivity.paint(
1413 global_id,
1414 inspector_id,
1415 bounds,
1416 hitbox.as_ref(),
1417 window,
1418 cx,
1419 |_style, window, cx| {
1420 for child in &mut self.children {
1421 child.paint(window, cx);
1422 }
1423 },
1424 )
1425 });
1426 }
1427}
1428
1429impl IntoElement for Div {
1430 type Element = Self;
1431
1432 fn into_element(self) -> Self::Element {
1433 self
1434 }
1435}
1436
1437/// The interactivity struct. Powers all of the general-purpose
1438/// interactivity in the `Div` element.
1439#[derive(Default)]
1440pub struct Interactivity {
1441 /// The element ID of the element. In id is required to support a stateful subset of the interactivity such as on_click.
1442 pub element_id: Option<ElementId>,
1443 /// Whether the element was clicked. This will only be present after layout.
1444 pub active: Option<bool>,
1445 /// Whether the element was hovered. This will only be present after paint if an hitbox
1446 /// was created for the interactive element.
1447 pub hovered: Option<bool>,
1448 pub(crate) tooltip_id: Option<TooltipId>,
1449 pub(crate) content_size: Size<Pixels>,
1450 pub(crate) key_context: Option<KeyContext>,
1451 pub(crate) focusable: bool,
1452 pub(crate) tracked_focus_handle: Option<FocusHandle>,
1453 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
1454 pub(crate) scroll_anchor: Option<ScrollAnchor>,
1455 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
1456 pub(crate) group: Option<SharedString>,
1457 /// The base style of the element, before any modifications are applied
1458 /// by focus, active, etc.
1459 pub base_style: Box<StyleRefinement>,
1460 pub(crate) focus_style: Option<Box<StyleRefinement>>,
1461 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
1462 pub(crate) hover_style: Option<Box<StyleRefinement>>,
1463 pub(crate) group_hover_style: Option<GroupStyle>,
1464 pub(crate) active_style: Option<Box<StyleRefinement>>,
1465 pub(crate) group_active_style: Option<GroupStyle>,
1466 pub(crate) drag_over_styles: Vec<(
1467 TypeId,
1468 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
1469 )>,
1470 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
1471 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
1472 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
1473 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
1474 pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
1475 pub(crate) key_down_listeners: Vec<KeyDownListener>,
1476 pub(crate) key_up_listeners: Vec<KeyUpListener>,
1477 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
1478 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
1479 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
1480 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
1481 pub(crate) click_listeners: Vec<ClickListener>,
1482 pub(crate) drag_listener: Option<(Arc<dyn Any>, DragListener)>,
1483 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
1484 pub(crate) tooltip_builder: Option<TooltipBuilder>,
1485 pub(crate) window_control: Option<WindowControlArea>,
1486 pub(crate) hitbox_behavior: HitboxBehavior,
1487 pub(crate) tab_index: Option<isize>,
1488
1489 #[cfg(any(feature = "inspector", debug_assertions))]
1490 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
1491
1492 #[cfg(any(test, feature = "test-support"))]
1493 pub(crate) debug_selector: Option<String>,
1494}
1495
1496impl Interactivity {
1497 /// Layout this element according to this interactivity state's configured styles
1498 pub fn request_layout(
1499 &mut self,
1500 global_id: Option<&GlobalElementId>,
1501 _inspector_id: Option<&InspectorElementId>,
1502 window: &mut Window,
1503 cx: &mut App,
1504 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
1505 ) -> LayoutId {
1506 #[cfg(any(feature = "inspector", debug_assertions))]
1507 window.with_inspector_state(
1508 _inspector_id,
1509 cx,
1510 |inspector_state: &mut Option<DivInspectorState>, _window| {
1511 if let Some(inspector_state) = inspector_state {
1512 self.base_style = inspector_state.base_style.clone();
1513 } else {
1514 *inspector_state = Some(DivInspectorState {
1515 base_style: self.base_style.clone(),
1516 bounds: Default::default(),
1517 content_size: Default::default(),
1518 })
1519 }
1520 },
1521 );
1522
1523 window.with_optional_element_state::<InteractiveElementState, _>(
1524 global_id,
1525 |element_state, window| {
1526 let mut element_state =
1527 element_state.map(|element_state| element_state.unwrap_or_default());
1528
1529 if let Some(element_state) = element_state.as_ref() {
1530 if cx.has_active_drag() {
1531 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref()
1532 {
1533 *pending_mouse_down.borrow_mut() = None;
1534 }
1535 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1536 *clicked_state.borrow_mut() = ElementClickedState::default();
1537 }
1538 }
1539 }
1540
1541 // Ensure we store a focus handle in our element state if we're focusable.
1542 // If there's an explicit focus handle we're tracking, use that. Otherwise
1543 // create a new handle and store it in the element state, which lives for as
1544 // as frames contain an element with this id.
1545 if self.focusable && self.tracked_focus_handle.is_none() {
1546 if let Some(element_state) = element_state.as_mut() {
1547 let mut handle = element_state
1548 .focus_handle
1549 .get_or_insert_with(|| cx.focus_handle())
1550 .clone()
1551 .tab_stop(false);
1552
1553 if let Some(index) = self.tab_index {
1554 handle = handle.tab_index(index).tab_stop(true);
1555 }
1556
1557 self.tracked_focus_handle = Some(handle);
1558 }
1559 }
1560
1561 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
1562 self.scroll_offset = Some(scroll_handle.0.borrow().offset.clone());
1563 } else if self.base_style.overflow.x == Some(Overflow::Scroll)
1564 || self.base_style.overflow.y == Some(Overflow::Scroll)
1565 {
1566 if let Some(element_state) = element_state.as_mut() {
1567 self.scroll_offset = Some(
1568 element_state
1569 .scroll_offset
1570 .get_or_insert_with(Rc::default)
1571 .clone(),
1572 );
1573 }
1574 }
1575
1576 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
1577 let layout_id = f(style, window, cx);
1578 (layout_id, element_state)
1579 },
1580 )
1581 }
1582
1583 /// Commit the bounds of this element according to this interactivity state's configured styles.
1584 pub fn prepaint<R>(
1585 &mut self,
1586 global_id: Option<&GlobalElementId>,
1587 _inspector_id: Option<&InspectorElementId>,
1588 bounds: Bounds<Pixels>,
1589 content_size: Size<Pixels>,
1590 window: &mut Window,
1591 cx: &mut App,
1592 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
1593 ) -> R {
1594 self.content_size = content_size;
1595
1596 #[cfg(any(feature = "inspector", debug_assertions))]
1597 window.with_inspector_state(
1598 _inspector_id,
1599 cx,
1600 |inspector_state: &mut Option<DivInspectorState>, _window| {
1601 if let Some(inspector_state) = inspector_state {
1602 inspector_state.bounds = bounds;
1603 inspector_state.content_size = content_size;
1604 }
1605 },
1606 );
1607
1608 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
1609 window.set_focus_handle(focus_handle, cx);
1610 }
1611 window.with_optional_element_state::<InteractiveElementState, _>(
1612 global_id,
1613 |element_state, window| {
1614 let mut element_state =
1615 element_state.map(|element_state| element_state.unwrap_or_default());
1616 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
1617
1618 if let Some(element_state) = element_state.as_mut() {
1619 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
1620 let clicked_state = clicked_state.borrow();
1621 self.active = Some(clicked_state.element);
1622 }
1623 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
1624 if self.tooltip_builder.is_some() {
1625 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
1626 } else {
1627 // If there is no longer a tooltip builder, remove the active tooltip.
1628 element_state.active_tooltip.take();
1629 }
1630 }
1631 }
1632
1633 window.with_text_style(style.text_style().cloned(), |window| {
1634 window.with_content_mask(
1635 style.overflow_mask(bounds, window.rem_size()),
1636 |window| {
1637 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
1638 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
1639 } else {
1640 None
1641 };
1642
1643 let scroll_offset =
1644 self.clamp_scroll_position(bounds, &style, window, cx);
1645 let result = f(&style, scroll_offset, hitbox, window, cx);
1646 (result, element_state)
1647 },
1648 )
1649 })
1650 },
1651 )
1652 }
1653
1654 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
1655 self.hitbox_behavior != HitboxBehavior::Normal
1656 || self.window_control.is_some()
1657 || style.mouse_cursor.is_some()
1658 || self.group.is_some()
1659 || self.scroll_offset.is_some()
1660 || self.tracked_focus_handle.is_some()
1661 || self.hover_style.is_some()
1662 || self.group_hover_style.is_some()
1663 || self.hover_listener.is_some()
1664 || !self.mouse_up_listeners.is_empty()
1665 || !self.mouse_down_listeners.is_empty()
1666 || !self.mouse_move_listeners.is_empty()
1667 || !self.click_listeners.is_empty()
1668 || !self.scroll_wheel_listeners.is_empty()
1669 || self.drag_listener.is_some()
1670 || !self.drop_listeners.is_empty()
1671 || self.tooltip_builder.is_some()
1672 || window.is_inspector_picking(cx)
1673 }
1674
1675 fn clamp_scroll_position(
1676 &self,
1677 bounds: Bounds<Pixels>,
1678 style: &Style,
1679 window: &mut Window,
1680 _cx: &mut App,
1681 ) -> Point<Pixels> {
1682 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
1683 const ROUNDING_FACTOR: f32 = 100.0;
1684 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
1685 }
1686
1687 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
1688 let mut scroll_to_bottom = false;
1689 let mut tracked_scroll_handle = self
1690 .tracked_scroll_handle
1691 .as_ref()
1692 .map(|handle| handle.0.borrow_mut());
1693 if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
1694 scroll_handle_state.overflow = style.overflow;
1695 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
1696 }
1697
1698 let rem_size = window.rem_size();
1699 let padding = style.padding.to_pixels(bounds.size.into(), rem_size);
1700 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
1701 // The floating point values produced by Taffy and ours often vary
1702 // slightly after ~5 decimal places. This can lead to cases where after
1703 // subtracting these, the container becomes scrollable for less than
1704 // 0.00000x pixels. As we generally don't benefit from a precision that
1705 // high for the maximum scroll, we round the scroll max to 2 decimal
1706 // places here.
1707 let padded_content_size = self.content_size + padding_size;
1708 let scroll_max = (padded_content_size - bounds.size)
1709 .map(round_to_two_decimals)
1710 .max(&Default::default());
1711 // Clamp scroll offset in case scroll max is smaller now (e.g., if children
1712 // were removed or the bounds became larger).
1713 let mut scroll_offset = scroll_offset.borrow_mut();
1714
1715 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.width, px(0.));
1716 if scroll_to_bottom {
1717 scroll_offset.y = -scroll_max.height;
1718 } else {
1719 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.height, px(0.));
1720 }
1721
1722 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
1723 scroll_handle_state.max_offset = scroll_max;
1724 scroll_handle_state.bounds = bounds;
1725 }
1726
1727 *scroll_offset
1728 } else {
1729 Point::default()
1730 }
1731 }
1732
1733 /// Paint this element according to this interactivity state's configured styles
1734 /// and bind the element's mouse and keyboard events.
1735 ///
1736 /// content_size is the size of the content of the element, which may be larger than the
1737 /// element's bounds if the element is scrollable.
1738 ///
1739 /// the final computed style will be passed to the provided function, along
1740 /// with the current scroll offset
1741 pub fn paint(
1742 &mut self,
1743 global_id: Option<&GlobalElementId>,
1744 _inspector_id: Option<&InspectorElementId>,
1745 bounds: Bounds<Pixels>,
1746 hitbox: Option<&Hitbox>,
1747 window: &mut Window,
1748 cx: &mut App,
1749 f: impl FnOnce(&Style, &mut Window, &mut App),
1750 ) {
1751 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
1752 window.with_optional_element_state::<InteractiveElementState, _>(
1753 global_id,
1754 |element_state, window| {
1755 let mut element_state =
1756 element_state.map(|element_state| element_state.unwrap_or_default());
1757
1758 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
1759
1760 #[cfg(any(feature = "test-support", test))]
1761 if let Some(debug_selector) = &self.debug_selector {
1762 window
1763 .next_frame
1764 .debug_bounds
1765 .insert(debug_selector.clone(), bounds);
1766 }
1767
1768 self.paint_hover_group_handler(window, cx);
1769
1770 if style.visibility == Visibility::Hidden {
1771 return ((), element_state);
1772 }
1773
1774 if let Some(focus_handle) = &self.tracked_focus_handle {
1775 window.next_frame.tab_handles.insert(focus_handle);
1776 }
1777
1778 window.with_element_opacity(style.opacity, |window| {
1779 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
1780 window.with_text_style(style.text_style().cloned(), |window| {
1781 window.with_content_mask(
1782 style.overflow_mask(bounds, window.rem_size()),
1783 |window| {
1784 if let Some(hitbox) = hitbox {
1785 #[cfg(debug_assertions)]
1786 self.paint_debug_info(
1787 global_id, hitbox, &style, window, cx,
1788 );
1789
1790 if let Some(drag) = cx.active_drag.as_ref() {
1791 if let Some(mouse_cursor) = drag.cursor_style {
1792 window.set_window_cursor_style(mouse_cursor);
1793 }
1794 } else {
1795 if let Some(mouse_cursor) = style.mouse_cursor {
1796 window.set_cursor_style(mouse_cursor, hitbox);
1797 }
1798 }
1799
1800 if let Some(group) = self.group.clone() {
1801 GroupHitboxes::push(group, hitbox.id, cx);
1802 }
1803
1804 if let Some(area) = self.window_control {
1805 window
1806 .insert_window_control_hitbox(area, hitbox.clone());
1807 }
1808
1809 self.paint_mouse_listeners(
1810 hitbox,
1811 element_state.as_mut(),
1812 window,
1813 cx,
1814 );
1815 self.paint_scroll_listener(hitbox, &style, window, cx);
1816 }
1817
1818 self.paint_keyboard_listeners(window, cx);
1819 f(&style, window, cx);
1820
1821 if let Some(_hitbox) = hitbox {
1822 #[cfg(any(feature = "inspector", debug_assertions))]
1823 window.insert_inspector_hitbox(
1824 _hitbox.id,
1825 _inspector_id,
1826 cx,
1827 );
1828
1829 if let Some(group) = self.group.as_ref() {
1830 GroupHitboxes::pop(group, cx);
1831 }
1832 }
1833 },
1834 );
1835 });
1836 });
1837 });
1838
1839 ((), element_state)
1840 },
1841 );
1842 }
1843
1844 #[cfg(debug_assertions)]
1845 fn paint_debug_info(
1846 &self,
1847 global_id: Option<&GlobalElementId>,
1848 hitbox: &Hitbox,
1849 style: &Style,
1850 window: &mut Window,
1851 cx: &mut App,
1852 ) {
1853 use crate::{BorderStyle, TextAlign};
1854
1855 if global_id.is_some()
1856 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
1857 && hitbox.is_hovered(window)
1858 {
1859 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
1860 let element_id = format!("{:?}", global_id.unwrap());
1861 let str_len = element_id.len();
1862
1863 let render_debug_text = |window: &mut Window| {
1864 if let Some(text) = window
1865 .text_system()
1866 .shape_text(
1867 element_id.into(),
1868 FONT_SIZE,
1869 &[window.text_style().to_run(str_len)],
1870 None,
1871 None,
1872 )
1873 .ok()
1874 .and_then(|mut text| text.pop())
1875 {
1876 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
1877 .ok();
1878
1879 let text_bounds = crate::Bounds {
1880 origin: hitbox.origin,
1881 size: text.size(FONT_SIZE),
1882 };
1883 if self.source_location.is_some()
1884 && text_bounds.contains(&window.mouse_position())
1885 && window.modifiers().secondary()
1886 {
1887 let secondary_held = window.modifiers().secondary();
1888 window.on_key_event({
1889 move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
1890 if e.modifiers.secondary() != secondary_held
1891 && text_bounds.contains(&window.mouse_position())
1892 {
1893 window.refresh();
1894 }
1895 }
1896 });
1897
1898 let was_hovered = hitbox.is_hovered(window);
1899 let current_view = window.current_view();
1900 window.on_mouse_event({
1901 let hitbox = hitbox.clone();
1902 move |_: &MouseMoveEvent, phase, window, cx| {
1903 if phase == DispatchPhase::Capture {
1904 let hovered = hitbox.is_hovered(window);
1905 if hovered != was_hovered {
1906 cx.notify(current_view)
1907 }
1908 }
1909 }
1910 });
1911
1912 window.on_mouse_event({
1913 let hitbox = hitbox.clone();
1914 let location = self.source_location.unwrap();
1915 move |e: &crate::MouseDownEvent, phase, window, cx| {
1916 if text_bounds.contains(&e.position)
1917 && phase.capture()
1918 && hitbox.is_hovered(window)
1919 {
1920 cx.stop_propagation();
1921 let Ok(dir) = std::env::current_dir() else {
1922 return;
1923 };
1924
1925 eprintln!(
1926 "This element was created at:\n{}:{}:{}",
1927 dir.join(location.file()).to_string_lossy(),
1928 location.line(),
1929 location.column()
1930 );
1931 }
1932 }
1933 });
1934 window.paint_quad(crate::outline(
1935 crate::Bounds {
1936 origin: hitbox.origin
1937 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
1938 size: crate::Size {
1939 width: text_bounds.size.width,
1940 height: crate::px(1.),
1941 },
1942 },
1943 crate::red(),
1944 BorderStyle::default(),
1945 ))
1946 }
1947 }
1948 };
1949
1950 window.with_text_style(
1951 Some(crate::TextStyleRefinement {
1952 color: Some(crate::red()),
1953 line_height: Some(FONT_SIZE.into()),
1954 background_color: Some(crate::white()),
1955 ..Default::default()
1956 }),
1957 render_debug_text,
1958 )
1959 }
1960 }
1961
1962 fn paint_mouse_listeners(
1963 &mut self,
1964 hitbox: &Hitbox,
1965 element_state: Option<&mut InteractiveElementState>,
1966 window: &mut Window,
1967 cx: &mut App,
1968 ) {
1969 let is_focused = self
1970 .tracked_focus_handle
1971 .as_ref()
1972 .map(|handle| handle.is_focused(window))
1973 .unwrap_or(false);
1974
1975 // If this element can be focused, register a mouse down listener
1976 // that will automatically transfer focus when hitting the element.
1977 // This behavior can be suppressed by using `cx.prevent_default()`.
1978 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
1979 let hitbox = hitbox.clone();
1980 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _| {
1981 if phase == DispatchPhase::Bubble
1982 && hitbox.is_hovered(window)
1983 && !window.default_prevented()
1984 {
1985 window.focus(&focus_handle);
1986 // If there is a parent that is also focusable, prevent it
1987 // from transferring focus because we already did so.
1988 window.prevent_default();
1989 }
1990 });
1991 }
1992
1993 for listener in self.mouse_down_listeners.drain(..) {
1994 let hitbox = hitbox.clone();
1995 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
1996 listener(event, phase, &hitbox, window, cx);
1997 })
1998 }
1999
2000 for listener in self.mouse_up_listeners.drain(..) {
2001 let hitbox = hitbox.clone();
2002 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2003 listener(event, phase, &hitbox, window, cx);
2004 })
2005 }
2006
2007 for listener in self.mouse_move_listeners.drain(..) {
2008 let hitbox = hitbox.clone();
2009 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2010 listener(event, phase, &hitbox, window, cx);
2011 })
2012 }
2013
2014 for listener in self.scroll_wheel_listeners.drain(..) {
2015 let hitbox = hitbox.clone();
2016 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2017 listener(event, phase, &hitbox, window, cx);
2018 })
2019 }
2020
2021 if self.hover_style.is_some()
2022 || self.base_style.mouse_cursor.is_some()
2023 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2024 {
2025 let hitbox = hitbox.clone();
2026 let was_hovered = hitbox.is_hovered(window);
2027 let current_view = window.current_view();
2028 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2029 let hovered = hitbox.is_hovered(window);
2030 if phase == DispatchPhase::Capture && hovered != was_hovered {
2031 cx.notify(current_view);
2032 }
2033 });
2034 }
2035 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2036
2037 let mut drag_listener = mem::take(&mut self.drag_listener);
2038 let drop_listeners = mem::take(&mut self.drop_listeners);
2039 let click_listeners = mem::take(&mut self.click_listeners);
2040 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2041
2042 if !drop_listeners.is_empty() {
2043 let hitbox = hitbox.clone();
2044 window.on_mouse_event({
2045 move |_: &MouseUpEvent, phase, window, cx| {
2046 if let Some(drag) = &cx.active_drag {
2047 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
2048 let drag_state_type = drag.value.as_ref().type_id();
2049 for (drop_state_type, listener) in &drop_listeners {
2050 if *drop_state_type == drag_state_type {
2051 let drag = cx
2052 .active_drag
2053 .take()
2054 .expect("checked for type drag state type above");
2055
2056 let mut can_drop = true;
2057 if let Some(predicate) = &can_drop_predicate {
2058 can_drop = predicate(drag.value.as_ref(), window, cx);
2059 }
2060
2061 if can_drop {
2062 listener(drag.value.as_ref(), window, cx);
2063 window.refresh();
2064 cx.stop_propagation();
2065 }
2066 }
2067 }
2068 }
2069 }
2070 }
2071 });
2072 }
2073
2074 if let Some(element_state) = element_state {
2075 if !click_listeners.is_empty() || drag_listener.is_some() {
2076 let pending_mouse_down = element_state
2077 .pending_mouse_down
2078 .get_or_insert_with(Default::default)
2079 .clone();
2080
2081 let clicked_state = element_state
2082 .clicked_state
2083 .get_or_insert_with(Default::default)
2084 .clone();
2085
2086 window.on_mouse_event({
2087 let pending_mouse_down = pending_mouse_down.clone();
2088 let hitbox = hitbox.clone();
2089 move |event: &MouseDownEvent, phase, window, _cx| {
2090 if phase == DispatchPhase::Bubble
2091 && event.button == MouseButton::Left
2092 && hitbox.is_hovered(window)
2093 {
2094 *pending_mouse_down.borrow_mut() = Some(event.clone());
2095 window.refresh();
2096 }
2097 }
2098 });
2099
2100 window.on_mouse_event({
2101 let pending_mouse_down = pending_mouse_down.clone();
2102 let hitbox = hitbox.clone();
2103 move |event: &MouseMoveEvent, phase, window, cx| {
2104 if phase == DispatchPhase::Capture {
2105 return;
2106 }
2107
2108 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2109 if let Some(mouse_down) = pending_mouse_down.clone() {
2110 if !cx.has_active_drag()
2111 && (event.position - mouse_down.position).magnitude()
2112 > DRAG_THRESHOLD
2113 {
2114 if let Some((drag_value, drag_listener)) = drag_listener.take() {
2115 *clicked_state.borrow_mut() = ElementClickedState::default();
2116 let cursor_offset = event.position - hitbox.origin;
2117 let drag = (drag_listener)(
2118 drag_value.as_ref(),
2119 cursor_offset,
2120 window,
2121 cx,
2122 );
2123 cx.active_drag = Some(AnyDrag {
2124 view: drag,
2125 value: drag_value,
2126 cursor_offset,
2127 cursor_style: drag_cursor_style,
2128 });
2129 pending_mouse_down.take();
2130 window.refresh();
2131 cx.stop_propagation();
2132 }
2133 }
2134 }
2135 }
2136 });
2137
2138 if is_focused {
2139 // Press enter, space to trigger click, when the element is focused.
2140 window.on_key_event({
2141 let click_listeners = click_listeners.clone();
2142 let hitbox = hitbox.clone();
2143 move |event: &KeyUpEvent, phase, window, cx| {
2144 if phase.bubble() && !window.default_prevented() {
2145 let stroke = &event.keystroke;
2146 let keyboard_button = if stroke.key.eq("enter") {
2147 Some(KeyboardButton::Enter)
2148 } else if stroke.key.eq("space") {
2149 Some(KeyboardButton::Space)
2150 } else {
2151 None
2152 };
2153
2154 if let Some(button) = keyboard_button
2155 && !stroke.modifiers.modified()
2156 {
2157 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
2158 button,
2159 bounds: hitbox.bounds,
2160 });
2161
2162 for listener in &click_listeners {
2163 listener(&click_event, window, cx);
2164 }
2165 }
2166 }
2167 }
2168 });
2169 }
2170
2171 window.on_mouse_event({
2172 let mut captured_mouse_down = None;
2173 let hitbox = hitbox.clone();
2174 move |event: &MouseUpEvent, phase, window, cx| match phase {
2175 // Clear the pending mouse down during the capture phase,
2176 // so that it happens even if another event handler stops
2177 // propagation.
2178 DispatchPhase::Capture => {
2179 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2180 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
2181 captured_mouse_down = pending_mouse_down.take();
2182 window.refresh();
2183 } else if pending_mouse_down.is_some() {
2184 // Clear the pending mouse down event (without firing click handlers)
2185 // if the hitbox is not being hovered.
2186 // This avoids dragging elements that changed their position
2187 // immediately after being clicked.
2188 // See https://github.com/zed-industries/zed/issues/24600 for more details
2189 pending_mouse_down.take();
2190 window.refresh();
2191 }
2192 }
2193 // Fire click handlers during the bubble phase.
2194 DispatchPhase::Bubble => {
2195 if let Some(mouse_down) = captured_mouse_down.take() {
2196 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
2197 down: mouse_down,
2198 up: event.clone(),
2199 });
2200 for listener in &click_listeners {
2201 listener(&mouse_click, window, cx);
2202 }
2203 }
2204 }
2205 }
2206 });
2207 }
2208
2209 if let Some(hover_listener) = self.hover_listener.take() {
2210 let hitbox = hitbox.clone();
2211 let was_hovered = element_state
2212 .hover_state
2213 .get_or_insert_with(Default::default)
2214 .clone();
2215 let has_mouse_down = element_state
2216 .pending_mouse_down
2217 .get_or_insert_with(Default::default)
2218 .clone();
2219
2220 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2221 if phase != DispatchPhase::Bubble {
2222 return;
2223 }
2224 let is_hovered = has_mouse_down.borrow().is_none()
2225 && !cx.has_active_drag()
2226 && hitbox.is_hovered(window);
2227 let mut was_hovered = was_hovered.borrow_mut();
2228
2229 if is_hovered != *was_hovered {
2230 *was_hovered = is_hovered;
2231 drop(was_hovered);
2232
2233 hover_listener(&is_hovered, window, cx);
2234 }
2235 });
2236 }
2237
2238 if let Some(tooltip_builder) = self.tooltip_builder.take() {
2239 let active_tooltip = element_state
2240 .active_tooltip
2241 .get_or_insert_with(Default::default)
2242 .clone();
2243 let pending_mouse_down = element_state
2244 .pending_mouse_down
2245 .get_or_insert_with(Default::default)
2246 .clone();
2247
2248 let tooltip_is_hoverable = tooltip_builder.hoverable;
2249 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
2250 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
2251 });
2252 // Use bounds instead of testing hitbox since this is called during prepaint.
2253 let check_is_hovered_during_prepaint = Rc::new({
2254 let pending_mouse_down = pending_mouse_down.clone();
2255 let source_bounds = hitbox.bounds;
2256 move |window: &Window| {
2257 pending_mouse_down.borrow().is_none()
2258 && source_bounds.contains(&window.mouse_position())
2259 }
2260 });
2261 let check_is_hovered = Rc::new({
2262 let hitbox = hitbox.clone();
2263 move |window: &Window| {
2264 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
2265 }
2266 });
2267 register_tooltip_mouse_handlers(
2268 &active_tooltip,
2269 self.tooltip_id,
2270 build_tooltip,
2271 check_is_hovered,
2272 check_is_hovered_during_prepaint,
2273 window,
2274 );
2275 }
2276
2277 let active_state = element_state
2278 .clicked_state
2279 .get_or_insert_with(Default::default)
2280 .clone();
2281 if active_state.borrow().is_clicked() {
2282 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
2283 if phase == DispatchPhase::Capture {
2284 *active_state.borrow_mut() = ElementClickedState::default();
2285 window.refresh();
2286 }
2287 });
2288 } else {
2289 let active_group_hitbox = self
2290 .group_active_style
2291 .as_ref()
2292 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
2293 let hitbox = hitbox.clone();
2294 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
2295 if phase == DispatchPhase::Bubble && !window.default_prevented() {
2296 let group_hovered = active_group_hitbox
2297 .map_or(false, |group_hitbox_id| group_hitbox_id.is_hovered(window));
2298 let element_hovered = hitbox.is_hovered(window);
2299 if group_hovered || element_hovered {
2300 *active_state.borrow_mut() = ElementClickedState {
2301 group: group_hovered,
2302 element: element_hovered,
2303 };
2304 window.refresh();
2305 }
2306 }
2307 });
2308 }
2309 }
2310 }
2311
2312 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
2313 let key_down_listeners = mem::take(&mut self.key_down_listeners);
2314 let key_up_listeners = mem::take(&mut self.key_up_listeners);
2315 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
2316 let action_listeners = mem::take(&mut self.action_listeners);
2317 if let Some(context) = self.key_context.clone() {
2318 window.set_key_context(context);
2319 }
2320
2321 for listener in key_down_listeners {
2322 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
2323 listener(event, phase, window, cx);
2324 })
2325 }
2326
2327 for listener in key_up_listeners {
2328 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
2329 listener(event, phase, window, cx);
2330 })
2331 }
2332
2333 for listener in modifiers_changed_listeners {
2334 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
2335 listener(event, window, cx);
2336 })
2337 }
2338
2339 for (action_type, listener) in action_listeners {
2340 window.on_action(action_type, listener)
2341 }
2342 }
2343
2344 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
2345 let group_hitbox = self
2346 .group_hover_style
2347 .as_ref()
2348 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
2349
2350 if let Some(group_hitbox) = group_hitbox {
2351 let was_hovered = group_hitbox.is_hovered(window);
2352 let current_view = window.current_view();
2353 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2354 let hovered = group_hitbox.is_hovered(window);
2355 if phase == DispatchPhase::Capture && hovered != was_hovered {
2356 cx.notify(current_view);
2357 }
2358 });
2359 }
2360 }
2361
2362 fn paint_scroll_listener(
2363 &self,
2364 hitbox: &Hitbox,
2365 style: &Style,
2366 window: &mut Window,
2367 _cx: &mut App,
2368 ) {
2369 if let Some(scroll_offset) = self.scroll_offset.clone() {
2370 let overflow = style.overflow;
2371 let allow_concurrent_scroll = style.allow_concurrent_scroll;
2372 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
2373 let line_height = window.line_height();
2374 let hitbox = hitbox.clone();
2375 let current_view = window.current_view();
2376 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2377 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
2378 let mut scroll_offset = scroll_offset.borrow_mut();
2379 let old_scroll_offset = *scroll_offset;
2380 let delta = event.delta.pixel_delta(line_height);
2381
2382 let mut delta_x = Pixels::ZERO;
2383 if overflow.x == Overflow::Scroll {
2384 if !delta.x.is_zero() {
2385 delta_x = delta.x;
2386 } else if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll {
2387 delta_x = delta.y;
2388 }
2389 }
2390 let mut delta_y = Pixels::ZERO;
2391 if overflow.y == Overflow::Scroll {
2392 if !delta.y.is_zero() {
2393 delta_y = delta.y;
2394 } else if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll {
2395 delta_y = delta.x;
2396 }
2397 }
2398 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
2399 if delta_x.abs() > delta_y.abs() {
2400 delta_y = Pixels::ZERO;
2401 } else {
2402 delta_x = Pixels::ZERO;
2403 }
2404 }
2405 scroll_offset.y += delta_y;
2406 scroll_offset.x += delta_x;
2407 if *scroll_offset != old_scroll_offset {
2408 cx.notify(current_view);
2409 }
2410 }
2411 });
2412 }
2413 }
2414
2415 /// Compute the visual style for this element, based on the current bounds and the element's state.
2416 pub fn compute_style(
2417 &self,
2418 global_id: Option<&GlobalElementId>,
2419 hitbox: Option<&Hitbox>,
2420 window: &mut Window,
2421 cx: &mut App,
2422 ) -> Style {
2423 window.with_optional_element_state(global_id, |element_state, window| {
2424 let mut element_state =
2425 element_state.map(|element_state| element_state.unwrap_or_default());
2426 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2427 (style, element_state)
2428 })
2429 }
2430
2431 /// Called from internal methods that have already called with_element_state.
2432 fn compute_style_internal(
2433 &self,
2434 hitbox: Option<&Hitbox>,
2435 element_state: Option<&mut InteractiveElementState>,
2436 window: &mut Window,
2437 cx: &mut App,
2438 ) -> Style {
2439 let mut style = Style::default();
2440 style.refine(&self.base_style);
2441
2442 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2443 if let Some(in_focus_style) = self.in_focus_style.as_ref() {
2444 if focus_handle.within_focused(window, cx) {
2445 style.refine(in_focus_style);
2446 }
2447 }
2448
2449 if let Some(focus_style) = self.focus_style.as_ref() {
2450 if focus_handle.is_focused(window) {
2451 style.refine(focus_style);
2452 }
2453 }
2454 }
2455
2456 if let Some(hitbox) = hitbox {
2457 if !cx.has_active_drag() {
2458 if let Some(group_hover) = self.group_hover_style.as_ref() {
2459 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2460 if group_hitbox_id.is_hovered(window) {
2461 style.refine(&group_hover.style);
2462 }
2463 }
2464 }
2465
2466 if let Some(hover_style) = self.hover_style.as_ref() {
2467 if hitbox.is_hovered(window) {
2468 style.refine(hover_style);
2469 }
2470 }
2471 }
2472
2473 if let Some(drag) = cx.active_drag.take() {
2474 let mut can_drop = true;
2475 if let Some(can_drop_predicate) = &self.can_drop_predicate {
2476 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
2477 }
2478
2479 if can_drop {
2480 for (state_type, group_drag_style) in &self.group_drag_over_styles {
2481 if let Some(group_hitbox_id) =
2482 GroupHitboxes::get(&group_drag_style.group, cx)
2483 {
2484 if *state_type == drag.value.as_ref().type_id()
2485 && group_hitbox_id.is_hovered(window)
2486 {
2487 style.refine(&group_drag_style.style);
2488 }
2489 }
2490 }
2491
2492 for (state_type, build_drag_over_style) in &self.drag_over_styles {
2493 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
2494 {
2495 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
2496 }
2497 }
2498 }
2499
2500 style.mouse_cursor = drag.cursor_style;
2501 cx.active_drag = Some(drag);
2502 }
2503 }
2504
2505 if let Some(element_state) = element_state {
2506 let clicked_state = element_state
2507 .clicked_state
2508 .get_or_insert_with(Default::default)
2509 .borrow();
2510 if clicked_state.group {
2511 if let Some(group) = self.group_active_style.as_ref() {
2512 style.refine(&group.style)
2513 }
2514 }
2515
2516 if let Some(active_style) = self.active_style.as_ref() {
2517 if clicked_state.element {
2518 style.refine(active_style)
2519 }
2520 }
2521 }
2522
2523 style
2524 }
2525}
2526
2527/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks
2528/// and scroll offsets.
2529#[derive(Default)]
2530pub struct InteractiveElementState {
2531 pub(crate) focus_handle: Option<FocusHandle>,
2532 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
2533 pub(crate) hover_state: Option<Rc<RefCell<bool>>>,
2534 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
2535 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2536 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
2537}
2538
2539/// Whether or not the element or a group that contains it is clicked by the mouse.
2540#[derive(Copy, Clone, Default, Eq, PartialEq)]
2541pub struct ElementClickedState {
2542 /// True if this element's group has been clicked, false otherwise
2543 pub group: bool,
2544
2545 /// True if this element has been clicked, false otherwise
2546 pub element: bool,
2547}
2548
2549impl ElementClickedState {
2550 fn is_clicked(&self) -> bool {
2551 self.group || self.element
2552 }
2553}
2554
2555pub(crate) enum ActiveTooltip {
2556 /// Currently delaying before showing the tooltip.
2557 WaitingForShow { _task: Task<()> },
2558 /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
2559 Visible {
2560 tooltip: AnyTooltip,
2561 is_hoverable: bool,
2562 },
2563 /// Tooltip is visible and hoverable, but the mouse is no longer hovering. Currently delaying
2564 /// before hiding it.
2565 WaitingForHide {
2566 tooltip: AnyTooltip,
2567 _task: Task<()>,
2568 },
2569}
2570
2571pub(crate) fn clear_active_tooltip(
2572 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2573 window: &mut Window,
2574) {
2575 match active_tooltip.borrow_mut().take() {
2576 None => {}
2577 Some(ActiveTooltip::WaitingForShow { .. }) => {}
2578 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
2579 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
2580 }
2581}
2582
2583pub(crate) fn clear_active_tooltip_if_not_hoverable(
2584 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2585 window: &mut Window,
2586) {
2587 let should_clear = match active_tooltip.borrow().as_ref() {
2588 None => false,
2589 Some(ActiveTooltip::WaitingForShow { .. }) => false,
2590 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
2591 Some(ActiveTooltip::WaitingForHide { .. }) => false,
2592 };
2593 if should_clear {
2594 active_tooltip.borrow_mut().take();
2595 window.refresh();
2596 }
2597}
2598
2599pub(crate) fn set_tooltip_on_window(
2600 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2601 window: &mut Window,
2602) -> Option<TooltipId> {
2603 let tooltip = match active_tooltip.borrow().as_ref() {
2604 None => return None,
2605 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
2606 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
2607 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
2608 };
2609 Some(window.set_tooltip(tooltip))
2610}
2611
2612pub(crate) fn register_tooltip_mouse_handlers(
2613 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2614 tooltip_id: Option<TooltipId>,
2615 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
2616 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
2617 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
2618 window: &mut Window,
2619) {
2620 window.on_mouse_event({
2621 let active_tooltip = active_tooltip.clone();
2622 let build_tooltip = build_tooltip.clone();
2623 let check_is_hovered = check_is_hovered.clone();
2624 move |_: &MouseMoveEvent, phase, window, cx| {
2625 handle_tooltip_mouse_move(
2626 &active_tooltip,
2627 &build_tooltip,
2628 &check_is_hovered,
2629 &check_is_hovered_during_prepaint,
2630 phase,
2631 window,
2632 cx,
2633 )
2634 }
2635 });
2636
2637 window.on_mouse_event({
2638 let active_tooltip = active_tooltip.clone();
2639 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
2640 if !tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(window)) {
2641 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
2642 }
2643 }
2644 });
2645
2646 window.on_mouse_event({
2647 let active_tooltip = active_tooltip.clone();
2648 move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
2649 if !tooltip_id.map_or(false, |tooltip_id| tooltip_id.is_hovered(window)) {
2650 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
2651 }
2652 }
2653 });
2654}
2655
2656/// Handles displaying tooltips when an element is hovered.
2657///
2658/// The mouse hovering logic also relies on being called from window prepaint in order to handle the
2659/// case where the element the tooltip is on is not rendered - in that case its mouse listeners are
2660/// also not registered. During window prepaint, the hitbox information is not available, so
2661/// `check_is_hovered_during_prepaint` is used which bases the check off of the absolute bounds of
2662/// the element.
2663///
2664/// TODO: There's a minor bug due to the use of absolute bounds while checking during prepaint - it
2665/// does not know if the hitbox is occluded. In the case where a tooltip gets displayed and then
2666/// gets occluded after display, it will stick around until the mouse exits the hover bounds.
2667fn handle_tooltip_mouse_move(
2668 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2669 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
2670 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
2671 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
2672 phase: DispatchPhase,
2673 window: &mut Window,
2674 cx: &mut App,
2675) {
2676 // Separates logic for what mutation should occur from applying it, to avoid overlapping
2677 // RefCell borrows.
2678 enum Action {
2679 None,
2680 CancelShow,
2681 ScheduleShow,
2682 }
2683
2684 let action = match active_tooltip.borrow().as_ref() {
2685 None => {
2686 let is_hovered = check_is_hovered(window);
2687 if is_hovered && phase.bubble() {
2688 Action::ScheduleShow
2689 } else {
2690 Action::None
2691 }
2692 }
2693 Some(ActiveTooltip::WaitingForShow { .. }) => {
2694 let is_hovered = check_is_hovered(window);
2695 if is_hovered {
2696 Action::None
2697 } else {
2698 Action::CancelShow
2699 }
2700 }
2701 // These are handled in check_visible_and_update.
2702 Some(ActiveTooltip::Visible { .. }) | Some(ActiveTooltip::WaitingForHide { .. }) => {
2703 Action::None
2704 }
2705 };
2706
2707 match action {
2708 Action::None => {}
2709 Action::CancelShow => {
2710 // Cancel waiting to show tooltip when it is no longer hovered.
2711 active_tooltip.borrow_mut().take();
2712 }
2713 Action::ScheduleShow => {
2714 let delayed_show_task = window.spawn(cx, {
2715 let active_tooltip = active_tooltip.clone();
2716 let build_tooltip = build_tooltip.clone();
2717 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
2718 async move |cx| {
2719 cx.background_executor().timer(TOOLTIP_SHOW_DELAY).await;
2720 cx.update(|window, cx| {
2721 let new_tooltip =
2722 build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
2723 let active_tooltip = active_tooltip.clone();
2724 ActiveTooltip::Visible {
2725 tooltip: AnyTooltip {
2726 view,
2727 mouse_position: window.mouse_position(),
2728 check_visible_and_update: Rc::new(
2729 move |tooltip_bounds, window, cx| {
2730 handle_tooltip_check_visible_and_update(
2731 &active_tooltip,
2732 tooltip_is_hoverable,
2733 &check_is_hovered_during_prepaint,
2734 tooltip_bounds,
2735 window,
2736 cx,
2737 )
2738 },
2739 ),
2740 },
2741 is_hoverable: tooltip_is_hoverable,
2742 }
2743 });
2744 *active_tooltip.borrow_mut() = new_tooltip;
2745 window.refresh();
2746 })
2747 .ok();
2748 }
2749 });
2750 active_tooltip
2751 .borrow_mut()
2752 .replace(ActiveTooltip::WaitingForShow {
2753 _task: delayed_show_task,
2754 });
2755 }
2756 }
2757}
2758
2759/// Returns a callback which will be called by window prepaint to update tooltip visibility. The
2760/// purpose of doing this logic here instead of the mouse move handler is that the mouse move
2761/// handler won't get called when the element is not painted (e.g. via use of `visible_on_hover`).
2762fn handle_tooltip_check_visible_and_update(
2763 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
2764 tooltip_is_hoverable: bool,
2765 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
2766 tooltip_bounds: Bounds<Pixels>,
2767 window: &mut Window,
2768 cx: &mut App,
2769) -> bool {
2770 // Separates logic for what mutation should occur from applying it, to avoid overlapping RefCell
2771 // borrows.
2772 enum Action {
2773 None,
2774 Hide,
2775 ScheduleHide(AnyTooltip),
2776 CancelHide(AnyTooltip),
2777 }
2778
2779 let is_hovered = check_is_hovered(window)
2780 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
2781 let action = match active_tooltip.borrow().as_ref() {
2782 Some(ActiveTooltip::Visible { tooltip, .. }) => {
2783 if is_hovered {
2784 Action::None
2785 } else {
2786 if tooltip_is_hoverable {
2787 Action::ScheduleHide(tooltip.clone())
2788 } else {
2789 Action::Hide
2790 }
2791 }
2792 }
2793 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
2794 if is_hovered {
2795 Action::CancelHide(tooltip.clone())
2796 } else {
2797 Action::None
2798 }
2799 }
2800 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
2801 };
2802
2803 match action {
2804 Action::None => {}
2805 Action::Hide => clear_active_tooltip(&active_tooltip, window),
2806 Action::ScheduleHide(tooltip) => {
2807 let delayed_hide_task = window.spawn(cx, {
2808 let active_tooltip = active_tooltip.clone();
2809 async move |cx| {
2810 cx.background_executor()
2811 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
2812 .await;
2813 if active_tooltip.borrow_mut().take().is_some() {
2814 cx.update(|window, _cx| window.refresh()).ok();
2815 }
2816 }
2817 });
2818 active_tooltip
2819 .borrow_mut()
2820 .replace(ActiveTooltip::WaitingForHide {
2821 tooltip,
2822 _task: delayed_hide_task,
2823 });
2824 }
2825 Action::CancelHide(tooltip) => {
2826 // Cancel waiting to hide tooltip when it becomes hovered.
2827 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
2828 tooltip,
2829 is_hoverable: true,
2830 });
2831 }
2832 }
2833
2834 active_tooltip.borrow().is_some()
2835}
2836
2837#[derive(Default)]
2838pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
2839
2840impl Global for GroupHitboxes {}
2841
2842impl GroupHitboxes {
2843 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
2844 cx.default_global::<Self>()
2845 .0
2846 .get(name)
2847 .and_then(|bounds_stack| bounds_stack.last())
2848 .cloned()
2849 }
2850
2851 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
2852 cx.default_global::<Self>()
2853 .0
2854 .entry(name)
2855 .or_default()
2856 .push(hitbox_id);
2857 }
2858
2859 pub fn pop(name: &SharedString, cx: &mut App) {
2860 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
2861 }
2862}
2863
2864/// A wrapper around an element that can store state, produced after assigning an ElementId.
2865pub struct Stateful<E> {
2866 pub(crate) element: E,
2867}
2868
2869impl<E> Styled for Stateful<E>
2870where
2871 E: Styled,
2872{
2873 fn style(&mut self) -> &mut StyleRefinement {
2874 self.element.style()
2875 }
2876}
2877
2878impl<E> StatefulInteractiveElement for Stateful<E>
2879where
2880 E: Element,
2881 Self: InteractiveElement,
2882{
2883}
2884
2885impl<E> InteractiveElement for Stateful<E>
2886where
2887 E: InteractiveElement,
2888{
2889 fn interactivity(&mut self) -> &mut Interactivity {
2890 self.element.interactivity()
2891 }
2892}
2893
2894impl<E> Element for Stateful<E>
2895where
2896 E: Element,
2897{
2898 type RequestLayoutState = E::RequestLayoutState;
2899 type PrepaintState = E::PrepaintState;
2900
2901 fn id(&self) -> Option<ElementId> {
2902 self.element.id()
2903 }
2904
2905 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
2906 self.element.source_location()
2907 }
2908
2909 fn request_layout(
2910 &mut self,
2911 id: Option<&GlobalElementId>,
2912 inspector_id: Option<&InspectorElementId>,
2913 window: &mut Window,
2914 cx: &mut App,
2915 ) -> (LayoutId, Self::RequestLayoutState) {
2916 self.element.request_layout(id, inspector_id, window, cx)
2917 }
2918
2919 fn prepaint(
2920 &mut self,
2921 id: Option<&GlobalElementId>,
2922 inspector_id: Option<&InspectorElementId>,
2923 bounds: Bounds<Pixels>,
2924 state: &mut Self::RequestLayoutState,
2925 window: &mut Window,
2926 cx: &mut App,
2927 ) -> E::PrepaintState {
2928 self.element
2929 .prepaint(id, inspector_id, bounds, state, window, cx)
2930 }
2931
2932 fn paint(
2933 &mut self,
2934 id: Option<&GlobalElementId>,
2935 inspector_id: Option<&InspectorElementId>,
2936 bounds: Bounds<Pixels>,
2937 request_layout: &mut Self::RequestLayoutState,
2938 prepaint: &mut Self::PrepaintState,
2939 window: &mut Window,
2940 cx: &mut App,
2941 ) {
2942 self.element.paint(
2943 id,
2944 inspector_id,
2945 bounds,
2946 request_layout,
2947 prepaint,
2948 window,
2949 cx,
2950 );
2951 }
2952}
2953
2954impl<E> IntoElement for Stateful<E>
2955where
2956 E: Element,
2957{
2958 type Element = Self;
2959
2960 fn into_element(self) -> Self::Element {
2961 self
2962 }
2963}
2964
2965impl<E> ParentElement for Stateful<E>
2966where
2967 E: ParentElement,
2968{
2969 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
2970 self.element.extend(elements)
2971 }
2972}
2973
2974/// Represents an element that can be scrolled *to* in its parent element.
2975///
2976/// Contrary to [ScrollHandle::scroll_to_item], an anchored element does not have to be an immediate child of the parent.
2977#[derive(Clone)]
2978pub struct ScrollAnchor {
2979 handle: ScrollHandle,
2980 last_origin: Rc<RefCell<Point<Pixels>>>,
2981}
2982
2983impl ScrollAnchor {
2984 /// Creates a [ScrollAnchor] associated with a given [ScrollHandle].
2985 pub fn for_handle(handle: ScrollHandle) -> Self {
2986 Self {
2987 handle,
2988 last_origin: Default::default(),
2989 }
2990 }
2991 /// Request scroll to this item on the next frame.
2992 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
2993 let this = self.clone();
2994
2995 window.on_next_frame(move |_, _| {
2996 let viewport_bounds = this.handle.bounds();
2997 let self_bounds = *this.last_origin.borrow();
2998 this.handle.set_offset(viewport_bounds.origin - self_bounds);
2999 });
3000 }
3001}
3002
3003#[derive(Default, Debug)]
3004struct ScrollHandleState {
3005 offset: Rc<RefCell<Point<Pixels>>>,
3006 bounds: Bounds<Pixels>,
3007 max_offset: Size<Pixels>,
3008 child_bounds: Vec<Bounds<Pixels>>,
3009 scroll_to_bottom: bool,
3010 overflow: Point<Overflow>,
3011}
3012
3013/// A handle to the scrollable aspects of an element.
3014/// Used for accessing scroll state, like the current scroll offset,
3015/// and for mutating the scroll state, like scrolling to a specific child.
3016#[derive(Clone, Debug)]
3017pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
3018
3019impl Default for ScrollHandle {
3020 fn default() -> Self {
3021 Self::new()
3022 }
3023}
3024
3025impl ScrollHandle {
3026 /// Construct a new scroll handle.
3027 pub fn new() -> Self {
3028 Self(Rc::default())
3029 }
3030
3031 /// Get the current scroll offset.
3032 pub fn offset(&self) -> Point<Pixels> {
3033 *self.0.borrow().offset.borrow()
3034 }
3035
3036 /// Get the maximum scroll offset.
3037 pub fn max_offset(&self) -> Size<Pixels> {
3038 self.0.borrow().max_offset
3039 }
3040
3041 /// Get the top child that's scrolled into view.
3042 pub fn top_item(&self) -> usize {
3043 let state = self.0.borrow();
3044 let top = state.bounds.top() - state.offset.borrow().y;
3045
3046 match state.child_bounds.binary_search_by(|bounds| {
3047 if top < bounds.top() {
3048 Ordering::Greater
3049 } else if top > bounds.bottom() {
3050 Ordering::Less
3051 } else {
3052 Ordering::Equal
3053 }
3054 }) {
3055 Ok(ix) => ix,
3056 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
3057 }
3058 }
3059
3060 /// Return the bounds into which this child is painted
3061 pub fn bounds(&self) -> Bounds<Pixels> {
3062 self.0.borrow().bounds
3063 }
3064
3065 /// Get the bounds for a specific child.
3066 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
3067 self.0.borrow().child_bounds.get(ix).cloned()
3068 }
3069
3070 /// scroll_to_item scrolls the minimal amount to ensure that the child is
3071 /// fully visible
3072 pub fn scroll_to_item(&self, ix: usize) {
3073 let state = self.0.borrow();
3074
3075 let Some(bounds) = state.child_bounds.get(ix) else {
3076 return;
3077 };
3078
3079 let mut scroll_offset = state.offset.borrow_mut();
3080
3081 if state.overflow.y == Overflow::Scroll {
3082 if bounds.top() + scroll_offset.y < state.bounds.top() {
3083 scroll_offset.y = state.bounds.top() - bounds.top();
3084 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
3085 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
3086 }
3087 }
3088
3089 if state.overflow.x == Overflow::Scroll {
3090 if bounds.left() + scroll_offset.x < state.bounds.left() {
3091 scroll_offset.x = state.bounds.left() - bounds.left();
3092 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
3093 scroll_offset.x = state.bounds.right() - bounds.right();
3094 }
3095 }
3096 }
3097
3098 /// Scrolls to the bottom.
3099 pub fn scroll_to_bottom(&self) {
3100 let mut state = self.0.borrow_mut();
3101 state.scroll_to_bottom = true;
3102 }
3103
3104 /// Set the offset explicitly. The offset is the distance from the top left of the
3105 /// parent container to the top left of the first child.
3106 /// As you scroll further down the offset becomes more negative.
3107 pub fn set_offset(&self, mut position: Point<Pixels>) {
3108 let state = self.0.borrow();
3109 *state.offset.borrow_mut() = position;
3110 }
3111
3112 /// Get the logical scroll top, based on a child index and a pixel offset.
3113 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
3114 let ix = self.top_item();
3115 let state = self.0.borrow();
3116
3117 if let Some(child_bounds) = state.child_bounds.get(ix) {
3118 (
3119 ix,
3120 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
3121 )
3122 } else {
3123 (ix, px(0.))
3124 }
3125 }
3126
3127 /// Get the count of children for scrollable item.
3128 pub fn children_count(&self) -> usize {
3129 self.0.borrow().child_bounds.len()
3130 }
3131}