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