BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-pre / src / elements / div.rs

div.rs

div.rs 220.2 KiB Download Raw
1//! Div is the central, reusable element that most GPUI trees will be built from.
2//! It functions as a container for other elements, and provides a number of
3//! useful features for laying out and styling its children as well as binding
4//! mouse events and action handlers. It is meant to be similar to the HTML `<div>`
5//! element, but for GPUI.
6//!
7//! # Build your own div
8//!
9//! GPUI does not directly provide APIs for stateful, multi step events like `click`
10//! and `drag`. We want GPUI users to be able to build their own abstractions for
11//! their own needs. However, as a UI framework, we're also obliged to provide some
12//! building blocks to make the process of building your own elements easier.
13//! For this we have the [`Interactivity`] and the [`StyleRefinement`] structs, as well
14//! as several associated traits. Together, these provide the full suite of Dom-like events
15//! and Tailwind-like styling that you can use to build your own custom elements. Div is
16//! constructed by combining these two systems into an all-in-one element.
17
18use crate::{
19 Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, Bounds, ClickEvent, DispatchPhase,
20 Display, Element, ElementId, Entity, EntityId, ExternalDragPayload, ExternalDragPayloadSource,
21 FileDropEvent, FocusHandle, Global, GlobalElementId, Hitbox, HitboxBehavior, HitboxId,
22 InspectorElementId, IntoElement, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, KeyboardButton,
23 KeyboardClickEvent, LayoutId, LongPressEvent, ModifiersChangedEvent, MouseButton,
24 MouseClickEvent, MouseDownEvent, MouseExitEvent, MouseMoveEvent, MousePressureEvent,
25 MouseUpEvent, OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels, Point, Render,
26 ScrollWheelEvent, SharedString, Size, Style, StyleRefinement, Styled, Task, TooltipId,
27 TouchPhase, Visibility, Window, WindowControlArea, point, px, size,
28};
29use collections::HashMap;
30use gpui_util::ResultExt;
31use refineable::Refineable;
32use smallvec::SmallVec;
33use std::{
34 any::{Any, TypeId},
35 cell::{Cell, RefCell},
36 cmp::Ordering,
37 fmt::Debug,
38 marker::PhantomData,
39 mem,
40 rc::Rc,
41 sync::Arc,
42 time::Duration,
43};
44
45use super::ImageCacheProvider;
46
47#[cfg(feature = "stacker")]
48type StackSafe<T> = stacksafe::StackSafe<T>;
49#[cfg(not(feature = "stacker"))]
50type StackSafe<T> = T;
51
52const DRAG_THRESHOLD: f64 = 2.;
53const DEFAULT_TOOLTIP_SHOW_DELAY: Duration = Duration::from_millis(500);
54const HOVERABLE_TOOLTIP_HIDE_DELAY: Duration = Duration::from_millis(500);
55
56/// The styling information for a given group.
57pub struct GroupStyle {
58 /// The identifier for this group.
59 pub group: SharedString,
60
61 /// The specific style refinement that this group would apply
62 /// to its children.
63 pub style: Box<StyleRefinement>,
64}
65
66/// An event for when a drag is moving over this element, with the given state type.
67pub struct DragMoveEvent<T> {
68 /// The mouse move event that triggered this drag move event.
69 pub event: MouseMoveEvent,
70
71 /// The bounds of this element.
72 pub bounds: Bounds<Pixels>,
73 drag: PhantomData<T>,
74 dragged_item: Arc<dyn Any>,
75}
76
77impl<T: 'static> DragMoveEvent<T> {
78 /// Returns the drag state for this event.
79 pub fn drag<'b>(&self, cx: &'b App) -> &'b T {
80 cx.active_drag
81 .as_ref()
82 .and_then(|drag| drag.value.downcast_ref::<T>())
83 .expect("DragMoveEvent is only valid when the stored active drag is of the same type.")
84 }
85
86 /// An item that is about to be dropped.
87 pub fn dragged_item(&self) -> &dyn Any {
88 self.dragged_item.as_ref()
89 }
90}
91
92impl Interactivity {
93 /// Create an `Interactivity`, capturing the caller location in debug mode.
94 #[cfg(any(feature = "inspector", debug_assertions))]
95 #[track_caller]
96 pub fn new() -> Interactivity {
97 Interactivity {
98 source_location: Some(core::panic::Location::caller()),
99 ..Default::default()
100 }
101 }
102
103 /// Create an `Interactivity`, capturing the caller location in debug mode.
104 #[cfg(not(any(feature = "inspector", debug_assertions)))]
105 pub fn new() -> Interactivity {
106 Interactivity::default()
107 }
108
109 /// Gets the source location of construction. Returns `None` when not in debug mode.
110 pub fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
111 #[cfg(any(feature = "inspector", debug_assertions))]
112 {
113 self.source_location
114 }
115
116 #[cfg(not(any(feature = "inspector", debug_assertions)))]
117 {
118 None
119 }
120 }
121
122 /// Bind the given callback to the mouse down event for the given mouse button, during the bubble phase.
123 /// The imperative API equivalent of [`InteractiveElement::on_mouse_down`].
124 ///
125 /// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
126 pub fn on_mouse_down(
127 &mut self,
128 button: MouseButton,
129 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
130 ) {
131 self.mouse_down_listeners
132 .push(Box::new(move |event, phase, hitbox, window, cx| {
133 if phase == DispatchPhase::Bubble
134 && event.button == button
135 && hitbox.is_hovered(window)
136 {
137 (listener)(event, window, cx)
138 }
139 }));
140 }
141
142 /// Bind the given callback to the mouse down event for any button, during the capture phase.
143 /// The imperative API equivalent of [`InteractiveElement::capture_any_mouse_down`].
144 ///
145 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
146 pub fn capture_any_mouse_down(
147 &mut self,
148 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
149 ) {
150 self.mouse_down_listeners
151 .push(Box::new(move |event, phase, hitbox, window, cx| {
152 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
153 (listener)(event, window, cx)
154 }
155 }));
156 }
157
158 /// Bind the given callback to the mouse down event for any button, during the bubble phase.
159 /// The imperative API equivalent to [`InteractiveElement::on_any_mouse_down`].
160 ///
161 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
162 pub fn on_any_mouse_down(
163 &mut self,
164 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
165 ) {
166 self.mouse_down_listeners
167 .push(Box::new(move |event, phase, hitbox, window, cx| {
168 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
169 (listener)(event, window, cx)
170 }
171 }));
172 }
173
174 /// Bind the given callback to the mouse pressure event, during the bubble phase
175 /// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
176 ///
177 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
178 pub fn on_mouse_pressure(
179 &mut self,
180 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
181 ) {
182 self.mouse_pressure_listeners
183 .push(Box::new(move |event, phase, hitbox, window, cx| {
184 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
185 (listener)(event, window, cx)
186 }
187 }));
188 }
189
190 /// Bind the given callback to the mouse pressure event, during the capture phase
191 /// the imperative API equivalent to [`InteractiveElement::on_mouse_pressure`].
192 ///
193 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
194 pub fn capture_mouse_pressure(
195 &mut self,
196 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
197 ) {
198 self.mouse_pressure_listeners
199 .push(Box::new(move |event, phase, hitbox, window, cx| {
200 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
201 (listener)(event, window, cx)
202 }
203 }));
204 }
205
206 /// Bind the given callback to the mouse up event for the given button, during the bubble phase.
207 /// The imperative API equivalent to [`InteractiveElement::on_mouse_up`].
208 ///
209 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
210 pub fn on_mouse_up(
211 &mut self,
212 button: MouseButton,
213 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
214 ) {
215 self.mouse_up_listeners
216 .push(Box::new(move |event, phase, hitbox, window, cx| {
217 if phase == DispatchPhase::Bubble
218 && event.button == button
219 && hitbox.is_hovered(window)
220 {
221 (listener)(event, window, cx)
222 }
223 }));
224 }
225
226 /// Bind the given callback to the mouse up event for any button, during the capture phase.
227 /// The imperative API equivalent to [`InteractiveElement::capture_any_mouse_up`].
228 ///
229 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
230 pub fn capture_any_mouse_up(
231 &mut self,
232 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
233 ) {
234 self.mouse_up_listeners
235 .push(Box::new(move |event, phase, hitbox, window, cx| {
236 if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
237 (listener)(event, window, cx)
238 }
239 }));
240 }
241
242 /// Bind the given callback to the mouse up event for any button, during the bubble phase.
243 /// The imperative API equivalent to [`Interactivity::on_any_mouse_up`].
244 ///
245 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
246 pub fn on_any_mouse_up(
247 &mut self,
248 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
249 ) {
250 self.mouse_up_listeners
251 .push(Box::new(move |event, phase, hitbox, window, cx| {
252 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
253 (listener)(event, window, cx)
254 }
255 }));
256 }
257
258 /// Bind the given callback to the mouse down event, on any button, during the capture phase,
259 /// when the mouse is outside of the bounds of this element.
260 /// The imperative API equivalent to [`InteractiveElement::on_mouse_down_out`].
261 ///
262 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
263 pub fn on_mouse_down_out(
264 &mut self,
265 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
266 ) {
267 self.mouse_down_listeners
268 .push(Box::new(move |event, phase, hitbox, window, cx| {
269 if phase == DispatchPhase::Capture
270 && !window.has_active_prompt()
271 && !hitbox.contains(&window.mouse_position())
272 {
273 (listener)(event, window, cx)
274 }
275 }));
276 }
277
278 /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
279 /// when the mouse is outside of the bounds of this element.
280 /// The imperative API equivalent to [`InteractiveElement::on_mouse_up_out`].
281 ///
282 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
283 pub fn on_mouse_up_out(
284 &mut self,
285 button: MouseButton,
286 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
287 ) {
288 self.mouse_up_listeners
289 .push(Box::new(move |event, phase, hitbox, window, cx| {
290 if phase == DispatchPhase::Capture
291 && event.button == button
292 && !hitbox.is_hovered(window)
293 {
294 (listener)(event, window, cx);
295 }
296 }));
297 }
298
299 /// Bind the given callback to the mouse move event, during the bubble phase.
300 /// The imperative API equivalent to [`InteractiveElement::on_mouse_move`].
301 ///
302 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
303 pub fn on_mouse_move(
304 &mut self,
305 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
306 ) {
307 self.mouse_move_listeners
308 .push(Box::new(move |event, phase, hitbox, window, cx| {
309 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
310 (listener)(event, window, cx);
311 }
312 }));
313 }
314
315 /// Bind the given callback to the mouse exit event, during the bubble phase.
316 /// The imperative API equivalent to [`InteractiveElement::on_mouse_exit`].
317 ///
318 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
319 pub fn on_mouse_exit(
320 &mut self,
321 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
322 ) {
323 self.mouse_exit_listeners
324 .push(Box::new(move |event, phase, hitbox, window, cx| {
325 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
326 (listener)(event, window, cx);
327 }
328 }));
329 }
330
331 /// Bind the given callback to [`FileDropEvent::Exited`] when a platform file drag
332 /// leaves this element's window while the element is hovered.
333 ///
334 /// This is a window-local exit event, not notification that the platform drag session ended.
335 /// The imperative API equivalent to [`InteractiveElement::on_file_drop_exit`].
336 ///
337 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
338 pub fn on_file_drop_exit(
339 &mut self,
340 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
341 ) {
342 self.file_drop_exit_listeners
343 .push(Box::new(move |event, phase, hitbox, window, cx| {
344 if phase == DispatchPhase::Bubble
345 && matches!(event, FileDropEvent::Exited)
346 && hitbox.id.is_hovered_ignoring_last_input(window)
347 {
348 (listener)(event, window, cx);
349 }
350 }));
351 }
352
353 /// Bind the given callback to the mouse drag event of the given type. Note that this
354 /// will be called for all move events, inside or outside of this element, as long as the
355 /// drag was started with this element under the mouse. Useful for implementing draggable
356 /// UIs that don't conform to a drag and drop style interaction, like resizing.
357 /// The imperative API equivalent to [`InteractiveElement::on_drag_move`].
358 ///
359 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
360 pub fn on_drag_move<T>(
361 &mut self,
362 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
363 ) where
364 T: 'static,
365 {
366 self.mouse_move_listeners
367 .push(Box::new(move |event, phase, hitbox, window, cx| {
368 if phase == DispatchPhase::Capture
369 && let Some(drag) = &cx.active_drag
370 && drag.value.as_ref().type_id() == TypeId::of::<T>()
371 {
372 (listener)(
373 &DragMoveEvent {
374 event: event.clone(),
375 bounds: hitbox.bounds,
376 drag: PhantomData,
377 dragged_item: Arc::clone(&drag.value),
378 },
379 window,
380 cx,
381 );
382 }
383 }));
384 }
385
386 /// Bind the given callback to scroll wheel events during the bubble phase.
387 /// The imperative API equivalent to [`InteractiveElement::on_scroll_wheel`].
388 ///
389 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
390 pub fn on_scroll_wheel(
391 &mut self,
392 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
393 ) {
394 self.scroll_wheel_listeners
395 .push(Box::new(move |event, phase, hitbox, window, cx| {
396 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
397 (listener)(event, window, cx);
398 }
399 }));
400 }
401
402 /// Bind the given callback to pinch gesture events during the bubble phase.
403 ///
404 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
405 pub fn on_pinch(&mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) {
406 self.pinch_listeners
407 .push(Box::new(move |event, phase, hitbox, window, cx| {
408 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
409 (listener)(event, window, cx);
410 }
411 }));
412 }
413
414 /// Bind the given callback to pinch gesture events during the capture phase.
415 ///
416 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
417 pub fn capture_pinch(
418 &mut self,
419 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
420 ) {
421 self.pinch_listeners
422 .push(Box::new(move |event, phase, _hitbox, window, cx| {
423 if phase == DispatchPhase::Capture {
424 (listener)(event, window, cx);
425 } else {
426 cx.propagate();
427 }
428 }));
429 }
430
431 /// Bind the given callback to an action dispatch during the capture phase.
432 /// The imperative API equivalent to [`InteractiveElement::capture_action`].
433 ///
434 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
435 pub fn capture_action<A: Action>(
436 &mut self,
437 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
438 ) {
439 self.action_listeners.push((
440 TypeId::of::<A>(),
441 Box::new(move |action, phase, window, cx| {
442 let action = action.downcast_ref().unwrap();
443 if phase == DispatchPhase::Capture {
444 (listener)(action, window, cx)
445 } else {
446 cx.propagate();
447 }
448 }),
449 ));
450 }
451
452 /// Bind the given callback to an action dispatch during the bubble phase.
453 /// The imperative API equivalent to [`InteractiveElement::on_action`].
454 ///
455 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
456 #[track_caller]
457 #[inline(always)]
458 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Window, &mut App) + 'static) {
459 self.action_listeners.push((
460 TypeId::of::<A>(),
461 Box::new(move |action, phase, window, cx| {
462 let action = action.downcast_ref().unwrap();
463 if phase == DispatchPhase::Bubble {
464 (listener)(action, window, cx)
465 }
466 }),
467 ));
468 }
469
470 /// Bind the given callback to an action dispatch, based on a dynamic action parameter
471 /// instead of a type parameter. Useful for component libraries that want to expose
472 /// action bindings to their users.
473 /// The imperative API equivalent to [`InteractiveElement::on_boxed_action`].
474 ///
475 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
476 pub fn on_boxed_action(
477 &mut self,
478 action: &dyn Action,
479 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
480 ) {
481 let action = action.boxed_clone();
482 self.action_listeners.push((
483 (*action).type_id(),
484 Box::new(move |_, phase, window, cx| {
485 if phase == DispatchPhase::Bubble {
486 (listener)(&*action, window, cx)
487 }
488 }),
489 ));
490 }
491
492 /// Bind the given callback to key down events during the bubble phase.
493 /// The imperative API equivalent to [`InteractiveElement::on_key_down`].
494 ///
495 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
496 pub fn on_key_down(
497 &mut self,
498 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
499 ) {
500 self.key_down_listeners
501 .push(Box::new(move |event, phase, window, cx| {
502 if phase == DispatchPhase::Bubble {
503 (listener)(event, window, cx)
504 }
505 }));
506 }
507
508 /// Bind the given callback to key down events during the capture phase.
509 /// The imperative API equivalent to [`InteractiveElement::capture_key_down`].
510 ///
511 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
512 pub fn capture_key_down(
513 &mut self,
514 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
515 ) {
516 self.key_down_listeners
517 .push(Box::new(move |event, phase, window, cx| {
518 if phase == DispatchPhase::Capture {
519 listener(event, window, cx)
520 }
521 }));
522 }
523
524 /// Bind the given callback to key up events during the bubble phase.
525 /// The imperative API equivalent to [`InteractiveElement::on_key_up`].
526 ///
527 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
528 pub fn on_key_up(&mut self, listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static) {
529 self.key_up_listeners
530 .push(Box::new(move |event, phase, window, cx| {
531 if phase == DispatchPhase::Bubble {
532 listener(event, window, cx)
533 }
534 }));
535 }
536
537 /// Bind the given callback to key up events during the capture phase.
538 /// The imperative API equivalent to [`InteractiveElement::on_key_up`].
539 ///
540 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
541 pub fn capture_key_up(
542 &mut self,
543 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
544 ) {
545 self.key_up_listeners
546 .push(Box::new(move |event, phase, window, cx| {
547 if phase == DispatchPhase::Capture {
548 listener(event, window, cx)
549 }
550 }));
551 }
552
553 /// Bind the given callback to modifiers changing events.
554 /// The imperative API equivalent to [`InteractiveElement::on_modifiers_changed`].
555 ///
556 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
557 pub fn on_modifiers_changed(
558 &mut self,
559 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
560 ) {
561 self.modifiers_changed_listeners.push(Box::new(listener));
562 }
563
564 /// Bind the given callback to drop events of the given type, whether or not the drag started on this element.
565 /// The imperative API equivalent to [`InteractiveElement::on_drop`].
566 ///
567 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
568 pub fn on_drop<T: 'static>(&mut self, listener: impl Fn(&T, &mut Window, &mut App) + 'static) {
569 self.drop_listeners.push((
570 TypeId::of::<T>(),
571 Box::new(move |dragged_value, window, cx| {
572 listener(dragged_value.downcast_ref().unwrap(), window, cx);
573 }),
574 ));
575 }
576
577 /// Use the given predicate to determine whether or not a drop event should be dispatched to this element.
578 /// The imperative API equivalent to [`InteractiveElement::can_drop`].
579 pub fn can_drop(
580 &mut self,
581 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
582 ) {
583 self.can_drop_predicate = Some(Box::new(predicate));
584 }
585
586 /// Bind the given callback to click events of this element.
587 /// The imperative API equivalent to [`StatefulInteractiveElement::on_click`].
588 ///
589 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
590 #[inline(always)]
591 pub fn on_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
592 where
593 Self: Sized,
594 {
595 self.click_listeners.push(Rc::new(listener));
596 }
597
598 /// Bind the given callback to non-primary click events of this element.
599 /// The imperative API equivalent to [`StatefulInteractiveElement::on_aux_click`].
600 ///
601 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
602 pub fn on_aux_click(&mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)
603 where
604 Self: Sized,
605 {
606 self.aux_click_listeners.push(Rc::new(listener));
607 }
608
609 /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
610 /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
611 /// the [`Self::on_drag_move`] API.
612 /// The imperative API equivalent to [`StatefulInteractiveElement::on_drag`].
613 ///
614 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
615 pub fn on_drag<T, W>(
616 &mut self,
617 value: T,
618 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
619 ) where
620 Self: Sized,
621 T: 'static,
622 W: 'static + Render,
623 {
624 debug_assert!(
625 self.drag_listener.is_none(),
626 "calling on_drag more than once on the same element is not supported"
627 );
628 self.drag_listener = Some(DragListener {
629 value: Arc::new(value),
630 render: Box::new(move |value, offset, window, cx| {
631 constructor(value.downcast_ref().unwrap(), offset, window, cx).into()
632 }),
633 external_payload: None,
634 });
635 }
636
637 /// Registers a callback resolving a payload to offer the platform if a drag started by this
638 /// element leaves the window. It is invoked at most once per drag gesture, when the pointer
639 /// exits the viewport. Must be called after [`Self::on_drag`], with the same dragged value
640 /// type `T`.
641 pub fn external_drag_payload<T>(
642 &mut self,
643 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
644 ) where
645 Self: Sized,
646 T: 'static,
647 {
648 let Some(drag_listener) = self.drag_listener.as_mut() else {
649 debug_assert!(false, "external_drag_payload must be called after on_drag");
650 return;
651 };
652 debug_assert!(
653 drag_listener.value.as_ref().type_id() == TypeId::of::<T>(),
654 "external_drag_payload must use the same dragged value type as on_drag"
655 );
656 debug_assert!(
657 drag_listener.external_payload.is_none(),
658 "calling external_drag_payload more than once on the same element is not supported"
659 );
660 drag_listener.external_payload = Some(Box::new(move |value, window, cx| {
661 resolver(value.downcast_ref::<T>()?, window, cx)
662 }));
663 }
664
665 /// Bind the given callback on the hover start and end events of this element. Note that the boolean
666 /// passed to the callback is true when the hover starts and false when it ends.
667 /// Transitions caused by layout changes under a stationary mouse also invoke the callback.
668 ///
669 /// By default, keyboard input suppresses hover until the next mouse move, mouse down, or touch. Set
670 /// [`HoverListenerMode::InputModalityIndependent`] with [`Self::hover_listener_mode`] to
671 /// continue hit-testing hover after keyboard input.
672 /// The imperative API equivalent to [`StatefulInteractiveElement::on_hover`].
673 ///
674 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
675 pub fn on_hover(&mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static)
676 where
677 Self: Sized,
678 {
679 debug_assert!(
680 self.hover_listener.is_none(),
681 "calling on_hover more than once on the same element is not supported"
682 );
683 self.hover_listener = Some(Box::new(listener));
684 }
685
686 /// Sets how [`Self::on_hover`] responds to key presses while the mouse is stationary.
687 /// This affects only the hover listener, not hover styles or tooltips. The imperative API
688 /// equivalent to [`StatefulInteractiveElement::hover_listener_mode`].
689 pub fn hover_listener_mode(&mut self, mode: HoverListenerMode)
690 where
691 Self: Sized,
692 {
693 self.hover_listener_mode = mode;
694 }
695
696 /// Constructs a tooltip when the element is hovered or long-pressed.
697 /// The imperative API equivalent to [`StatefulInteractiveElement::tooltip`].
698 pub fn tooltip(&mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static)
699 where
700 Self: Sized,
701 {
702 debug_assert!(
703 self.tooltip_builder.is_none(),
704 "calling tooltip more than once on the same element is not supported"
705 );
706 self.tooltip_builder = Some(TooltipBuilder {
707 build: Rc::new(build_tooltip),
708 hoverable: false,
709 });
710 }
711
712 /// Constructs a tooltip when the element is hovered or long-pressed.
713 /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
714 /// the tooltip. The imperative API equivalent to [`StatefulInteractiveElement::hoverable_tooltip`].
715 pub fn hoverable_tooltip(
716 &mut self,
717 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
718 ) where
719 Self: Sized,
720 {
721 debug_assert!(
722 self.tooltip_builder.is_none(),
723 "calling tooltip more than once on the same element is not supported"
724 );
725 self.tooltip_builder = Some(TooltipBuilder {
726 build: Rc::new(build_tooltip),
727 hoverable: true,
728 });
729 }
730
731 /// Sets the delay before this element's tooltip is shown on hover.
732 ///
733 /// Touch long presses show the tooltip immediately once the gesture is recognized.
734 /// The imperative API equivalent to [`StatefulInteractiveElement::tooltip_show_delay`].
735 pub fn tooltip_show_delay(&mut self, delay: Duration) {
736 self.tooltip_show_delay = Some(delay);
737 }
738
739 /// Block the mouse from all interactions with elements behind this element's hitbox. Typically
740 /// `block_mouse_except_scroll` should be preferred.
741 ///
742 /// The imperative API equivalent to [`InteractiveElement::occlude`]
743 pub fn occlude_mouse(&mut self) {
744 self.hitbox_behavior = HitboxBehavior::BlockMouse;
745 }
746
747 /// Set the bounds of this element as a window control area for the platform window.
748 /// The imperative API equivalent to [`InteractiveElement::window_control_area`]
749 pub fn window_control_area(&mut self, area: WindowControlArea) {
750 self.window_control = Some(area);
751 }
752
753 /// Block non-scroll mouse interactions with elements behind this element's hitbox.
754 /// The imperative API equivalent to [`InteractiveElement::block_mouse_except_scroll`].
755 ///
756 /// See [`Hitbox::is_hovered`] for details.
757 pub fn block_mouse_except_scroll(&mut self) {
758 self.hitbox_behavior = HitboxBehavior::BlockMouseExceptScroll;
759 }
760
761 fn has_pinch_listeners(&self) -> bool {
762 !self.pinch_listeners.is_empty()
763 }
764}
765
766/// A trait for elements that want to use the standard GPUI event handlers that don't
767/// require any state.
768pub trait InteractiveElement: Sized {
769 /// Retrieve the interactivity state associated with this element
770 fn interactivity(&mut self) -> &mut Interactivity;
771
772 /// Assign this element to a group of elements that can be styled together
773 fn group(mut self, group: impl Into<SharedString>) -> Self {
774 self.interactivity().group = Some(group.into());
775 self
776 }
777
778 /// Assign this element an ID, so that it can be used with interactivity
779 fn id(mut self, id: impl Into<ElementId>) -> Stateful<Self> {
780 self.interactivity().element_id = Some(id.into());
781
782 Stateful { element: self }
783 }
784
785 /// Track the focus state of the given focus handle on this element.
786 /// If the focus handle is focused by the application, this element will
787 /// apply its focused styles.
788 fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
789 self.interactivity().focusable = true;
790 self.interactivity().tracked_focus_handle = Some(focus_handle.clone());
791 self
792 }
793
794 /// Set whether this element is a tab stop.
795 ///
796 /// When false, the element remains in tab-index order but cannot be reached via keyboard navigation.
797 /// Useful for container elements: focus the container, then call `window.focus_next(cx)` to focus
798 /// the first tab stop inside it while having the container element itself be unreachable via the keyboard.
799 /// Should only be used with `tab_index`.
800 fn tab_stop(mut self, tab_stop: bool) -> Self {
801 self.interactivity().tab_stop = tab_stop;
802 self
803 }
804
805 /// Set index of the tab stop order, and set this node as a tab stop.
806 /// This will default the element to being a tab stop. See [`Self::tab_stop`] for more information.
807 /// This should only be used in conjunction with `tab_group`
808 /// in order to not interfere with the tab index of other elements.
809 fn tab_index(mut self, index: isize) -> Self {
810 self.interactivity().focusable = true;
811 self.interactivity().tab_index = Some(index);
812 self.interactivity().tab_stop = true;
813 self
814 }
815
816 /// Designate this div as a "tab group". Tab groups have their own location in the tab-index order,
817 /// but for children of the tab group, the tab index is reset to 0. This can be useful for swapping
818 /// the order of tab stops within the group, without having to renumber all the tab stops in the whole
819 /// application.
820 fn tab_group(mut self) -> Self {
821 self.interactivity().tab_group = true;
822 if self.interactivity().tab_index.is_none() {
823 self.interactivity().tab_index = Some(0);
824 }
825 self
826 }
827
828 /// Set the keymap context for this element. This will be used to determine
829 /// which action to dispatch from the keymap.
830 fn key_context<C, E>(mut self, key_context: C) -> Self
831 where
832 C: TryInto<KeyContext, Error = E>,
833 E: std::fmt::Display,
834 {
835 if let Some(key_context) = key_context.try_into().log_err() {
836 self.interactivity().key_context = Some(key_context);
837 }
838 self
839 }
840
841 /// Apply the given style to this element when the mouse hovers over it
842 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
843 debug_assert!(
844 self.interactivity().hover_style.is_none(),
845 "hover style already set"
846 );
847 self.interactivity().hover_style = Some(Box::new(f(StyleRefinement::default())));
848 self
849 }
850
851 /// Apply the given style to this element when the mouse hovers over a group member
852 fn group_hover(
853 mut self,
854 group_name: impl Into<SharedString>,
855 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
856 ) -> Self {
857 self.interactivity().group_hover_style = Some(GroupStyle {
858 group: group_name.into(),
859 style: Box::new(f(StyleRefinement::default())),
860 });
861 self
862 }
863
864 /// Bind the given callback to the mouse down event for the given mouse button.
865 /// The fluent API equivalent to [`Interactivity::on_mouse_down`].
866 ///
867 /// See [`Context::listener`](crate::Context::listener) to get access to the view state from this callback.
868 #[inline(always)]
869 fn on_mouse_down(
870 mut self,
871 button: MouseButton,
872 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
873 ) -> Self {
874 self.interactivity().on_mouse_down(button, listener);
875 self
876 }
877
878 /// Set a key that can be used to look up this element's bounds
879 /// in the [`crate::VisualTestContext::debug_bounds`] map.
880 ///
881 /// Selectors are only recorded in debug builds with the `test-support`
882 /// feature. Elsewhere this is a no-op, so `test-support` can stay enabled
883 /// in release builds without the per-frame cost.
884 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
885 fn debug_selector(mut self, f: impl FnOnce() -> String) -> Self {
886 self.interactivity().debug_selector = Some(f());
887 self
888 }
889
890 /// Set a key that can be used to look up this element's bounds
891 /// in the [`crate::VisualTestContext::debug_bounds`] map.
892 ///
893 /// Selectors are only recorded in debug builds with the `test-support`
894 /// feature. Elsewhere this is a no-op, so `test-support` can stay enabled
895 /// in release builds without the per-frame cost.
896 #[cfg(not(any(test, all(debug_assertions, feature = "test-support"))))]
897 #[inline]
898 fn debug_selector(self, _: impl FnOnce() -> String) -> Self {
899 self
900 }
901
902 /// Bind the given callback to the mouse down event for any button, during the capture phase.
903 /// The fluent API equivalent to [`Interactivity::capture_any_mouse_down`].
904 ///
905 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
906 fn capture_any_mouse_down(
907 mut self,
908 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
909 ) -> Self {
910 self.interactivity().capture_any_mouse_down(listener);
911 self
912 }
913
914 /// Bind the given callback to the mouse down event for any button, during the capture phase.
915 /// The fluent API equivalent to [`Interactivity::on_any_mouse_down`].
916 ///
917 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
918 fn on_any_mouse_down(
919 mut self,
920 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
921 ) -> Self {
922 self.interactivity().on_any_mouse_down(listener);
923 self
924 }
925
926 /// Bind the given callback to the mouse up event for the given button, during the bubble phase.
927 /// The fluent API equivalent to [`Interactivity::on_mouse_up`].
928 ///
929 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
930 fn on_mouse_up(
931 mut self,
932 button: MouseButton,
933 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
934 ) -> Self {
935 self.interactivity().on_mouse_up(button, listener);
936 self
937 }
938
939 /// Bind the given callback to the mouse up event for any button, during the capture phase.
940 /// The fluent API equivalent to [`Interactivity::capture_any_mouse_up`].
941 ///
942 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
943 fn capture_any_mouse_up(
944 mut self,
945 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
946 ) -> Self {
947 self.interactivity().capture_any_mouse_up(listener);
948 self
949 }
950
951 /// Bind the given callback to the mouse pressure event, during the bubble phase
952 /// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
953 ///
954 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
955 fn on_mouse_pressure(
956 mut self,
957 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
958 ) -> Self {
959 self.interactivity().on_mouse_pressure(listener);
960 self
961 }
962
963 /// Bind the given callback to the mouse pressure event, during the capture phase
964 /// the fluent API equivalent to [`Interactivity::on_mouse_pressure`]
965 ///
966 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
967 fn capture_mouse_pressure(
968 mut self,
969 listener: impl Fn(&MousePressureEvent, &mut Window, &mut App) + 'static,
970 ) -> Self {
971 self.interactivity().capture_mouse_pressure(listener);
972 self
973 }
974
975 /// Bind the given callback to the mouse down event, on any button, during the capture phase,
976 /// when the mouse is outside of the bounds of this element.
977 /// The fluent API equivalent to [`Interactivity::on_mouse_down_out`].
978 ///
979 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
980 fn on_mouse_down_out(
981 mut self,
982 listener: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
983 ) -> Self {
984 self.interactivity().on_mouse_down_out(listener);
985 self
986 }
987
988 /// Bind the given callback to the mouse up event, for the given button, during the capture phase,
989 /// when the mouse is outside of the bounds of this element.
990 /// The fluent API equivalent to [`Interactivity::on_mouse_up_out`].
991 ///
992 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
993 fn on_mouse_up_out(
994 mut self,
995 button: MouseButton,
996 listener: impl Fn(&MouseUpEvent, &mut Window, &mut App) + 'static,
997 ) -> Self {
998 self.interactivity().on_mouse_up_out(button, listener);
999 self
1000 }
1001
1002 /// Bind the given callback to the mouse move event, during the bubble phase.
1003 /// The fluent API equivalent to [`Interactivity::on_mouse_move`].
1004 ///
1005 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1006 fn on_mouse_move(
1007 mut self,
1008 listener: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
1009 ) -> Self {
1010 self.interactivity().on_mouse_move(listener);
1011 self
1012 }
1013
1014 /// Bind the given callback to the mouse exit event, during the bubble phase.
1015 /// The fluent API equivalent to [`Interactivity::on_mouse_exit`].
1016 ///
1017 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1018 fn on_mouse_exit(
1019 mut self,
1020 listener: impl Fn(&MouseExitEvent, &mut Window, &mut App) + 'static,
1021 ) -> Self {
1022 self.interactivity().on_mouse_exit(listener);
1023 self
1024 }
1025
1026 /// Bind the given callback to [`FileDropEvent::Exited`] when a platform file drag
1027 /// leaves this element's window while the element is hovered.
1028 ///
1029 /// This is a window-local exit event, not notification that the platform drag session ended.
1030 /// The fluent API equivalent to [`Interactivity::on_file_drop_exit`].
1031 ///
1032 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1033 fn on_file_drop_exit(
1034 mut self,
1035 listener: impl Fn(&FileDropEvent, &mut Window, &mut App) + 'static,
1036 ) -> Self {
1037 self.interactivity().on_file_drop_exit(listener);
1038 self
1039 }
1040
1041 /// Bind the given callback to the mouse drag event of the given type. Note that this
1042 /// will be called for all move events, inside or outside of this element, as long as the
1043 /// drag was started with this element under the mouse. Useful for implementing draggable
1044 /// UIs that don't conform to a drag and drop style interaction, like resizing.
1045 /// The fluent API equivalent to [`Interactivity::on_drag_move`].
1046 ///
1047 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1048 fn on_drag_move<T: 'static>(
1049 mut self,
1050 listener: impl Fn(&DragMoveEvent<T>, &mut Window, &mut App) + 'static,
1051 ) -> Self {
1052 self.interactivity().on_drag_move(listener);
1053 self
1054 }
1055
1056 /// Bind the given callback to scroll wheel events during the bubble phase.
1057 /// The fluent API equivalent to [`Interactivity::on_scroll_wheel`].
1058 ///
1059 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1060 fn on_scroll_wheel(
1061 mut self,
1062 listener: impl Fn(&ScrollWheelEvent, &mut Window, &mut App) + 'static,
1063 ) -> Self {
1064 self.interactivity().on_scroll_wheel(listener);
1065 self
1066 }
1067
1068 /// Bind the given callback to pinch gesture events during the bubble phase.
1069 /// The fluent API equivalent to [`Interactivity::on_pinch`].
1070 ///
1071 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1072 fn on_pinch(mut self, listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static) -> Self {
1073 self.interactivity().on_pinch(listener);
1074 self
1075 }
1076
1077 /// Bind the given callback to pinch gesture events during the capture phase.
1078 /// The fluent API equivalent to [`Interactivity::capture_pinch`].
1079 ///
1080 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1081 fn capture_pinch(
1082 mut self,
1083 listener: impl Fn(&PinchEvent, &mut Window, &mut App) + 'static,
1084 ) -> Self {
1085 self.interactivity().capture_pinch(listener);
1086 self
1087 }
1088 /// Capture the given action, before normal action dispatch can fire.
1089 /// The fluent API equivalent to [`Interactivity::capture_action`].
1090 ///
1091 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1092 fn capture_action<A: Action>(
1093 mut self,
1094 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1095 ) -> Self {
1096 self.interactivity().capture_action(listener);
1097 self
1098 }
1099
1100 /// Bind the given callback to an action dispatch during the bubble phase.
1101 /// The fluent API equivalent to [`Interactivity::on_action`].
1102 ///
1103 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1104 #[track_caller]
1105 #[inline(always)]
1106 fn on_action<A: Action>(
1107 mut self,
1108 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
1109 ) -> Self {
1110 self.interactivity().on_action(listener);
1111 self
1112 }
1113
1114 /// Bind the given callback to an action dispatch, based on a dynamic action parameter
1115 /// instead of a type parameter. Useful for component libraries that want to expose
1116 /// action bindings to their users.
1117 /// The fluent API equivalent to [`Interactivity::on_boxed_action`].
1118 ///
1119 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1120 fn on_boxed_action(
1121 mut self,
1122 action: &dyn Action,
1123 listener: impl Fn(&dyn Action, &mut Window, &mut App) + 'static,
1124 ) -> Self {
1125 self.interactivity().on_boxed_action(action, listener);
1126 self
1127 }
1128
1129 /// Bind the given callback to key down events during the bubble phase.
1130 /// The fluent API equivalent to [`Interactivity::on_key_down`].
1131 ///
1132 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1133 fn on_key_down(
1134 mut self,
1135 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1136 ) -> Self {
1137 self.interactivity().on_key_down(listener);
1138 self
1139 }
1140
1141 /// Bind the given callback to key down events during the capture phase.
1142 /// The fluent API equivalent to [`Interactivity::capture_key_down`].
1143 ///
1144 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1145 fn capture_key_down(
1146 mut self,
1147 listener: impl Fn(&KeyDownEvent, &mut Window, &mut App) + 'static,
1148 ) -> Self {
1149 self.interactivity().capture_key_down(listener);
1150 self
1151 }
1152
1153 /// Bind the given callback to key up events during the bubble phase.
1154 /// The fluent API equivalent to [`Interactivity::on_key_up`].
1155 ///
1156 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1157 fn on_key_up(
1158 mut self,
1159 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1160 ) -> Self {
1161 self.interactivity().on_key_up(listener);
1162 self
1163 }
1164
1165 /// Bind the given callback to key up events during the capture phase.
1166 /// The fluent API equivalent to [`Interactivity::capture_key_up`].
1167 ///
1168 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1169 fn capture_key_up(
1170 mut self,
1171 listener: impl Fn(&KeyUpEvent, &mut Window, &mut App) + 'static,
1172 ) -> Self {
1173 self.interactivity().capture_key_up(listener);
1174 self
1175 }
1176
1177 /// Bind the given callback to modifiers changing events.
1178 /// The fluent API equivalent to [`Interactivity::on_modifiers_changed`].
1179 ///
1180 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1181 #[inline(always)]
1182 fn on_modifiers_changed(
1183 mut self,
1184 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
1185 ) -> Self {
1186 self.interactivity().on_modifiers_changed(listener);
1187 self
1188 }
1189
1190 /// Apply the given style when the given data type is dragged over this element
1191 fn drag_over<S: 'static>(
1192 mut self,
1193 f: impl 'static + Fn(StyleRefinement, &S, &mut Window, &mut App) -> StyleRefinement,
1194 ) -> Self {
1195 self.interactivity().drag_over_styles.push((
1196 TypeId::of::<S>(),
1197 Box::new(move |currently_dragged: &dyn Any, window, cx| {
1198 f(
1199 StyleRefinement::default(),
1200 currently_dragged.downcast_ref::<S>().unwrap(),
1201 window,
1202 cx,
1203 )
1204 }),
1205 ));
1206 self
1207 }
1208
1209 /// Apply the given style when the given data type is dragged over this element's group
1210 fn group_drag_over<S: 'static>(
1211 mut self,
1212 group_name: impl Into<SharedString>,
1213 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1214 ) -> Self {
1215 self.interactivity().group_drag_over_styles.push((
1216 TypeId::of::<S>(),
1217 GroupStyle {
1218 group: group_name.into(),
1219 style: Box::new(f(StyleRefinement::default())),
1220 },
1221 ));
1222 self
1223 }
1224
1225 /// Bind the given callback to drop events of the given type, whether or not the drag started on this element.
1226 /// The fluent API equivalent to [`Interactivity::on_drop`].
1227 ///
1228 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1229 fn on_drop<T: 'static>(
1230 mut self,
1231 listener: impl Fn(&T, &mut Window, &mut App) + 'static,
1232 ) -> Self {
1233 self.interactivity().on_drop(listener);
1234 self
1235 }
1236
1237 /// Use the given predicate to determine whether or not a drop event should be dispatched to this element.
1238 /// The fluent API equivalent to [`Interactivity::can_drop`].
1239 fn can_drop(
1240 mut self,
1241 predicate: impl Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static,
1242 ) -> Self {
1243 self.interactivity().can_drop(predicate);
1244 self
1245 }
1246
1247 /// Block the mouse from all interactions with elements behind this element's hitbox. Typically
1248 /// `block_mouse_except_scroll` should be preferred.
1249 /// The fluent API equivalent to [`Interactivity::occlude_mouse`].
1250 fn occlude(mut self) -> Self {
1251 self.interactivity().occlude_mouse();
1252 self
1253 }
1254
1255 /// Set the bounds of this element as a window control area for the platform window.
1256 /// The fluent API equivalent to [`Interactivity::window_control_area`].
1257 fn window_control_area(mut self, area: WindowControlArea) -> Self {
1258 self.interactivity().window_control_area(area);
1259 self
1260 }
1261
1262 /// Block non-scroll mouse interactions with elements behind this element's hitbox.
1263 /// The fluent API equivalent to [`Interactivity::block_mouse_except_scroll`].
1264 ///
1265 /// See [`Hitbox::is_hovered`] for details.
1266 fn block_mouse_except_scroll(mut self) -> Self {
1267 self.interactivity().block_mouse_except_scroll();
1268 self
1269 }
1270
1271 /// Set the given styles to be applied when this element, specifically, is focused.
1272 /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1273 fn focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1274 where
1275 Self: Sized,
1276 {
1277 self.interactivity().focus_style = Some(Box::new(f(StyleRefinement::default())));
1278 self
1279 }
1280
1281 /// Set the given styles to be applied when this element is inside another element that is focused.
1282 /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1283 fn in_focus(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1284 where
1285 Self: Sized,
1286 {
1287 self.interactivity().in_focus_style = Some(Box::new(f(StyleRefinement::default())));
1288 self
1289 }
1290
1291 /// Set the given styles to be applied when this element is focused via keyboard navigation.
1292 /// This is similar to CSS's `:focus-visible` pseudo-class - it only applies when the element
1293 /// is focused AND the user is navigating via keyboard (not mouse clicks).
1294 /// Requires that the element is focusable. Elements can be made focusable using [`InteractiveElement::track_focus`].
1295 fn focus_visible(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1296 where
1297 Self: Sized,
1298 {
1299 self.interactivity().focus_visible_style = Some(Box::new(f(StyleRefinement::default())));
1300 self
1301 }
1302}
1303
1304/// A trait for elements that want to use the standard GPUI interactivity features
1305/// that require state.
1306pub trait StatefulInteractiveElement: InteractiveElement {
1307 /// Set the accessible role for this element.
1308 ///
1309 /// See the [accessibility guide](crate::_accessibility) for an overview.
1310 fn role(mut self, role: accesskit::Role) -> Self {
1311 debug_assert!(
1312 role != accesskit::Role::GenericContainer,
1313 "GenericContainer is filtered out of the a11y tree and has no effect"
1314 );
1315 self.interactivity().override_role = Some(role);
1316 self
1317 }
1318
1319 /// Set the author-provided identifier exposed to accessibility clients.
1320 ///
1321 /// Unlike the GPUI element ID, this value is visible outside the process.
1322 /// Keep it stable and unique within its accessibility tree.
1323 /// AccessKit maps it to platform identifiers where supported, including
1324 /// UIA `AutomationId` on Windows, `AXIdentifier` on macOS, and AT-SPI
1325 /// `AccessibleId` on Linux stacks whose deployed adapter exposes it.
1326 fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self {
1327 self.interactivity().aria.author_id = Some(id.into());
1328 self
1329 }
1330
1331 /// Set the accessible label for this element.
1332 fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
1333 self.interactivity().aria.label = Some(label.into());
1334 self
1335 }
1336
1337 /// Set the accessible description for this element. Unlike the label (which
1338 /// names the element), the description provides supplementary information
1339 /// that assistive technology announces after the name, role, and value -
1340 /// for example a settings subtitle or a hint.
1341 fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
1342 self.interactivity().aria.description = Some(description.into());
1343 self
1344 }
1345
1346 /// Set the keyboard shortcut(s) that activate this element, announced by
1347 /// assistive technology (maps to AccessKit's `keyboard_shortcut`).
1348 ///
1349 /// Note that this does not create a keymap. It simply instructs assistive
1350 /// technology what the keymap is.
1351 fn aria_keyshortcuts(mut self, keyshortcuts: impl Into<SharedString>) -> Self {
1352 self.interactivity().aria.keyshortcuts = Some(keyshortcuts.into());
1353 self
1354 }
1355
1356 /// Report this element as the focused node in the accessibility tree,
1357 /// overriding the element that holds real keyboard focus — but only while
1358 /// one of its ancestors actually holds focus.
1359 ///
1360 /// This implements the `aria-activedescendant` pattern for composite
1361 /// widgets that keep keyboard focus on a container (e.g. a menu or
1362 /// listbox) while a child is "selected": set this on the selected child so
1363 /// assistive technology announces and highlights it as focused.
1364 ///
1365 /// The element must also have a [`role`][Self::role] (and an id) so it
1366 /// produces an accessibility node. Unlike the web's container-side
1367 /// `aria-activedescendant`, this is set on the descendant; GPUI honors it
1368 /// only when a focused ancestor is present in the tree, so it is safe to
1369 /// set unconditionally on the selected child — if the container isn't
1370 /// focused, the claim is ignored.
1371 fn aria_active_descendant(mut self) -> Self {
1372 self.interactivity().report_active_descendant_focus = true;
1373 self
1374 }
1375
1376 /// Contribute synthetic accessibility nodes — nodes that don't correspond
1377 /// to any element — as children of this element's a11y node. For example,
1378 /// text runs describing an editor's text content.
1379 ///
1380 /// The closure is called after this element is prepainted, and only if it
1381 /// contributed a node to the accessibility tree (i.e. it has an id and a
1382 /// [`role`][StatefulInteractiveElement::role]).
1383 ///
1384 /// See [`Element::a11y_synthetic_children`] for details.
1385 fn a11y_synthetic_children(
1386 mut self,
1387 f: impl FnOnce(&mut crate::A11ySubtreeBuilder) + 'static,
1388 ) -> Self {
1389 self.interactivity().a11y_synthetic_children = Some(Box::new(f));
1390 self
1391 }
1392
1393 /// Set the selected state for this element.
1394 fn aria_selected(mut self, selected: bool) -> Self {
1395 self.interactivity().aria.selected = Some(selected);
1396 self
1397 }
1398
1399 /// Set the expanded state for this element.
1400 fn aria_expanded(mut self, expanded: bool) -> Self {
1401 self.interactivity().aria.expanded = Some(expanded);
1402 self
1403 }
1404
1405 /// Set the toggled state for this element.
1406 fn aria_toggled(mut self, toggled: accesskit::Toggled) -> Self {
1407 self.interactivity().aria.toggled = Some(toggled);
1408 self
1409 }
1410
1411 /// Set the numeric value for this element.
1412 fn aria_numeric_value(mut self, value: f64) -> Self {
1413 self.interactivity().aria.numeric_value = Some(value);
1414 self
1415 }
1416
1417 /// Set the step by which assistive technology should expect the numeric
1418 /// value of this element to change (e.g. when incrementing a spin button).
1419 fn aria_numeric_value_step(mut self, step: f64) -> Self {
1420 self.interactivity().aria.numeric_value_step = Some(step);
1421 self
1422 }
1423
1424 /// Set the string value of this element, e.g. the text content of a simple
1425 /// text input.
1426 fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
1427 self.interactivity().aria.value = Some(value.into());
1428 self
1429 }
1430
1431 /// Set the placeholder text reported to assistive technology for this
1432 /// element, shown when a text input is empty.
1433 fn aria_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1434 self.interactivity().aria.placeholder = Some(placeholder.into());
1435 self
1436 }
1437
1438 /// Set the minimum numeric value for this element.
1439 fn aria_min_numeric_value(mut self, value: f64) -> Self {
1440 self.interactivity().aria.min_numeric_value = Some(value);
1441 self
1442 }
1443
1444 /// Set the maximum numeric value for this element.
1445 fn aria_max_numeric_value(mut self, value: f64) -> Self {
1446 self.interactivity().aria.max_numeric_value = Some(value);
1447 self
1448 }
1449
1450 /// Set the orientation of this element.
1451 fn aria_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1452 self.interactivity().aria.orientation = Some(orientation);
1453 self
1454 }
1455
1456 /// Set the heading level of this element.
1457 fn aria_level(mut self, level: usize) -> Self {
1458 self.interactivity().aria.level = Some(level);
1459 self
1460 }
1461
1462 /// Set the position in set of this element.
1463 fn aria_position_in_set(mut self, position: usize) -> Self {
1464 self.interactivity().aria.position_in_set = Some(position);
1465 self
1466 }
1467
1468 /// Set the size of set for this element.
1469 fn aria_size_of_set(mut self, size: usize) -> Self {
1470 self.interactivity().aria.size_of_set = Some(size);
1471 self
1472 }
1473
1474 /// Set the row index for this element.
1475 fn aria_row_index(mut self, index: usize) -> Self {
1476 self.interactivity().aria.row_index = Some(index);
1477 self
1478 }
1479
1480 /// Set the column index for this element.
1481 fn aria_column_index(mut self, index: usize) -> Self {
1482 self.interactivity().aria.column_index = Some(index);
1483 self
1484 }
1485
1486 /// Set the row count for this element.
1487 fn aria_row_count(mut self, count: usize) -> Self {
1488 self.interactivity().aria.row_count = Some(count);
1489 self
1490 }
1491
1492 /// Set the column count for this element.
1493 fn aria_column_count(mut self, count: usize) -> Self {
1494 self.interactivity().aria.column_count = Some(count);
1495 self
1496 }
1497
1498 /// Register a handler for an accessibility action on this element.
1499 /// The handler is called when a screen reader requests the given action.
1500 ///
1501 /// See the [accessibility guide](crate::_accessibility) for an overview.
1502 #[inline(always)]
1503 fn on_a11y_action(
1504 mut self,
1505 action: accesskit::Action,
1506 listener: impl FnMut(Option<&accesskit::ActionData>, &mut crate::Window, &mut crate::App)
1507 + 'static,
1508 ) -> Self {
1509 self.interactivity()
1510 .a11y_action_listeners
1511 .push((action, Box::new(listener)));
1512 self
1513 }
1514
1515 /// Set this element to focusable.
1516 fn focusable(mut self) -> Self {
1517 self.interactivity().focusable = true;
1518 self
1519 }
1520
1521 /// Set the overflow x and y to scroll.
1522 fn overflow_scroll(mut self) -> Self {
1523 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1524 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1525 self
1526 }
1527
1528 /// Set the overflow x to scroll.
1529 fn overflow_x_scroll(mut self) -> Self {
1530 self.interactivity().base_style.overflow.x = Some(Overflow::Scroll);
1531 self
1532 }
1533
1534 /// Set the overflow y to scroll.
1535 fn overflow_y_scroll(mut self) -> Self {
1536 self.interactivity().base_style.overflow.y = Some(Overflow::Scroll);
1537 self
1538 }
1539
1540 /// Restrict scrolling of this element to the axis of the input gesture.
1541 ///
1542 /// See [`Style::restrict_scroll_to_axis`](crate::Style::restrict_scroll_to_axis) for details.
1543 fn restrict_scroll_to_axis(mut self) -> Self {
1544 self.interactivity().base_style.restrict_scroll_to_axis = Some(true);
1545 self
1546 }
1547
1548 /// Track the scroll state of this element with the given handle.
1549 fn track_scroll(mut self, scroll_handle: &ScrollHandle) -> Self {
1550 self.interactivity().tracked_scroll_handle = Some(scroll_handle.clone());
1551 self
1552 }
1553
1554 /// Track the scroll state of this element with the given handle.
1555 fn anchor_scroll(mut self, scroll_anchor: Option<ScrollAnchor>) -> Self {
1556 self.interactivity().scroll_anchor = scroll_anchor;
1557 self
1558 }
1559
1560 /// Set the given styles to be applied when this element is active.
1561 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
1562 where
1563 Self: Sized,
1564 {
1565 self.interactivity().active_style = Some(Box::new(f(StyleRefinement::default())));
1566 self
1567 }
1568
1569 /// Set the given styles to be applied when this element's group is active.
1570 fn group_active(
1571 mut self,
1572 group_name: impl Into<SharedString>,
1573 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
1574 ) -> Self
1575 where
1576 Self: Sized,
1577 {
1578 self.interactivity().group_active_style = Some(GroupStyle {
1579 group: group_name.into(),
1580 style: Box::new(f(StyleRefinement::default())),
1581 });
1582 self
1583 }
1584
1585 /// Bind the given callback to click events of this element.
1586 /// The fluent API equivalent to [`Interactivity::on_click`].
1587 ///
1588 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1589 #[inline(always)]
1590 fn on_click(mut self, listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self
1591 where
1592 Self: Sized,
1593 {
1594 self.interactivity().on_click(listener);
1595 self
1596 }
1597
1598 /// Bind the given callback to non-primary click events of this element.
1599 /// The fluent API equivalent to [`Interactivity::on_aux_click`].
1600 ///
1601 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1602 fn on_aux_click(
1603 mut self,
1604 listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1605 ) -> Self
1606 where
1607 Self: Sized,
1608 {
1609 self.interactivity().on_aux_click(listener);
1610 self
1611 }
1612
1613 /// On drag initiation, this callback will be used to create a new view to render the dragged value for a
1614 /// drag and drop operation. This API should also be used as the equivalent of 'on drag start' with
1615 /// the [`InteractiveElement::on_drag_move`] API.
1616 /// The callback also has access to the offset of triggering click from the origin of parent element.
1617 /// The fluent API equivalent to [`Interactivity::on_drag`].
1618 ///
1619 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1620 fn on_drag<T, W>(
1621 mut self,
1622 value: T,
1623 constructor: impl Fn(&T, Point<Pixels>, &mut Window, &mut App) -> Entity<W> + 'static,
1624 ) -> Self
1625 where
1626 Self: Sized,
1627 T: 'static,
1628 W: 'static + Render,
1629 {
1630 self.interactivity().on_drag(value, constructor);
1631 self
1632 }
1633
1634 /// Registers a callback resolving a payload to offer the platform if a drag started by this
1635 /// element leaves the window. It is invoked at most once per drag gesture, when the pointer
1636 /// exits the viewport. Must be called after [`Self::on_drag`], with the same dragged value
1637 /// type `T`.
1638 /// The fluent API equivalent to [`Interactivity::external_drag_payload`].
1639 fn external_drag_payload<T>(
1640 mut self,
1641 resolver: impl Fn(&T, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
1642 ) -> Self
1643 where
1644 Self: Sized,
1645 T: 'static,
1646 {
1647 self.interactivity().external_drag_payload(resolver);
1648 self
1649 }
1650
1651 /// Bind the given callback on the hover start and end events of this element. Note that the boolean
1652 /// passed to the callback is true when the hover starts and false when it ends.
1653 /// Transitions caused by layout changes under a stationary mouse also invoke the callback.
1654 ///
1655 /// By default, keyboard input suppresses hover until the next mouse move, mouse down, or touch. Set
1656 /// [`HoverListenerMode::InputModalityIndependent`] with [`Self::hover_listener_mode`] to
1657 /// continue hit-testing hover after keyboard input.
1658 /// The fluent API equivalent to [`Interactivity::on_hover`].
1659 ///
1660 /// See [`Context::listener`](crate::Context::listener) to get access to a view's state from this callback.
1661 fn on_hover(mut self, listener: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self
1662 where
1663 Self: Sized,
1664 {
1665 self.interactivity().on_hover(listener);
1666 self
1667 }
1668
1669 /// Sets how [`Self::on_hover`] responds to key presses while the mouse is stationary.
1670 /// This affects only the hover listener, not hover styles or tooltips. The fluent API
1671 /// equivalent to [`Interactivity::hover_listener_mode`].
1672 fn hover_listener_mode(mut self, mode: HoverListenerMode) -> Self
1673 where
1674 Self: Sized,
1675 {
1676 self.interactivity().hover_listener_mode(mode);
1677 self
1678 }
1679
1680 /// Constructs a tooltip when the element is hovered or long-pressed.
1681 /// The fluent API equivalent to [`Interactivity::tooltip`].
1682 fn tooltip(mut self, build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self
1683 where
1684 Self: Sized,
1685 {
1686 self.interactivity().tooltip(build_tooltip);
1687 self
1688 }
1689
1690 /// Constructs a tooltip when the element is hovered or long-pressed.
1691 /// The tooltip itself is also hoverable and won't disappear when the user moves the mouse into
1692 /// the tooltip. The fluent API equivalent to [`Interactivity::hoverable_tooltip`].
1693 fn hoverable_tooltip(
1694 mut self,
1695 build_tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
1696 ) -> Self
1697 where
1698 Self: Sized,
1699 {
1700 self.interactivity().hoverable_tooltip(build_tooltip);
1701 self
1702 }
1703
1704 /// Sets the delay before this element's tooltip is shown on hover.
1705 ///
1706 /// Touch long presses show the tooltip immediately once the gesture is recognized.
1707 /// The fluent API equivalent to [`Interactivity::tooltip_show_delay`].
1708 fn tooltip_show_delay(mut self, delay: Duration) -> Self
1709 where
1710 Self: Sized,
1711 {
1712 self.interactivity().tooltip_show_delay(delay);
1713 self
1714 }
1715}
1716
1717pub(crate) type MouseDownListener =
1718 Box<dyn Fn(&MouseDownEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1719pub(crate) type MouseUpListener =
1720 Box<dyn Fn(&MouseUpEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1721pub(crate) type MousePressureListener =
1722 Box<dyn Fn(&MousePressureEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1723pub(crate) type MouseMoveListener =
1724 Box<dyn Fn(&MouseMoveEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1725pub(crate) type MouseExitListener =
1726 Box<dyn Fn(&MouseExitEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1727
1728pub(crate) type FileDropExitListener =
1729 Box<dyn Fn(&FileDropEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1730
1731pub(crate) type ScrollWheelListener =
1732 Box<dyn Fn(&ScrollWheelEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1733
1734pub(crate) type PinchListener =
1735 Box<dyn Fn(&PinchEvent, DispatchPhase, &Hitbox, &mut Window, &mut App) + 'static>;
1736
1737pub(crate) type ClickListener = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;
1738
1739/// Controls how [`StatefulInteractiveElement::on_hover`] responds to key presses while the mouse
1740/// is stationary.
1741#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1742pub enum HoverListenerMode {
1743 /// Use input-modality-aware hit testing. Keyboard input suppresses hover until the mouse moves
1744 /// again, unless pointer capture or an active mouse-down interaction keeps the listener hovered.
1745 #[default]
1746 InputModalityAware,
1747 /// Use hit testing even when the last input was from the keyboard. This changes only
1748 /// keyboard-modality filtering; all other [`StatefulInteractiveElement::on_hover`] behavior
1749 /// remains unchanged.
1750 InputModalityIndependent,
1751}
1752
1753impl HoverListenerMode {
1754 fn is_hovered(self, hitbox: &Hitbox, window: &Window) -> bool {
1755 match self {
1756 Self::InputModalityAware => hitbox.is_hovered(window),
1757 Self::InputModalityIndependent => hitbox.id.is_hovered_ignoring_last_input(window),
1758 }
1759 }
1760}
1761
1762pub(crate) struct DragListener {
1763 value: Arc<dyn Any>,
1764 render: Box<dyn Fn(&dyn Any, Point<Pixels>, &mut Window, &mut App) -> AnyView + 'static>,
1765 external_payload: Option<ExternalDragPayloadResolver>,
1766}
1767
1768type ExternalDragPayloadResolver =
1769 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
1770
1771type DropListener = Box<dyn Fn(&dyn Any, &mut Window, &mut App) + 'static>;
1772
1773type CanDropPredicate = Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>;
1774
1775pub(crate) struct TooltipBuilder {
1776 build: Rc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>,
1777 hoverable: bool,
1778}
1779
1780pub(crate) type KeyDownListener =
1781 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1782
1783pub(crate) type KeyUpListener =
1784 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut Window, &mut App) + 'static>;
1785
1786pub(crate) type ModifiersChangedListener =
1787 Box<dyn Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static>;
1788
1789pub(crate) type ActionListener =
1790 Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
1791
1792/// Construct a new [`Div`] element
1793#[track_caller]
1794pub fn div() -> Div {
1795 Div {
1796 interactivity: Interactivity::new(),
1797 children: SmallVec::default(),
1798 prepaint_listener: None,
1799 image_cache: None,
1800 prepaint_order_fn: None,
1801 }
1802}
1803
1804/// A [`Div`] element, the all-in-one element for building complex UIs in GPUI
1805pub struct Div {
1806 interactivity: Interactivity,
1807 children: SmallVec<[StackSafe<AnyElement>; 2]>,
1808 prepaint_listener: Option<Box<dyn Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static>>,
1809 image_cache: Option<Box<dyn ImageCacheProvider>>,
1810 prepaint_order_fn: Option<Box<dyn Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]>>>,
1811}
1812
1813impl Div {
1814 /// Add a listener to be called when the children of this `Div` are prepainted.
1815 /// This allows you to store the [`Bounds`] of the children for later use.
1816 pub fn on_children_prepainted(
1817 mut self,
1818 listener: impl Fn(Vec<Bounds<Pixels>>, &mut Window, &mut App) + 'static,
1819 ) -> Self {
1820 self.prepaint_listener = Some(Box::new(listener));
1821 self
1822 }
1823
1824 /// Add an image cache at the location of this div in the element tree.
1825 pub fn image_cache(mut self, cache: impl ImageCacheProvider) -> Self {
1826 self.image_cache = Some(Box::new(cache));
1827 self
1828 }
1829
1830 /// Specify a function that determines the order in which children are prepainted.
1831 ///
1832 /// The function is called at prepaint time and should return a vector of child indices
1833 /// in the desired prepaint order. Each index should appear exactly once.
1834 ///
1835 /// This is useful when the prepaint of one child affects state that another child reads.
1836 /// For example, in split editor views, the editor with an autoscroll request should
1837 /// be prepainted first so its scroll position update is visible to the other editor.
1838 pub fn with_dynamic_prepaint_order(
1839 mut self,
1840 order_fn: impl Fn(&mut Window, &mut App) -> SmallVec<[usize; 8]> + 'static,
1841 ) -> Self {
1842 self.prepaint_order_fn = Some(Box::new(order_fn));
1843 self
1844 }
1845}
1846
1847/// A frame state for a `Div` element, which contains layout IDs for its children.
1848///
1849/// This struct is used internally by the `Div` element to manage the layout state of its children
1850/// during the UI update cycle. It holds a small vector of `LayoutId` values, each corresponding to
1851/// a child element of the `Div`. These IDs are used to query the layout engine for the computed
1852/// bounds of the children after the layout phase is complete.
1853pub struct DivFrameState {
1854 child_layout_ids: SmallVec<[LayoutId; 2]>,
1855}
1856
1857/// Interactivity state displayed an manipulated in the inspector.
1858#[derive(Clone)]
1859pub struct DivInspectorState {
1860 /// The inspected element's base style. This is used for both inspecting and modifying the
1861 /// state. In the future it will make sense to separate the read and write, possibly tracking
1862 /// the modifications.
1863 #[cfg(any(feature = "inspector", debug_assertions))]
1864 pub base_style: Box<StyleRefinement>,
1865 /// Inspects the bounds of the element.
1866 pub bounds: Bounds<Pixels>,
1867 /// Size of the children of the element, or `bounds.size` if it has no children.
1868 pub content_size: Size<Pixels>,
1869}
1870
1871impl Styled for Div {
1872 fn style(&mut self) -> &mut StyleRefinement {
1873 &mut self.interactivity.base_style
1874 }
1875}
1876
1877impl InteractiveElement for Div {
1878 fn interactivity(&mut self) -> &mut Interactivity {
1879 &mut self.interactivity
1880 }
1881}
1882
1883impl ParentElement for Div {
1884 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1885 #[cfg(feature = "stacker")]
1886 self.children
1887 .extend(elements.into_iter().map(StackSafe::new));
1888 #[cfg(not(feature = "stacker"))]
1889 self.children.extend(elements);
1890 }
1891}
1892
1893impl Element for Div {
1894 type RequestLayoutState = DivFrameState;
1895 type PrepaintState = Option<Hitbox>;
1896
1897 fn id(&self) -> Option<ElementId> {
1898 self.interactivity.element_id.clone()
1899 }
1900
1901 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
1902 self.interactivity.source_location()
1903 }
1904
1905 fn a11y_role(&self) -> Option<accesskit::Role> {
1906 // Nodes with `GenericContainer` should never be reported to accesskit.
1907 // Equivalent to an HTML div with no role.
1908 self.interactivity
1909 .override_role
1910 .filter(|role| *role != accesskit::Role::GenericContainer)
1911 }
1912
1913 fn write_a11y_info(&self, node: &mut accesskit::Node) {
1914 self.interactivity.write_a11y_info(node);
1915 }
1916
1917 fn a11y_synthetic_children(
1918 &mut self,
1919 _prepaint: &mut Self::PrepaintState,
1920 builder: &mut crate::A11ySubtreeBuilder,
1921 ) {
1922 if let Some(f) = self.interactivity.a11y_synthetic_children.take() {
1923 f(builder);
1924 }
1925 }
1926
1927 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
1928 fn request_layout(
1929 &mut self,
1930 global_id: Option<&GlobalElementId>,
1931 inspector_id: Option<&InspectorElementId>,
1932 window: &mut Window,
1933 cx: &mut App,
1934 ) -> (LayoutId, Self::RequestLayoutState) {
1935 let mut child_layout_ids = SmallVec::new();
1936 let image_cache = self
1937 .image_cache
1938 .as_mut()
1939 .map(|provider| provider.provide(window, cx));
1940
1941 let layout_id = window.with_image_cache(image_cache, |window| {
1942 self.interactivity.request_layout(
1943 global_id,
1944 inspector_id,
1945 window,
1946 cx,
1947 |style, window, cx| {
1948 window.with_text_style(style.text_style().cloned(), |window| {
1949 child_layout_ids = self
1950 .children
1951 .iter_mut()
1952 .map(|child| child.request_layout(window, cx))
1953 .collect::<SmallVec<_>>();
1954 window.request_layout(style, child_layout_ids.iter().copied(), cx)
1955 })
1956 },
1957 )
1958 });
1959
1960 (layout_id, DivFrameState { child_layout_ids })
1961 }
1962
1963 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
1964 fn prepaint(
1965 &mut self,
1966 global_id: Option<&GlobalElementId>,
1967 inspector_id: Option<&InspectorElementId>,
1968 bounds: Bounds<Pixels>,
1969 request_layout: &mut Self::RequestLayoutState,
1970 window: &mut Window,
1971 cx: &mut App,
1972 ) -> Option<Hitbox> {
1973 let image_cache = self
1974 .image_cache
1975 .as_mut()
1976 .map(|provider| provider.provide(window, cx));
1977
1978 let has_prepaint_listener = self.prepaint_listener.is_some();
1979 let mut children_bounds = Vec::with_capacity(if has_prepaint_listener {
1980 request_layout.child_layout_ids.len()
1981 } else {
1982 0
1983 });
1984
1985 let mut child_min = point(Pixels::MAX, Pixels::MAX);
1986 let mut child_max = Point::default();
1987 if let Some(handle) = self.interactivity.scroll_anchor.as_ref() {
1988 *handle.last_origin.borrow_mut() = bounds.origin - window.element_offset();
1989 }
1990 let content_size = if request_layout.child_layout_ids.is_empty() {
1991 bounds.size
1992 } else if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
1993 let mut state = scroll_handle.0.borrow_mut();
1994 state.child_bounds = Vec::with_capacity(request_layout.child_layout_ids.len());
1995 for child_layout_id in &request_layout.child_layout_ids {
1996 let child_bounds = window.layout_bounds(*child_layout_id);
1997 child_min = child_min.min(&child_bounds.origin);
1998 child_max = child_max.max(&child_bounds.bottom_right());
1999 state.child_bounds.push(child_bounds);
2000 }
2001 (child_max - child_min).into()
2002 } else {
2003 for child_layout_id in &request_layout.child_layout_ids {
2004 let child_bounds = window.layout_bounds(*child_layout_id);
2005 child_min = child_min.min(&child_bounds.origin);
2006 child_max = child_max.max(&child_bounds.bottom_right());
2007
2008 if has_prepaint_listener {
2009 children_bounds.push(child_bounds);
2010 }
2011 }
2012 (child_max - child_min).into()
2013 };
2014
2015 if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() {
2016 scroll_handle.scroll_to_active_item();
2017 }
2018
2019 self.interactivity.prepaint(
2020 global_id,
2021 inspector_id,
2022 bounds,
2023 content_size,
2024 window,
2025 cx,
2026 |style, scroll_offset, hitbox, window, cx| {
2027 // skip children
2028 if style.display == Display::None {
2029 return hitbox;
2030 }
2031
2032 window.with_image_cache(image_cache, |window| {
2033 window.with_element_offset(scroll_offset, |window| {
2034 if let Some(order_fn) = &self.prepaint_order_fn {
2035 let order = order_fn(window, cx);
2036 for idx in order {
2037 if let Some(child) = self.children.get_mut(idx) {
2038 child.prepaint(window, cx);
2039 }
2040 }
2041 } else {
2042 for child in &mut self.children {
2043 child.prepaint(window, cx);
2044 }
2045 }
2046 });
2047
2048 if let Some(listener) = self.prepaint_listener.as_ref() {
2049 listener(children_bounds, window, cx);
2050 }
2051 });
2052
2053 hitbox
2054 },
2055 )
2056 }
2057
2058 #[cfg_attr(feature = "stacker", stacksafe::stacksafe)]
2059 fn paint(
2060 &mut self,
2061 global_id: Option<&GlobalElementId>,
2062 inspector_id: Option<&InspectorElementId>,
2063 bounds: Bounds<Pixels>,
2064 _request_layout: &mut Self::RequestLayoutState,
2065 hitbox: &mut Option<Hitbox>,
2066 window: &mut Window,
2067 cx: &mut App,
2068 ) {
2069 let image_cache = self
2070 .image_cache
2071 .as_mut()
2072 .map(|provider| provider.provide(window, cx));
2073
2074 window.with_image_cache(image_cache, |window| {
2075 self.interactivity.paint(
2076 global_id,
2077 inspector_id,
2078 bounds,
2079 hitbox.as_ref(),
2080 window,
2081 cx,
2082 |style, window, cx| {
2083 // skip children
2084 if style.display == Display::None {
2085 return;
2086 }
2087
2088 for child in &mut self.children {
2089 child.paint(window, cx);
2090 }
2091 },
2092 )
2093 });
2094 }
2095}
2096
2097impl IntoElement for Div {
2098 type Element = Self;
2099
2100 fn into_element(self) -> Self::Element {
2101 self
2102 }
2103}
2104
2105#[derive(Default)]
2106pub(crate) struct AriaProperties {
2107 pub(crate) author_id: Option<SharedString>,
2108 pub(crate) label: Option<SharedString>,
2109 pub(crate) description: Option<SharedString>,
2110 pub(crate) keyshortcuts: Option<SharedString>,
2111 pub(crate) selected: Option<bool>,
2112 pub(crate) expanded: Option<bool>,
2113 pub(crate) toggled: Option<accesskit::Toggled>,
2114 pub(crate) numeric_value: Option<f64>,
2115 pub(crate) min_numeric_value: Option<f64>,
2116 pub(crate) max_numeric_value: Option<f64>,
2117 pub(crate) numeric_value_step: Option<f64>,
2118 pub(crate) value: Option<SharedString>,
2119 pub(crate) placeholder: Option<SharedString>,
2120 pub(crate) orientation: Option<accesskit::Orientation>,
2121 pub(crate) level: Option<usize>,
2122 pub(crate) position_in_set: Option<usize>,
2123 pub(crate) size_of_set: Option<usize>,
2124 pub(crate) row_index: Option<usize>,
2125 pub(crate) column_index: Option<usize>,
2126 pub(crate) row_count: Option<usize>,
2127 pub(crate) column_count: Option<usize>,
2128}
2129
2130/// The interactivity struct. Powers all of the general-purpose
2131/// interactivity in the `Div` element.
2132#[derive(Default)]
2133pub struct Interactivity {
2134 /// The element ID of the element. In id is required to support a stateful subset of the interactivity such as on_click.
2135 pub element_id: Option<ElementId>,
2136 /// Whether the element was clicked. This will only be present after layout.
2137 pub active: Option<bool>,
2138 /// Whether the element was hovered. This will only be present after paint if an hitbox
2139 /// was created for the interactive element.
2140 pub hovered: Option<bool>,
2141 pub(crate) tooltip_id: Option<TooltipId>,
2142 pub(crate) content_size: Size<Pixels>,
2143 pub(crate) key_context: Option<KeyContext>,
2144 pub(crate) focusable: bool,
2145 pub(crate) tracked_focus_handle: Option<FocusHandle>,
2146 pub(crate) tracked_scroll_handle: Option<ScrollHandle>,
2147 pub(crate) scroll_anchor: Option<ScrollAnchor>,
2148 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
2149 pub(crate) ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
2150 pub(crate) group: Option<SharedString>,
2151 /// The base style of the element, before any modifications are applied
2152 /// by focus, active, etc.
2153 pub base_style: Box<StyleRefinement>,
2154 pub(crate) focus_style: Option<Box<StyleRefinement>>,
2155 pub(crate) in_focus_style: Option<Box<StyleRefinement>>,
2156 pub(crate) focus_visible_style: Option<Box<StyleRefinement>>,
2157 pub(crate) hover_style: Option<Box<StyleRefinement>>,
2158 pub(crate) group_hover_style: Option<GroupStyle>,
2159 pub(crate) active_style: Option<Box<StyleRefinement>>,
2160 pub(crate) group_active_style: Option<GroupStyle>,
2161 pub(crate) drag_over_styles: Vec<(
2162 TypeId,
2163 Box<dyn Fn(&dyn Any, &mut Window, &mut App) -> StyleRefinement>,
2164 )>,
2165 pub(crate) group_drag_over_styles: Vec<(TypeId, GroupStyle)>,
2166 pub(crate) mouse_down_listeners: Vec<MouseDownListener>,
2167 pub(crate) mouse_up_listeners: Vec<MouseUpListener>,
2168 pub(crate) mouse_pressure_listeners: Vec<MousePressureListener>,
2169 pub(crate) mouse_move_listeners: Vec<MouseMoveListener>,
2170 pub(crate) mouse_exit_listeners: Vec<MouseExitListener>,
2171 pub(crate) file_drop_exit_listeners: Vec<FileDropExitListener>,
2172 pub(crate) scroll_wheel_listeners: Vec<ScrollWheelListener>,
2173 pub(crate) pinch_listeners: Vec<PinchListener>,
2174 pub(crate) key_down_listeners: Vec<KeyDownListener>,
2175 pub(crate) key_up_listeners: Vec<KeyUpListener>,
2176 pub(crate) modifiers_changed_listeners: Vec<ModifiersChangedListener>,
2177 pub(crate) action_listeners: Vec<(TypeId, ActionListener)>,
2178 pub(crate) drop_listeners: Vec<(TypeId, DropListener)>,
2179 pub(crate) can_drop_predicate: Option<CanDropPredicate>,
2180 pub(crate) click_listeners: Vec<ClickListener>,
2181 pub(crate) aux_click_listeners: Vec<ClickListener>,
2182 pub(crate) drag_listener: Option<DragListener>,
2183 pub(crate) hover_listener: Option<Box<dyn Fn(&bool, &mut Window, &mut App)>>,
2184 pub(crate) hover_listener_mode: HoverListenerMode,
2185 pub(crate) tooltip_builder: Option<TooltipBuilder>,
2186 pub(crate) tooltip_show_delay: Option<Duration>,
2187 pub(crate) window_control: Option<WindowControlArea>,
2188 pub(crate) hitbox_behavior: HitboxBehavior,
2189 pub(crate) tab_index: Option<isize>,
2190 pub(crate) tab_group: bool,
2191 pub(crate) tab_stop: bool,
2192
2193 pub(crate) a11y_action_listeners:
2194 Vec<(accesskit::Action, crate::window::a11y::A11yActionListener)>,
2195 pub(crate) a11y_synthetic_children: Option<Box<dyn FnOnce(&mut crate::A11ySubtreeBuilder)>>,
2196 pub(crate) report_active_descendant_focus: bool,
2197 pub(crate) override_role: Option<accesskit::Role>,
2198 pub(crate) aria: AriaProperties,
2199
2200 #[cfg(any(feature = "inspector", debug_assertions))]
2201 pub(crate) source_location: Option<&'static core::panic::Location<'static>>,
2202
2203 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2204 pub(crate) debug_selector: Option<String>,
2205}
2206
2207impl Interactivity {
2208 /// Layout this element according to this interactivity state's configured styles
2209 pub fn request_layout(
2210 &mut self,
2211 global_id: Option<&GlobalElementId>,
2212 _inspector_id: Option<&InspectorElementId>,
2213 window: &mut Window,
2214 cx: &mut App,
2215 f: impl FnOnce(Style, &mut Window, &mut App) -> LayoutId,
2216 ) -> LayoutId {
2217 #[cfg(any(feature = "inspector", debug_assertions))]
2218 window.with_inspector_state(
2219 _inspector_id,
2220 cx,
2221 |inspector_state: &mut Option<DivInspectorState>, _window| {
2222 if let Some(inspector_state) = inspector_state {
2223 self.base_style = inspector_state.base_style.clone();
2224 } else {
2225 *inspector_state = Some(DivInspectorState {
2226 base_style: self.base_style.clone(),
2227 bounds: Default::default(),
2228 content_size: Default::default(),
2229 })
2230 }
2231 },
2232 );
2233
2234 window.with_optional_element_state::<InteractiveElementState, _>(
2235 global_id,
2236 |element_state, window| {
2237 let mut element_state =
2238 element_state.map(|element_state| element_state.unwrap_or_default());
2239
2240 if let Some(element_state) = element_state.as_ref()
2241 && cx.has_active_drag()
2242 {
2243 if let Some(pending_mouse_down) = element_state.pending_mouse_down.as_ref() {
2244 *pending_mouse_down.borrow_mut() = None;
2245 }
2246 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2247 *clicked_state.borrow_mut() = ElementClickedState::default();
2248 }
2249 }
2250
2251 // Ensure we store a focus handle in our element state if we're focusable.
2252 // If there's an explicit focus handle we're tracking, use that. Otherwise
2253 // create a new handle and store it in the element state, which lives for as
2254 // as frames contain an element with this id.
2255 if self.focusable
2256 && self.tracked_focus_handle.is_none()
2257 && let Some(element_state) = element_state.as_mut()
2258 {
2259 let mut handle = element_state
2260 .focus_handle
2261 .get_or_insert_with(|| cx.focus_handle())
2262 .clone()
2263 .tab_stop(self.tab_stop);
2264
2265 if let Some(index) = self.tab_index {
2266 handle = handle.tab_index(index);
2267 }
2268
2269 self.tracked_focus_handle = Some(handle);
2270 }
2271
2272 if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() {
2273 let scroll_handle_state = scroll_handle.0.borrow();
2274 self.scroll_offset = Some(scroll_handle_state.offset.clone());
2275 self.ongoing_scroll = Some(scroll_handle_state.ongoing_scroll.clone());
2276 } else if (self.base_style.overflow.x == Some(Overflow::Scroll)
2277 || self.base_style.overflow.y == Some(Overflow::Scroll))
2278 && let Some(element_state) = element_state.as_mut()
2279 {
2280 self.scroll_offset = Some(
2281 element_state
2282 .scroll_offset
2283 .get_or_insert_with(Rc::default)
2284 .clone(),
2285 );
2286 self.ongoing_scroll = Some(
2287 element_state
2288 .ongoing_scroll
2289 .get_or_insert_with(|| Rc::new(RefCell::new(OngoingScroll::default())))
2290 .clone(),
2291 );
2292 }
2293
2294 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2295 let layout_id = f(style, window, cx);
2296 (layout_id, element_state)
2297 },
2298 )
2299 }
2300
2301 /// Commit the bounds of this element according to this interactivity state's configured styles.
2302 pub fn prepaint<R>(
2303 &mut self,
2304 global_id: Option<&GlobalElementId>,
2305 _inspector_id: Option<&InspectorElementId>,
2306 bounds: Bounds<Pixels>,
2307 content_size: Size<Pixels>,
2308 window: &mut Window,
2309 cx: &mut App,
2310 f: impl FnOnce(&Style, Point<Pixels>, Option<Hitbox>, &mut Window, &mut App) -> R,
2311 ) -> R {
2312 self.content_size = content_size;
2313
2314 #[cfg(any(feature = "inspector", debug_assertions))]
2315 window.with_inspector_state(
2316 _inspector_id,
2317 cx,
2318 |inspector_state: &mut Option<DivInspectorState>, _window| {
2319 if let Some(inspector_state) = inspector_state {
2320 inspector_state.bounds = bounds;
2321 inspector_state.content_size = content_size;
2322 }
2323 },
2324 );
2325
2326 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
2327 window.set_focus_handle(focus_handle, cx);
2328
2329 if window.a11y.is_active() {
2330 if let Some(global_id) = global_id {
2331 let node_id = global_id.accesskit_node_id();
2332 window.a11y.set_focusable(node_id, focus_handle.id);
2333 if focus_handle.is_focused(window) {
2334 window.a11y.set_focus(node_id);
2335 }
2336 } else if focus_handle.is_focused(window) {
2337 // Focusable, but with no element id it can't have an
2338 // accessibility node, so screen readers fall back to the
2339 // whole window.
2340 window
2341 .a11y
2342 .note_focus_without_node(focus_handle.id, "it has no element id");
2343 }
2344 }
2345 }
2346
2347 if self.report_active_descendant_focus && window.a11y.is_active() {
2348 if let Some(global_id) = global_id {
2349 window
2350 .a11y
2351 .set_active_descendant(global_id.accesskit_node_id());
2352 }
2353 }
2354 window.with_optional_element_state::<InteractiveElementState, _>(
2355 global_id,
2356 |element_state, window| {
2357 let mut element_state =
2358 element_state.map(|element_state| element_state.unwrap_or_default());
2359 let style = self.compute_style_internal(None, element_state.as_mut(), window, cx);
2360
2361 if let Some(element_state) = element_state.as_mut() {
2362 if let Some(clicked_state) = element_state.clicked_state.as_ref() {
2363 let clicked_state = clicked_state.borrow();
2364 self.active = Some(clicked_state.element);
2365 }
2366 if self.hover_style.is_some() || self.group_hover_style.is_some() {
2367 element_state
2368 .hover_state
2369 .get_or_insert_with(Default::default);
2370 }
2371 if let Some(active_tooltip) = element_state.active_tooltip.as_ref() {
2372 if self.tooltip_builder.is_some() {
2373 self.tooltip_id = set_tooltip_on_window(active_tooltip, window);
2374 } else {
2375 // If there is no longer a tooltip builder, remove the active tooltip.
2376 if let Some(long_press_tooltip_active) =
2377 element_state.long_press_tooltip_active.as_ref()
2378 {
2379 long_press_tooltip_active.set(false);
2380 }
2381 element_state.active_tooltip.take();
2382 }
2383 }
2384 }
2385
2386 window.with_text_style(style.text_style().cloned(), |window| {
2387 window.with_content_mask(
2388 style.overflow_mask(bounds, window.rem_size()),
2389 |window| {
2390 let hitbox = if self.should_insert_hitbox(&style, window, cx) {
2391 Some(window.insert_hitbox(bounds, self.hitbox_behavior))
2392 } else {
2393 None
2394 };
2395
2396 let scroll_offset =
2397 self.clamp_scroll_position(bounds, &style, window, cx);
2398 let result = f(&style, scroll_offset, hitbox, window, cx);
2399 (result, element_state)
2400 },
2401 )
2402 })
2403 },
2404 )
2405 }
2406
2407 fn should_insert_hitbox(&self, style: &Style, window: &Window, cx: &App) -> bool {
2408 self.hitbox_behavior != HitboxBehavior::Normal
2409 || self.window_control.is_some()
2410 || style.mouse_cursor.is_some()
2411 || self.group.is_some()
2412 || self.scroll_offset.is_some()
2413 || self.tracked_focus_handle.is_some()
2414 || self.hover_style.is_some()
2415 || self.group_hover_style.is_some()
2416 || self.hover_listener.is_some()
2417 || !self.mouse_up_listeners.is_empty()
2418 || !self.mouse_pressure_listeners.is_empty()
2419 || !self.mouse_down_listeners.is_empty()
2420 || !self.mouse_move_listeners.is_empty()
2421 || !self.mouse_exit_listeners.is_empty()
2422 || !self.file_drop_exit_listeners.is_empty()
2423 || !self.click_listeners.is_empty()
2424 || !self.aux_click_listeners.is_empty()
2425 || !self.scroll_wheel_listeners.is_empty()
2426 || self.has_pinch_listeners()
2427 || self.drag_listener.is_some()
2428 || !self.drop_listeners.is_empty()
2429 || !self.drag_over_styles.is_empty()
2430 || self.tooltip_builder.is_some()
2431 || window.is_inspector_picking(cx)
2432 }
2433
2434 fn clamp_scroll_position(
2435 &self,
2436 bounds: Bounds<Pixels>,
2437 style: &Style,
2438 window: &mut Window,
2439 _cx: &mut App,
2440 ) -> Point<Pixels> {
2441 fn round_to_two_decimals(pixels: Pixels) -> Pixels {
2442 const ROUNDING_FACTOR: f32 = 100.0;
2443 (pixels * ROUNDING_FACTOR).round() / ROUNDING_FACTOR
2444 }
2445
2446 if let Some(scroll_offset) = self.scroll_offset.as_ref() {
2447 let mut scroll_to_bottom = false;
2448 let mut tracked_scroll_handle = self
2449 .tracked_scroll_handle
2450 .as_ref()
2451 .map(|handle| handle.0.borrow_mut());
2452 if let Some(mut scroll_handle_state) = tracked_scroll_handle.as_deref_mut() {
2453 scroll_handle_state.overflow = style.overflow;
2454 scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom);
2455 }
2456
2457 let rem_size = window.rem_size();
2458 // Taffy lays the box out with the padding snapped to the device pixel
2459 // grid (`to_taffy`); recomputed unsnapped, e.g. py_1 at a fractional
2460 // rem size, it exceeds `bounds` and leaves the box scrollable by the
2461 // sub-pixel difference.
2462 let padding = style
2463 .padding
2464 .to_pixels(bounds.size.into(), rem_size)
2465 .map(|edge| window.pixel_snap(*edge));
2466 let padding_size = size(padding.left + padding.right, padding.top + padding.bottom);
2467 // The floating point values produced by Taffy and ours often vary
2468 // slightly after ~5 decimal places. This can lead to cases where after
2469 // subtracting these, the container becomes scrollable for less than
2470 // 0.00000x pixels. As we generally don't benefit from a precision that
2471 // high for the maximum scroll, we round the scroll max to 2 decimal
2472 // places here.
2473 let padded_content_size = self.content_size + padding_size;
2474 let scroll_max = Point::from(padded_content_size - bounds.size)
2475 .map(round_to_two_decimals)
2476 .max(&Default::default());
2477 // Clamp scroll offset in case scroll max is smaller now (e.g., if children
2478 // were removed or the bounds became larger).
2479 let mut scroll_offset = scroll_offset.borrow_mut();
2480
2481 scroll_offset.x = scroll_offset.x.clamp(-scroll_max.x, px(0.));
2482 if scroll_to_bottom {
2483 scroll_offset.y = -scroll_max.y;
2484 } else {
2485 scroll_offset.y = scroll_offset.y.clamp(-scroll_max.y, px(0.));
2486 }
2487
2488 if let Some(mut scroll_handle_state) = tracked_scroll_handle {
2489 scroll_handle_state.max_offset = scroll_max;
2490 scroll_handle_state.bounds = bounds;
2491 }
2492
2493 *scroll_offset
2494 } else {
2495 Point::default()
2496 }
2497 }
2498
2499 /// Paint this element according to this interactivity state's configured styles
2500 /// and bind the element's mouse and keyboard events.
2501 ///
2502 /// content_size is the size of the content of the element, which may be larger than the
2503 /// element's bounds if the element is scrollable.
2504 ///
2505 /// the final computed style will be passed to the provided function, along
2506 /// with the current scroll offset
2507 pub fn paint(
2508 &mut self,
2509 global_id: Option<&GlobalElementId>,
2510 _inspector_id: Option<&InspectorElementId>,
2511 bounds: Bounds<Pixels>,
2512 hitbox: Option<&Hitbox>,
2513 window: &mut Window,
2514 cx: &mut App,
2515 f: impl FnOnce(&Style, &mut Window, &mut App),
2516 ) {
2517 self.hovered = hitbox.map(|hitbox| hitbox.is_hovered(window));
2518 window.with_optional_element_state::<InteractiveElementState, _>(
2519 global_id,
2520 |element_state, window| {
2521 let mut element_state =
2522 element_state.map(|element_state| element_state.unwrap_or_default());
2523
2524 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
2525
2526 #[cfg(any(test, all(debug_assertions, feature = "test-support")))]
2527 if let Some(debug_selector) = &self.debug_selector {
2528 window
2529 .next_frame
2530 .record_debug_bounds(debug_selector.clone(), bounds);
2531 }
2532
2533 self.paint_hover_group_handler(window, cx);
2534
2535 if style.visibility == Visibility::Hidden {
2536 return ((), element_state);
2537 }
2538
2539 let mut tab_group = None;
2540 if self.tab_group {
2541 tab_group = self.tab_index;
2542 }
2543
2544 window.with_element_opacity(style.opacity, |window| {
2545 style.paint(bounds, window, cx, |window: &mut Window, cx: &mut App| {
2546 window.with_text_style(style.text_style().cloned(), |window| {
2547 window.with_content_mask(
2548 style.overflow_mask(bounds, window.rem_size()),
2549 |window| {
2550 window.with_tab_group(tab_group, |window| {
2551 // Register the container's own focus handle *inside* its
2552 // tab group, so that focusing the container and then
2553 // calling `focus_next` descends into this group's first
2554 // item. Inserting it before `with_tab_group` would give the
2555 // container a shallower tab path than its children; with
2556 // sibling groups every container would then sort ahead of
2557 // every item, and `focus_next` from a container would jump
2558 // to the first item in the whole window instead of its own.
2559 if let Some(focus_handle) = &self.tracked_focus_handle {
2560 window.next_frame.tab_stops.insert(focus_handle);
2561 }
2562 if let Some(hitbox) = hitbox {
2563 #[cfg(debug_assertions)]
2564 self.paint_debug_info(
2565 global_id, hitbox, &style, window, cx,
2566 );
2567
2568 if let Some(drag) = cx.active_drag.as_ref() {
2569 if let Some(mouse_cursor) = drag.cursor_style {
2570 window.set_window_cursor_style(mouse_cursor);
2571 }
2572 } else {
2573 if let Some(mouse_cursor) = style.mouse_cursor {
2574 window.set_cursor_style(mouse_cursor, hitbox);
2575 }
2576 }
2577
2578 if let Some(group) = self.group.clone() {
2579 GroupHitboxes::push(group, hitbox.id, cx);
2580 }
2581
2582 if let Some(area) = self.window_control {
2583 window.insert_window_control_hitbox(
2584 area,
2585 hitbox.clone(),
2586 );
2587 }
2588
2589 self.paint_mouse_listeners(
2590 hitbox,
2591 element_state.as_mut(),
2592 window,
2593 cx,
2594 );
2595 self.paint_scroll_listener(hitbox, &style, window, cx);
2596 }
2597
2598 self.paint_keyboard_listeners(window, cx);
2599
2600 if window.a11y.is_active() {
2601 if let Some(global_id) = global_id {
2602 if !self.a11y_action_listeners.is_empty() {
2603 let node_id = global_id.accesskit_node_id();
2604 for (action, listener) in
2605 self.a11y_action_listeners.drain(..)
2606 {
2607 window.on_a11y_action(
2608 node_id, action, listener,
2609 );
2610 }
2611 }
2612 }
2613 }
2614
2615 f(&style, window, cx);
2616
2617 if let Some(_hitbox) = hitbox {
2618 #[cfg(any(feature = "inspector", debug_assertions))]
2619 window.insert_inspector_hitbox(
2620 _hitbox.id,
2621 _inspector_id,
2622 cx,
2623 );
2624
2625 if let Some(group) = self.group.as_ref() {
2626 GroupHitboxes::pop(group, cx);
2627 }
2628 }
2629 })
2630 },
2631 );
2632 });
2633 });
2634 });
2635
2636 ((), element_state)
2637 },
2638 );
2639 }
2640
2641 #[cfg(debug_assertions)]
2642 fn paint_debug_info(
2643 &self,
2644 global_id: Option<&GlobalElementId>,
2645 hitbox: &Hitbox,
2646 style: &Style,
2647 window: &mut Window,
2648 cx: &mut App,
2649 ) {
2650 use crate::{BorderStyle, TextAlign};
2651
2652 if let Some(global_id) = global_id
2653 && (style.debug || style.debug_below || cx.has_global::<crate::DebugBelow>())
2654 && hitbox.is_hovered(window)
2655 {
2656 const FONT_SIZE: crate::Pixels = crate::Pixels(10.);
2657 let element_id = format!("{global_id:?}");
2658 let str_len = element_id.len();
2659
2660 let render_debug_text = |window: &mut Window| {
2661 if let Some(text) = window
2662 .text_system()
2663 .shape_text(
2664 element_id.into(),
2665 FONT_SIZE,
2666 &[window.text_style().to_run(str_len)],
2667 None,
2668 None,
2669 )
2670 .ok()
2671 .and_then(|mut text| text.pop())
2672 {
2673 text.paint(hitbox.origin, FONT_SIZE, TextAlign::Left, None, window, cx)
2674 .ok();
2675
2676 let text_bounds = crate::Bounds {
2677 origin: hitbox.origin,
2678 size: text.size(FONT_SIZE),
2679 };
2680 if let Some(source_location) = self.source_location
2681 && text_bounds.contains(&window.mouse_position())
2682 && window.modifiers().secondary()
2683 {
2684 let secondary_held = window.modifiers().secondary();
2685 window.on_key_event({
2686 move |e: &crate::ModifiersChangedEvent, _phase, window, _cx| {
2687 if e.modifiers.secondary() != secondary_held
2688 && text_bounds.contains(&window.mouse_position())
2689 {
2690 window.refresh();
2691 }
2692 }
2693 });
2694
2695 let was_hovered = hitbox.is_hovered(window);
2696 let current_view = window.current_view();
2697 window.on_mouse_event({
2698 let hitbox = hitbox.clone();
2699 move |_: &MouseMoveEvent, phase, window, cx| {
2700 if phase == DispatchPhase::Capture {
2701 let hovered = hitbox.is_hovered(window);
2702 if hovered != was_hovered {
2703 cx.notify(current_view)
2704 }
2705 }
2706 }
2707 });
2708
2709 window.on_mouse_event({
2710 let hitbox = hitbox.clone();
2711 move |e: &crate::MouseDownEvent, phase, window, cx| {
2712 if text_bounds.contains(&e.position)
2713 && phase.capture()
2714 && hitbox.is_hovered(window)
2715 {
2716 cx.stop_propagation();
2717 let Ok(dir) = std::env::current_dir() else {
2718 return;
2719 };
2720
2721 eprintln!(
2722 "This element was created at:\n{}:{}:{}",
2723 dir.join(source_location.file()).to_string_lossy(),
2724 source_location.line(),
2725 source_location.column()
2726 );
2727 }
2728 }
2729 });
2730 window.paint_quad(crate::outline(
2731 crate::Bounds {
2732 origin: hitbox.origin
2733 + crate::point(crate::px(0.), FONT_SIZE - px(2.)),
2734 size: crate::Size {
2735 width: text_bounds.size.width,
2736 height: crate::px(1.),
2737 },
2738 },
2739 crate::red(),
2740 BorderStyle::default(),
2741 ))
2742 }
2743 }
2744 };
2745
2746 window.with_text_style(
2747 Some(crate::TextStyleRefinement {
2748 color: Some(crate::red()),
2749 line_height: Some(FONT_SIZE.into()),
2750 background_color: Some(crate::white()),
2751 ..Default::default()
2752 }),
2753 render_debug_text,
2754 )
2755 }
2756 }
2757
2758 fn paint_mouse_listeners(
2759 &mut self,
2760 hitbox: &Hitbox,
2761 element_state: Option<&mut InteractiveElementState>,
2762 window: &mut Window,
2763 cx: &mut App,
2764 ) {
2765 let is_focused = self
2766 .tracked_focus_handle
2767 .as_ref()
2768 .map(|handle| handle.is_focused(window))
2769 .unwrap_or(false);
2770
2771 // If this element can be focused, register a mouse down listener
2772 // that will automatically transfer focus when hitting the element.
2773 // This behavior can be suppressed by using `cx.prevent_default()`.
2774 if let Some(focus_handle) = self.tracked_focus_handle.clone() {
2775 let hitbox = hitbox.clone();
2776 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
2777 if phase == DispatchPhase::Bubble
2778 && hitbox.is_hovered(window)
2779 && !window.default_prevented()
2780 {
2781 window.focus(&focus_handle, cx);
2782 // If there is a parent that is also focusable, prevent it
2783 // from transferring focus because we already did so.
2784 window.prevent_default();
2785 }
2786 });
2787 }
2788
2789 for listener in self.mouse_down_listeners.drain(..) {
2790 let hitbox = hitbox.clone();
2791 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
2792 listener(event, phase, &hitbox, window, cx);
2793 })
2794 }
2795
2796 for listener in self.mouse_up_listeners.drain(..) {
2797 let hitbox = hitbox.clone();
2798 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
2799 listener(event, phase, &hitbox, window, cx);
2800 })
2801 }
2802
2803 for listener in self.mouse_pressure_listeners.drain(..) {
2804 let hitbox = hitbox.clone();
2805 window.on_mouse_event(move |event: &MousePressureEvent, phase, window, cx| {
2806 listener(event, phase, &hitbox, window, cx);
2807 })
2808 }
2809
2810 for listener in self.mouse_move_listeners.drain(..) {
2811 let hitbox = hitbox.clone();
2812 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
2813 listener(event, phase, &hitbox, window, cx);
2814 })
2815 }
2816
2817 for listener in self.mouse_exit_listeners.drain(..) {
2818 let hitbox = hitbox.clone();
2819 window.on_mouse_event(move |event: &MouseExitEvent, phase, window, cx| {
2820 listener(event, phase, &hitbox, window, cx);
2821 })
2822 }
2823
2824 for listener in self.file_drop_exit_listeners.drain(..) {
2825 let hitbox = hitbox.clone();
2826 window.on_mouse_event(move |event: &FileDropEvent, phase, window, cx| {
2827 listener(event, phase, &hitbox, window, cx);
2828 })
2829 }
2830
2831 for listener in self.scroll_wheel_listeners.drain(..) {
2832 let hitbox = hitbox.clone();
2833 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
2834 listener(event, phase, &hitbox, window, cx);
2835 })
2836 }
2837
2838 for listener in self.pinch_listeners.drain(..) {
2839 let hitbox = hitbox.clone();
2840 window.on_mouse_event(move |event: &PinchEvent, phase, window, cx| {
2841 listener(event, phase, &hitbox, window, cx);
2842 })
2843 }
2844
2845 if self.hover_style.is_some()
2846 || self.base_style.mouse_cursor.is_some()
2847 || cx.active_drag.is_some() && !self.drag_over_styles.is_empty()
2848 {
2849 let hitbox = hitbox.clone();
2850 let hover_state = self.hover_style.as_ref().and_then(|_| {
2851 element_state
2852 .as_ref()
2853 .and_then(|state| state.hover_state.as_ref())
2854 .cloned()
2855 });
2856 let current_view = window.current_view();
2857
2858 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2859 let hovered = hitbox.is_hovered(window);
2860 let was_hovered = hover_state
2861 .as_ref()
2862 .is_some_and(|state| state.borrow().element);
2863 if phase == DispatchPhase::Capture && hovered != was_hovered {
2864 if let Some(hover_state) = &hover_state {
2865 hover_state.borrow_mut().element = hovered;
2866 cx.notify(current_view);
2867 }
2868 }
2869 });
2870 }
2871
2872 if let Some(group_hover) = self.group_hover_style.as_ref() {
2873 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
2874 let hover_state = element_state
2875 .as_ref()
2876 .and_then(|element| element.hover_state.as_ref())
2877 .cloned();
2878 let current_view = window.current_view();
2879
2880 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
2881 let group_hovered = group_hitbox_id.is_hovered(window);
2882 let was_group_hovered = hover_state
2883 .as_ref()
2884 .is_some_and(|state| state.borrow().group);
2885 if phase == DispatchPhase::Capture && group_hovered != was_group_hovered {
2886 if let Some(hover_state) = &hover_state {
2887 hover_state.borrow_mut().group = group_hovered;
2888 cx.notify(current_view);
2889 }
2890 }
2891 });
2892 }
2893 }
2894
2895 let drag_cursor_style = self.base_style.as_ref().mouse_cursor;
2896
2897 let mut drag_listener = mem::take(&mut self.drag_listener);
2898 let drop_listeners = mem::take(&mut self.drop_listeners);
2899 let click_listeners = mem::take(&mut self.click_listeners);
2900 let aux_click_listeners = mem::take(&mut self.aux_click_listeners);
2901 let can_drop_predicate = mem::take(&mut self.can_drop_predicate);
2902
2903 if !drop_listeners.is_empty() {
2904 let hitbox = hitbox.clone();
2905 window.on_mouse_event({
2906 move |_: &MouseUpEvent, phase, window, cx| {
2907 if let Some(drag) = &cx.active_drag
2908 && phase == DispatchPhase::Bubble
2909 && hitbox.is_hovered(window)
2910 {
2911 let drag_state_type = drag.value.as_ref().type_id();
2912 for (drop_state_type, listener) in &drop_listeners {
2913 if *drop_state_type == drag_state_type {
2914 let drag = cx
2915 .active_drag
2916 .take()
2917 .expect("checked for type drag state type above");
2918
2919 let mut can_drop = true;
2920 if let Some(predicate) = &can_drop_predicate {
2921 can_drop = predicate(drag.value.as_ref(), window, cx);
2922 }
2923
2924 if can_drop {
2925 listener(drag.value.as_ref(), window, cx);
2926 window.refresh();
2927 cx.stop_propagation();
2928 }
2929 }
2930 }
2931 }
2932 }
2933 });
2934 }
2935
2936 if let Some(element_state) = element_state {
2937 if !click_listeners.is_empty()
2938 || !aux_click_listeners.is_empty()
2939 || drag_listener.is_some()
2940 {
2941 let pending_mouse_down = element_state
2942 .pending_mouse_down
2943 .get_or_insert_with(Default::default)
2944 .clone();
2945
2946 let pending_keyboard_down = element_state
2947 .pending_keyboard_down
2948 .get_or_insert_with(Default::default)
2949 .clone();
2950
2951 let clicked_state = element_state
2952 .clicked_state
2953 .get_or_insert_with(Default::default)
2954 .clone();
2955
2956 window.on_mouse_event({
2957 let pending_mouse_down = pending_mouse_down.clone();
2958 let hitbox = hitbox.clone();
2959 let has_aux_click_listeners = !aux_click_listeners.is_empty();
2960 move |event: &MouseDownEvent, phase, window, _cx| {
2961 if phase == DispatchPhase::Bubble
2962 && (event.button == MouseButton::Left || has_aux_click_listeners)
2963 && hitbox.is_hovered(window)
2964 {
2965 *pending_mouse_down.borrow_mut() = Some(event.clone());
2966 window.refresh();
2967 }
2968 }
2969 });
2970
2971 window.on_mouse_event({
2972 let pending_mouse_down = pending_mouse_down.clone();
2973 let hitbox = hitbox.clone();
2974 move |event: &MouseMoveEvent, phase, window, cx| {
2975 if phase == DispatchPhase::Capture {
2976 return;
2977 }
2978
2979 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
2980 if let Some(mouse_down) = pending_mouse_down.clone()
2981 && !cx.has_active_drag()
2982 && (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
2983 && let Some(listener) = drag_listener.take()
2984 && mouse_down.button == MouseButton::Left
2985 {
2986 *clicked_state.borrow_mut() = ElementClickedState::default();
2987 let cursor_offset = event.position - hitbox.origin;
2988 let drag = (listener.render)(
2989 listener.value.as_ref(),
2990 cursor_offset,
2991 window,
2992 cx,
2993 );
2994 let external_payload_source =
2995 listener.external_payload.map(|external_payload| {
2996 let value = listener.value.clone();
2997 Box::new(move |window: &mut Window, cx: &mut App| {
2998 external_payload(value.as_ref(), window, cx)
2999 })
3000 as ExternalDragPayloadSource
3001 });
3002 cx.active_drag = Some(AnyDrag {
3003 view: drag,
3004 value: listener.value,
3005 cursor_offset,
3006 cursor_style: drag_cursor_style,
3007 external_payload_source,
3008 });
3009 pending_mouse_down.take();
3010 window.refresh();
3011 cx.stop_propagation();
3012 }
3013 }
3014 });
3015
3016 if is_focused {
3017 // Record the focus generation at which an enter/space key
3018 // down event happened on this element. The next key up
3019 // event will be mapped to a click event if both of the
3020 // following are true:
3021 // - no other key events happen in between
3022 // - the focus generation is the same (implying focus did not move)
3023 //
3024 // This design avoids an ABA problem that happens if you
3025 // store the focus handle that registered the keypress.
3026 window.on_key_event({
3027 let pending_keyboard_down = pending_keyboard_down.clone();
3028 move |event: &KeyDownEvent, phase, window, _cx| {
3029 if phase.bubble() && !window.default_prevented() {
3030 let stroke = &event.keystroke;
3031 let is_activation_key = (stroke.key.eq("enter")
3032 || stroke.key.eq("space"))
3033 && !stroke.modifiers.modified();
3034 *pending_keyboard_down.borrow_mut() =
3035 is_activation_key.then_some(window.focus_generation);
3036 }
3037 }
3038 });
3039
3040 // Press enter, space to trigger click, when the element is focused.
3041 window.on_key_event({
3042 let click_listeners = click_listeners.clone();
3043 let hitbox = hitbox.clone();
3044 move |event: &KeyUpEvent, phase, window, cx| {
3045 if phase.bubble() && !window.default_prevented() {
3046 let stroke = &event.keystroke;
3047 let keyboard_button = if stroke.key.eq("enter") {
3048 Some(KeyboardButton::Enter)
3049 } else if stroke.key.eq("space") {
3050 Some(KeyboardButton::Space)
3051 } else {
3052 None
3053 };
3054
3055 if let Some(button) = keyboard_button
3056 && !stroke.modifiers.modified()
3057 {
3058 let pending =
3059 std::mem::take(&mut *pending_keyboard_down.borrow_mut());
3060 if pending != Some(window.focus_generation) {
3061 return;
3062 }
3063
3064 let click_event = ClickEvent::Keyboard(KeyboardClickEvent {
3065 button,
3066 bounds: hitbox.bounds,
3067 });
3068
3069 for listener in &click_listeners {
3070 listener(&click_event, window, cx);
3071 }
3072 } else {
3073 // Releasing any other key mid-press means
3074 // this isn't a clean activation, so cancel
3075 // the pending keydown.
3076 *pending_keyboard_down.borrow_mut() = None;
3077 }
3078 }
3079 }
3080 });
3081 }
3082
3083 window.on_mouse_event({
3084 let mut captured_mouse_down = None;
3085 let hitbox = hitbox.clone();
3086 move |event: &MouseUpEvent, phase, window, cx| match phase {
3087 // Clear the pending mouse down during the capture phase,
3088 // so that it happens even if another event handler stops
3089 // propagation.
3090 DispatchPhase::Capture => {
3091 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
3092 if pending_mouse_down.is_some() && hitbox.is_hovered(window) {
3093 captured_mouse_down = pending_mouse_down.take();
3094 window.refresh();
3095 } else if pending_mouse_down.is_some() {
3096 // Clear the pending mouse down event (without firing click handlers)
3097 // if the hitbox is not being hovered.
3098 // This avoids dragging elements that changed their position
3099 // immediately after being clicked.
3100 // See https://github.com/zed-industries/zed/issues/24600 for more details
3101 pending_mouse_down.take();
3102 window.refresh();
3103 }
3104 }
3105 // Fire click handlers during the bubble phase.
3106 DispatchPhase::Bubble => {
3107 if let Some(mouse_down) = captured_mouse_down.take() {
3108 let btn = mouse_down.button;
3109
3110 let mouse_click = ClickEvent::Mouse(MouseClickEvent {
3111 down: mouse_down,
3112 up: event.clone(),
3113 });
3114
3115 match btn {
3116 MouseButton::Left => {
3117 for listener in &click_listeners {
3118 listener(&mouse_click, window, cx);
3119 }
3120 }
3121 _ => {
3122 for listener in &aux_click_listeners {
3123 listener(&mouse_click, window, cx);
3124 }
3125 }
3126 }
3127 }
3128 }
3129 }
3130 });
3131 }
3132
3133 if let Some(hover_listener) = self.hover_listener.take() {
3134 let was_hovered = element_state
3135 .hover_listener_state
3136 .get_or_insert_with(Default::default)
3137 .clone();
3138 let has_mouse_down = element_state
3139 .pending_mouse_down
3140 .get_or_insert_with(Default::default)
3141 .clone();
3142 let hover_listener = Rc::new(hover_listener);
3143 let hover_listener_state = was_hovered.clone();
3144 let update_hover = move |is_hovered: bool, window: &mut Window, cx: &mut App| {
3145 let mut was_hovered = hover_listener_state.borrow_mut();
3146 if is_hovered != *was_hovered {
3147 *was_hovered = is_hovered;
3148 drop(was_hovered);
3149 hover_listener(&is_hovered, window, cx);
3150 }
3151 };
3152 let hover_listener_mode = self.hover_listener_mode;
3153
3154 if has_mouse_down.borrow().is_none() {
3155 let is_hovered =
3156 !cx.has_active_drag() && hover_listener_mode.is_hovered(hitbox, window);
3157 if is_hovered != *was_hovered.borrow() {
3158 let update_hover = update_hover.clone();
3159 window.defer(cx, move |window, cx| {
3160 update_hover(is_hovered, window, cx);
3161 });
3162 }
3163 }
3164
3165 window.on_mouse_event({
3166 let update_hover = update_hover.clone();
3167 let hitbox = hitbox.clone();
3168 move |_: &MouseMoveEvent, phase, window, cx| {
3169 if phase == DispatchPhase::Bubble {
3170 let is_hovered = has_mouse_down.borrow().is_none()
3171 && !cx.has_active_drag()
3172 && hover_listener_mode.is_hovered(&hitbox, window);
3173 update_hover(is_hovered, window, cx);
3174 }
3175 }
3176 });
3177
3178 // The pointer can leave the window without a final MouseMove, so also
3179 // clear hover on MouseExited.
3180 window.on_mouse_event(move |_: &MouseExitEvent, phase, window, cx| {
3181 if phase == DispatchPhase::Bubble {
3182 update_hover(false, window, cx);
3183 }
3184 });
3185 }
3186
3187 if let Some(tooltip_builder) = self.tooltip_builder.take() {
3188 let active_tooltip = element_state
3189 .active_tooltip
3190 .get_or_insert_with(Default::default)
3191 .clone();
3192 let pending_mouse_down = element_state
3193 .pending_mouse_down
3194 .get_or_insert_with(Default::default)
3195 .clone();
3196 let long_press_tooltip_active = element_state
3197 .long_press_tooltip_active
3198 .get_or_insert_with(Default::default)
3199 .clone();
3200
3201 let tooltip_is_hoverable = tooltip_builder.hoverable;
3202 let build_tooltip = Rc::new(move |window: &mut Window, cx: &mut App| {
3203 Some(((tooltip_builder.build)(window, cx), tooltip_is_hoverable))
3204 });
3205 // Use bounds instead of testing hitbox since this is called during prepaint.
3206 let check_is_hovered_during_prepaint = Rc::new({
3207 let pending_mouse_down = pending_mouse_down.clone();
3208 let source_bounds = hitbox.bounds;
3209 move |window: &Window| {
3210 !window.last_input_was_keyboard()
3211 && pending_mouse_down.borrow().is_none()
3212 && source_bounds.contains(&window.mouse_position())
3213 }
3214 });
3215 let check_is_hovered = Rc::new({
3216 let hitbox = hitbox.clone();
3217 move |window: &Window| {
3218 pending_mouse_down.borrow().is_none() && hitbox.is_hovered(window)
3219 }
3220 });
3221 register_tooltip_mouse_handlers(
3222 &active_tooltip,
3223 self.tooltip_id,
3224 build_tooltip,
3225 check_is_hovered,
3226 check_is_hovered_during_prepaint,
3227 long_press_tooltip_active,
3228 self.tooltip_show_delay,
3229 window,
3230 );
3231 }
3232
3233 // We unconditionally bind both the mouse up and mouse down active state handlers
3234 // Because we might not get a chance to render a frame before the mouse up event arrives.
3235 let active_state = element_state
3236 .clicked_state
3237 .get_or_insert_with(Default::default)
3238 .clone();
3239
3240 {
3241 let active_state = active_state.clone();
3242 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, _cx| {
3243 if phase == DispatchPhase::Capture && active_state.borrow().is_clicked() {
3244 *active_state.borrow_mut() = ElementClickedState::default();
3245 window.refresh();
3246 }
3247 });
3248 }
3249
3250 {
3251 let active_group_hitbox = self
3252 .group_active_style
3253 .as_ref()
3254 .and_then(|group_active| GroupHitboxes::get(&group_active.group, cx));
3255 let hitbox = hitbox.clone();
3256 window.on_mouse_event(move |_: &MouseDownEvent, phase, window, _cx| {
3257 if phase == DispatchPhase::Bubble && !window.default_prevented() {
3258 let group_hovered = active_group_hitbox
3259 .is_some_and(|group_hitbox_id| group_hitbox_id.is_hovered(window));
3260 let element_hovered = hitbox.is_hovered(window);
3261 if group_hovered || element_hovered {
3262 *active_state.borrow_mut() = ElementClickedState {
3263 group: group_hovered,
3264 element: element_hovered,
3265 };
3266 window.refresh();
3267 }
3268 }
3269 });
3270 }
3271 }
3272 }
3273
3274 fn paint_keyboard_listeners(&mut self, window: &mut Window, _cx: &mut App) {
3275 let key_down_listeners = mem::take(&mut self.key_down_listeners);
3276 let key_up_listeners = mem::take(&mut self.key_up_listeners);
3277 let modifiers_changed_listeners = mem::take(&mut self.modifiers_changed_listeners);
3278 let action_listeners = mem::take(&mut self.action_listeners);
3279 if let Some(context) = self.key_context.clone() {
3280 window.set_key_context(context);
3281 }
3282
3283 for listener in key_down_listeners {
3284 window.on_key_event(move |event: &KeyDownEvent, phase, window, cx| {
3285 listener(event, phase, window, cx);
3286 })
3287 }
3288
3289 for listener in key_up_listeners {
3290 window.on_key_event(move |event: &KeyUpEvent, phase, window, cx| {
3291 listener(event, phase, window, cx);
3292 })
3293 }
3294
3295 for listener in modifiers_changed_listeners {
3296 window.on_modifiers_changed(move |event: &ModifiersChangedEvent, window, cx| {
3297 listener(event, window, cx);
3298 })
3299 }
3300
3301 for (action_type, listener) in action_listeners {
3302 window.on_action(action_type, listener)
3303 }
3304 }
3305
3306 fn paint_hover_group_handler(&self, window: &mut Window, cx: &mut App) {
3307 let group_hitbox = self
3308 .group_hover_style
3309 .as_ref()
3310 .and_then(|group_hover| GroupHitboxes::get(&group_hover.group, cx));
3311
3312 if let Some(group_hitbox) = group_hitbox {
3313 let was_hovered = group_hitbox.is_hovered(window);
3314 let current_view = window.current_view();
3315 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
3316 let hovered = group_hitbox.is_hovered(window);
3317 if phase == DispatchPhase::Capture && hovered != was_hovered {
3318 cx.notify(current_view);
3319 }
3320 });
3321 }
3322 }
3323
3324 fn paint_scroll_listener(
3325 &self,
3326 hitbox: &Hitbox,
3327 style: &Style,
3328 window: &mut Window,
3329 _cx: &mut App,
3330 ) {
3331 if let Some(scroll_offset) = self.scroll_offset.clone() {
3332 let ongoing_scroll = self.ongoing_scroll.clone();
3333 let overflow = style.overflow;
3334 let allow_concurrent_scroll = style.allow_concurrent_scroll;
3335 let restrict_scroll_to_axis = style.restrict_scroll_to_axis;
3336 let line_height = window.line_height();
3337 let hitbox = hitbox.clone();
3338 let current_view = window.current_view();
3339 window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
3340 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
3341 let mut scroll_offset = scroll_offset.borrow_mut();
3342 let old_scroll_offset = *scroll_offset;
3343 let mut delta = event.delta.pixel_delta(line_height);
3344
3345 if restrict_scroll_to_axis
3346 && event.delta.precise()
3347 && let Some(ongoing_scroll) = &ongoing_scroll
3348 {
3349 ongoing_scroll
3350 .borrow_mut()
3351 .filter(&mut delta, event.touch_phase);
3352 }
3353
3354 let mut delta_x = match overflow.x {
3355 Overflow::Scroll if !delta.x.is_zero() => delta.x,
3356 Overflow::Scroll
3357 if !restrict_scroll_to_axis && overflow.y != Overflow::Scroll =>
3358 {
3359 delta.y
3360 }
3361 _ => Pixels::ZERO,
3362 };
3363 let mut delta_y = match overflow.y {
3364 Overflow::Scroll if !delta.y.is_zero() => delta.y,
3365 Overflow::Scroll
3366 if !restrict_scroll_to_axis && overflow.x != Overflow::Scroll =>
3367 {
3368 delta.x
3369 }
3370 _ => Pixels::ZERO,
3371 };
3372 if !allow_concurrent_scroll && !delta_x.is_zero() && !delta_y.is_zero() {
3373 if delta_x.abs() > delta_y.abs() {
3374 delta_y = Pixels::ZERO;
3375 } else {
3376 delta_x = Pixels::ZERO;
3377 }
3378 }
3379 scroll_offset.y += delta_y;
3380 scroll_offset.x += delta_x;
3381 if *scroll_offset != old_scroll_offset {
3382 cx.notify(current_view);
3383 }
3384 }
3385 });
3386 }
3387 }
3388
3389 /// Compute the visual style for this element, based on the current bounds and the element's state.
3390 pub fn compute_style(
3391 &self,
3392 global_id: Option<&GlobalElementId>,
3393 hitbox: Option<&Hitbox>,
3394 window: &mut Window,
3395 cx: &mut App,
3396 ) -> Style {
3397 window.with_optional_element_state(global_id, |element_state, window| {
3398 let mut element_state =
3399 element_state.map(|element_state| element_state.unwrap_or_default());
3400 let style = self.compute_style_internal(hitbox, element_state.as_mut(), window, cx);
3401 (style, element_state)
3402 })
3403 }
3404
3405 /// Called from internal methods that have already called with_element_state.
3406 fn compute_style_internal(
3407 &self,
3408 hitbox: Option<&Hitbox>,
3409 element_state: Option<&mut InteractiveElementState>,
3410 window: &mut Window,
3411 cx: &mut App,
3412 ) -> Style {
3413 let mut style = Style::default();
3414 style.refine(&self.base_style);
3415
3416 if let Some(focus_handle) = self.tracked_focus_handle.as_ref() {
3417 if let Some(in_focus_style) = self.in_focus_style.as_ref()
3418 && focus_handle.within_focused(window, cx)
3419 {
3420 style.refine(in_focus_style);
3421 }
3422
3423 if let Some(focus_style) = self.focus_style.as_ref()
3424 && focus_handle.is_focused(window)
3425 {
3426 style.refine(focus_style);
3427 }
3428
3429 if let Some(focus_visible_style) = self.focus_visible_style.as_ref()
3430 && focus_handle.is_focused(window)
3431 && window.last_input_was_keyboard()
3432 {
3433 style.refine(focus_visible_style);
3434 }
3435 }
3436
3437 if !cx.has_active_drag() {
3438 if let Some(group_hover) = self.group_hover_style.as_ref() {
3439 let is_group_hovered =
3440 if let Some(group_hitbox_id) = GroupHitboxes::get(&group_hover.group, cx) {
3441 !window.last_input_was_touch() && group_hitbox_id.is_hovered(window)
3442 } else if let Some(element_state) = element_state.as_ref() {
3443 !window.last_input_was_touch()
3444 && element_state
3445 .hover_state
3446 .as_ref()
3447 .map(|state| state.borrow().group)
3448 .unwrap_or(false)
3449 } else {
3450 false
3451 };
3452
3453 if is_group_hovered {
3454 style.refine(&group_hover.style);
3455 }
3456 }
3457
3458 if let Some(hover_style) = self.hover_style.as_ref() {
3459 let is_hovered = if let Some(hitbox) = hitbox {
3460 !window.last_input_was_touch() && hitbox.is_hovered(window)
3461 } else if let Some(element_state) = element_state.as_ref() {
3462 !window.last_input_was_touch()
3463 && element_state
3464 .hover_state
3465 .as_ref()
3466 .map(|state| state.borrow().element)
3467 .unwrap_or(false)
3468 } else {
3469 false
3470 };
3471
3472 if is_hovered {
3473 style.refine(hover_style);
3474 }
3475 }
3476 }
3477
3478 if let Some(hitbox) = hitbox {
3479 if let Some(drag) = cx.active_drag.take() {
3480 let mut can_drop = true;
3481 if let Some(can_drop_predicate) = &self.can_drop_predicate {
3482 can_drop = can_drop_predicate(drag.value.as_ref(), window, cx);
3483 }
3484
3485 if can_drop {
3486 for (state_type, group_drag_style) in &self.group_drag_over_styles {
3487 if let Some(group_hitbox_id) =
3488 GroupHitboxes::get(&group_drag_style.group, cx)
3489 && *state_type == drag.value.as_ref().type_id()
3490 && group_hitbox_id.is_hovered(window)
3491 {
3492 style.refine(&group_drag_style.style);
3493 }
3494 }
3495
3496 for (state_type, build_drag_over_style) in &self.drag_over_styles {
3497 if *state_type == drag.value.as_ref().type_id() && hitbox.is_hovered(window)
3498 {
3499 style.refine(&build_drag_over_style(drag.value.as_ref(), window, cx));
3500 }
3501 }
3502 }
3503
3504 style.mouse_cursor = drag.cursor_style;
3505 cx.active_drag = Some(drag);
3506 }
3507 }
3508
3509 if let Some(element_state) = element_state {
3510 let clicked_state = element_state
3511 .clicked_state
3512 .get_or_insert_with(Default::default)
3513 .borrow();
3514 if clicked_state.group
3515 && let Some(group) = self.group_active_style.as_ref()
3516 {
3517 style.refine(&group.style)
3518 }
3519
3520 if let Some(active_style) = self.active_style.as_ref()
3521 && clicked_state.element
3522 {
3523 style.refine(active_style)
3524 }
3525 }
3526
3527 style
3528 }
3529
3530 pub(crate) fn write_a11y_info(&self, node: &mut accesskit::Node) {
3531 if let Some(id) = &self.aria.author_id {
3532 node.set_author_id(id.to_string());
3533 }
3534 if let Some(label) = &self.aria.label {
3535 node.set_label(label.to_string());
3536 }
3537 if let Some(description) = &self.aria.description {
3538 node.set_description(description.to_string());
3539 }
3540 if let Some(keyshortcuts) = &self.aria.keyshortcuts {
3541 node.set_keyboard_shortcut(keyshortcuts.to_string());
3542 }
3543 if let Some(selected) = self.aria.selected {
3544 node.set_selected(selected);
3545 }
3546 if let Some(expanded) = self.aria.expanded {
3547 node.set_expanded(expanded);
3548 }
3549 if let Some(toggled) = self.aria.toggled {
3550 node.set_toggled(toggled);
3551 }
3552 if let Some(value) = self.aria.numeric_value {
3553 node.set_numeric_value(value);
3554 }
3555 if let Some(value) = self.aria.min_numeric_value {
3556 node.set_min_numeric_value(value);
3557 }
3558 if let Some(value) = self.aria.max_numeric_value {
3559 node.set_max_numeric_value(value);
3560 }
3561 if let Some(step) = self.aria.numeric_value_step {
3562 node.set_numeric_value_step(step);
3563 }
3564 if let Some(value) = &self.aria.value {
3565 node.set_value(value.to_string());
3566 }
3567 if let Some(placeholder) = &self.aria.placeholder {
3568 node.set_placeholder(placeholder.to_string());
3569 }
3570 if let Some(orientation) = self.aria.orientation {
3571 node.set_orientation(orientation);
3572 }
3573 if let Some(level) = self.aria.level {
3574 node.set_level(level);
3575 }
3576 if let Some(position) = self.aria.position_in_set {
3577 node.set_position_in_set(position);
3578 }
3579 if let Some(size) = self.aria.size_of_set {
3580 node.set_size_of_set(size);
3581 }
3582 if let Some(index) = self.aria.row_index {
3583 node.set_row_index(index);
3584 }
3585 if let Some(index) = self.aria.column_index {
3586 node.set_column_index(index);
3587 }
3588 if let Some(count) = self.aria.row_count {
3589 node.set_row_count(count);
3590 }
3591 if let Some(count) = self.aria.column_count {
3592 node.set_column_count(count);
3593 }
3594 if !self.click_listeners.is_empty() {
3595 node.add_action(accesskit::Action::Click);
3596 }
3597 if self.tracked_focus_handle.is_some() || self.focusable {
3598 node.add_action(accesskit::Action::Focus);
3599 }
3600 for (action, _) in &self.a11y_action_listeners {
3601 node.add_action(*action);
3602 }
3603 }
3604}
3605
3606/// The per-frame state of an interactive element. Used for tracking stateful interactions like clicks
3607/// and scroll offsets.
3608#[derive(Default)]
3609pub struct InteractiveElementState {
3610 pub(crate) focus_handle: Option<FocusHandle>,
3611 pub(crate) clicked_state: Option<Rc<RefCell<ElementClickedState>>>,
3612 pub(crate) hover_state: Option<Rc<RefCell<ElementHoverState>>>,
3613 pub(crate) hover_listener_state: Option<Rc<RefCell<bool>>>,
3614 pub(crate) pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
3615 /// Set to the window's [`focus_generation`](crate::Window::focus_generation)
3616 /// when an Enter/Space keydown is received while this element is focused,
3617 /// recording that we are waiting for the matching keyup to fire a keyboard
3618 /// click. On keyup the click only fires if the stored generation still
3619 /// matches the window's current one, i.e. focus never moved during the
3620 /// press (mirroring the browser clearing a control's pressed state on
3621 /// blur). `None` means no activation key is pending.
3622 pub(crate) pending_keyboard_down: Option<Rc<RefCell<Option<u64>>>>,
3623 pub(crate) scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
3624 ongoing_scroll: Option<Rc<RefCell<OngoingScroll>>>,
3625 pub(crate) active_tooltip: Option<Rc<RefCell<Option<ActiveTooltip>>>>,
3626 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3627}
3628
3629/// Whether or not the element or a group that contains it is clicked by the mouse.
3630#[derive(Copy, Clone, Default, Eq, PartialEq)]
3631pub struct ElementClickedState {
3632 /// True if this element's group has been clicked, false otherwise
3633 pub group: bool,
3634
3635 /// True if this element has been clicked, false otherwise
3636 pub element: bool,
3637}
3638
3639impl ElementClickedState {
3640 fn is_clicked(&self) -> bool {
3641 self.group || self.element
3642 }
3643}
3644
3645/// Whether or not the element or a group that contains it is hovered.
3646#[derive(Copy, Clone, Default, Eq, PartialEq)]
3647pub struct ElementHoverState {
3648 /// True if this element's group is hovered, false otherwise
3649 pub group: bool,
3650
3651 /// True if this element is hovered, false otherwise
3652 pub element: bool,
3653}
3654
3655/// The tooltip state an element keeps between frames. Public so custom elements can show a
3656/// tooltip over part of their content with [register_tooltip_mouse_handlers].
3657#[allow(missing_docs)]
3658pub enum ActiveTooltip {
3659 /// Currently delaying before showing the tooltip.
3660 WaitingForShow { _task: Task<()> },
3661 /// Tooltip is visible, element was hovered or for hoverable tooltips, the tooltip was hovered.
3662 Visible {
3663 tooltip: AnyTooltip,
3664 is_hoverable: bool,
3665 },
3666 /// Tooltip is visible and hoverable, but the mouse is no longer hovering. Currently delaying
3667 /// before hiding it.
3668 WaitingForHide {
3669 tooltip: AnyTooltip,
3670 _task: Task<()>,
3671 },
3672}
3673
3674pub(crate) fn clear_active_tooltip(
3675 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3676 window: &mut Window,
3677) {
3678 match active_tooltip.borrow_mut().take() {
3679 None => {}
3680 Some(ActiveTooltip::WaitingForShow { .. }) => {}
3681 Some(ActiveTooltip::Visible { .. }) => window.refresh(),
3682 Some(ActiveTooltip::WaitingForHide { .. }) => window.refresh(),
3683 }
3684}
3685
3686pub(crate) fn clear_active_tooltip_if_not_hoverable(
3687 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3688 window: &mut Window,
3689) {
3690 let should_clear = match active_tooltip.borrow().as_ref() {
3691 None => false,
3692 Some(ActiveTooltip::WaitingForShow { .. }) => false,
3693 Some(ActiveTooltip::Visible { is_hoverable, .. }) => !is_hoverable,
3694 Some(ActiveTooltip::WaitingForHide { .. }) => false,
3695 };
3696 if should_clear {
3697 active_tooltip.borrow_mut().take();
3698 window.refresh();
3699 }
3700}
3701
3702/// Puts a visible tooltip on the window. Call it from a custom element's prepaint.
3703pub fn set_tooltip_on_window(
3704 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3705 window: &mut Window,
3706) -> Option<TooltipId> {
3707 let tooltip = match active_tooltip.borrow().as_ref() {
3708 None => return None,
3709 Some(ActiveTooltip::WaitingForShow { .. }) => return None,
3710 Some(ActiveTooltip::Visible { tooltip, .. }) => tooltip.clone(),
3711 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => tooltip.clone(),
3712 };
3713 Some(window.set_tooltip(tooltip))
3714}
3715
3716/// Shows and hides a tooltip as the mouse moves, after the usual delay. Call it from a custom
3717/// element's paint, with the id [set_tooltip_on_window] returned in prepaint.
3718#[allow(clippy::too_many_arguments)]
3719pub fn register_tooltip_mouse_handlers(
3720 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3721 tooltip_id: Option<TooltipId>,
3722 build_tooltip: Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3723 check_is_hovered: Rc<dyn Fn(&Window) -> bool>,
3724 check_is_hovered_during_prepaint: Rc<dyn Fn(&Window) -> bool>,
3725 long_press_tooltip_active: Rc<Cell<bool>>,
3726 show_delay: Option<Duration>,
3727 window: &mut Window,
3728) {
3729 let current_view = window.current_view();
3730 let show_delay = show_delay.unwrap_or(DEFAULT_TOOLTIP_SHOW_DELAY);
3731
3732 window.on_mouse_event({
3733 let active_tooltip = active_tooltip.clone();
3734 let build_tooltip = build_tooltip.clone();
3735 let check_is_hovered = check_is_hovered.clone();
3736 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3737 move |_: &MouseMoveEvent, phase, window, cx| {
3738 handle_tooltip_mouse_move(
3739 &active_tooltip,
3740 &build_tooltip,
3741 &check_is_hovered,
3742 &check_is_hovered_during_prepaint,
3743 tooltip_id,
3744 current_view,
3745 phase,
3746 show_delay,
3747 window,
3748 cx,
3749 )
3750 }
3751 });
3752
3753 window.on_mouse_event({
3754 let active_tooltip = active_tooltip.clone();
3755 move |_: &MouseDownEvent, _phase, window: &mut Window, _cx| {
3756 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3757 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3758 }
3759 }
3760 });
3761
3762 window.on_mouse_event({
3763 let active_tooltip = active_tooltip.clone();
3764 let build_tooltip = build_tooltip.clone();
3765 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3766 move |event: &LongPressEvent, phase, window, cx| {
3767 if !phase.bubble() {
3768 return;
3769 }
3770
3771 match event.phase {
3772 TouchPhase::Started if !window.default_prevented() && check_is_hovered(window) => {
3773 if show_tooltip(
3774 &active_tooltip,
3775 &build_tooltip,
3776 &check_is_hovered_during_prepaint,
3777 Some(long_press_tooltip_active.clone()),
3778 window,
3779 cx,
3780 ) {
3781 long_press_tooltip_active.set(true);
3782 window.prevent_default();
3783 cx.stop_propagation();
3784 }
3785 }
3786 TouchPhase::Ended | TouchPhase::Cancelled
3787 if long_press_tooltip_active.replace(false) =>
3788 {
3789 clear_active_tooltip(&active_tooltip, window);
3790 cx.stop_propagation();
3791 }
3792 TouchPhase::Started
3793 | TouchPhase::Moved
3794 | TouchPhase::Ended
3795 | TouchPhase::Cancelled => {}
3796 }
3797 }
3798 });
3799
3800 window.on_mouse_event({
3801 let active_tooltip = active_tooltip.clone();
3802 move |_: &ScrollWheelEvent, _phase, window: &mut Window, _cx| {
3803 if !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)) {
3804 clear_active_tooltip_if_not_hoverable(&active_tooltip, window);
3805 }
3806 }
3807 });
3808}
3809
3810/// Handles displaying tooltips when an element is hovered.
3811///
3812/// The mouse hovering logic also relies on being called from window prepaint in order to handle the
3813/// case where the element the tooltip is on is not rendered - in that case its mouse listeners are
3814/// also not registered. During window prepaint, the hitbox information is not available, so
3815/// `check_is_hovered_during_prepaint` is used which bases the check off of the absolute bounds of
3816/// the element.
3817///
3818/// TODO: There's a minor bug due to the use of absolute bounds while checking during prepaint - it
3819/// does not know if the hitbox is occluded. In the case where a tooltip gets displayed and then
3820/// gets occluded after display, it will stick around until the mouse exits the hover bounds.
3821fn handle_tooltip_mouse_move(
3822 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3823 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3824 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3825 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3826 tooltip_id: Option<TooltipId>,
3827 current_view: EntityId,
3828 phase: DispatchPhase,
3829 show_delay: Duration,
3830 window: &mut Window,
3831 cx: &mut App,
3832) {
3833 // Separates logic for what mutation should occur from applying it, to avoid overlapping
3834 // RefCell borrows.
3835 enum Action {
3836 None,
3837 CancelShow,
3838 ScheduleShow,
3839 CheckVisible,
3840 }
3841
3842 let action = match active_tooltip.borrow().as_ref() {
3843 None => {
3844 let is_hovered = check_is_hovered(window);
3845 if is_hovered && phase.bubble() {
3846 Action::ScheduleShow
3847 } else {
3848 Action::None
3849 }
3850 }
3851 Some(ActiveTooltip::WaitingForShow { .. }) => {
3852 let is_hovered = check_is_hovered(window);
3853 if is_hovered {
3854 Action::None
3855 } else {
3856 Action::CancelShow
3857 }
3858 }
3859 Some(ActiveTooltip::Visible { is_hoverable, .. }) => {
3860 if phase.capture()
3861 && !check_is_hovered(window)
3862 && (!*is_hoverable
3863 || !tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3864 {
3865 Action::CheckVisible
3866 } else {
3867 Action::None
3868 }
3869 }
3870 Some(ActiveTooltip::WaitingForHide { .. }) => {
3871 if phase.capture()
3872 && (check_is_hovered(window)
3873 || tooltip_id.is_some_and(|tooltip_id| tooltip_id.is_hovered(window)))
3874 {
3875 Action::CheckVisible
3876 } else {
3877 Action::None
3878 }
3879 }
3880 };
3881
3882 match action {
3883 Action::None => {}
3884 Action::CancelShow => {
3885 // Cancel waiting to show tooltip when it is no longer hovered.
3886 active_tooltip.borrow_mut().take();
3887 }
3888 Action::ScheduleShow => {
3889 let delayed_show_task = window.spawn(cx, {
3890 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3891 let build_tooltip = build_tooltip.clone();
3892 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3893 async move |cx| {
3894 cx.background_executor().timer(show_delay).await;
3895 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3896 return;
3897 };
3898 cx.update(|window, cx| {
3899 show_tooltip(
3900 &active_tooltip,
3901 &build_tooltip,
3902 &check_is_hovered_during_prepaint,
3903 None,
3904 window,
3905 cx,
3906 );
3907 })
3908 .ok();
3909 }
3910 });
3911 active_tooltip
3912 .borrow_mut()
3913 .replace(ActiveTooltip::WaitingForShow {
3914 _task: delayed_show_task,
3915 });
3916 }
3917 Action::CheckVisible => cx.notify(current_view),
3918 }
3919}
3920
3921fn show_tooltip(
3922 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3923 build_tooltip: &Rc<dyn Fn(&mut Window, &mut App) -> Option<(AnyView, bool)>>,
3924 check_is_hovered_during_prepaint: &Rc<dyn Fn(&Window) -> bool>,
3925 long_press_tooltip_active: Option<Rc<Cell<bool>>>,
3926 window: &mut Window,
3927 cx: &mut App,
3928) -> bool {
3929 let new_tooltip = build_tooltip(window, cx).map(|(view, tooltip_is_hoverable)| {
3930 let weak_active_tooltip = Rc::downgrade(active_tooltip);
3931 let check_is_hovered_during_prepaint = check_is_hovered_during_prepaint.clone();
3932 ActiveTooltip::Visible {
3933 tooltip: AnyTooltip {
3934 view,
3935 mouse_position: window.mouse_position(),
3936 check_visible_and_update: Rc::new(move |tooltip_bounds, window, cx| {
3937 if long_press_tooltip_active
3938 .as_ref()
3939 .is_some_and(|active| active.get())
3940 {
3941 return true;
3942 }
3943 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
3944 return false;
3945 };
3946 handle_tooltip_check_visible_and_update(
3947 &active_tooltip,
3948 tooltip_is_hoverable,
3949 &check_is_hovered_during_prepaint,
3950 tooltip_bounds,
3951 window,
3952 cx,
3953 )
3954 }),
3955 },
3956 is_hoverable: tooltip_is_hoverable,
3957 }
3958 });
3959 let did_show = new_tooltip.is_some();
3960 *active_tooltip.borrow_mut() = new_tooltip;
3961 window.refresh();
3962 did_show
3963}
3964
3965/// Returns a callback which will be called by window prepaint to update tooltip visibility. The
3966/// purpose of doing this logic here instead of the mouse move handler is that the mouse move
3967/// handler won't get called when the element is not painted (e.g. via use of `visible_on_hover`).
3968fn handle_tooltip_check_visible_and_update(
3969 active_tooltip: &Rc<RefCell<Option<ActiveTooltip>>>,
3970 tooltip_is_hoverable: bool,
3971 check_is_hovered: &Rc<dyn Fn(&Window) -> bool>,
3972 tooltip_bounds: Bounds<Pixels>,
3973 window: &mut Window,
3974 cx: &mut App,
3975) -> bool {
3976 // Separates logic for what mutation should occur from applying it, to avoid overlapping RefCell
3977 // borrows.
3978 enum Action {
3979 None,
3980 Hide,
3981 ScheduleHide(AnyTooltip),
3982 CancelHide(AnyTooltip),
3983 }
3984
3985 let is_hovered = check_is_hovered(window)
3986 || (tooltip_is_hoverable && tooltip_bounds.contains(&window.mouse_position()));
3987 let action = match active_tooltip.borrow().as_ref() {
3988 Some(ActiveTooltip::Visible { tooltip, .. }) => {
3989 if is_hovered {
3990 Action::None
3991 } else {
3992 if tooltip_is_hoverable {
3993 Action::ScheduleHide(tooltip.clone())
3994 } else {
3995 Action::Hide
3996 }
3997 }
3998 }
3999 Some(ActiveTooltip::WaitingForHide { tooltip, .. }) => {
4000 if is_hovered {
4001 Action::CancelHide(tooltip.clone())
4002 } else {
4003 Action::None
4004 }
4005 }
4006 None | Some(ActiveTooltip::WaitingForShow { .. }) => Action::None,
4007 };
4008
4009 match action {
4010 Action::None => {}
4011 Action::Hide => clear_active_tooltip(active_tooltip, window),
4012 Action::ScheduleHide(tooltip) => {
4013 let delayed_hide_task = window.spawn(cx, {
4014 let weak_active_tooltip = Rc::downgrade(active_tooltip);
4015 async move |cx| {
4016 cx.background_executor()
4017 .timer(HOVERABLE_TOOLTIP_HIDE_DELAY)
4018 .await;
4019 let Some(active_tooltip) = weak_active_tooltip.upgrade() else {
4020 return;
4021 };
4022 if active_tooltip.borrow_mut().take().is_some() {
4023 cx.update(|window, _cx| window.refresh()).ok();
4024 }
4025 }
4026 });
4027 active_tooltip
4028 .borrow_mut()
4029 .replace(ActiveTooltip::WaitingForHide {
4030 tooltip,
4031 _task: delayed_hide_task,
4032 });
4033 }
4034 Action::CancelHide(tooltip) => {
4035 // Cancel waiting to hide tooltip when it becomes hovered.
4036 active_tooltip.borrow_mut().replace(ActiveTooltip::Visible {
4037 tooltip,
4038 is_hoverable: true,
4039 });
4040 }
4041 }
4042
4043 active_tooltip.borrow().is_some()
4044}
4045
4046#[derive(Default)]
4047pub(crate) struct GroupHitboxes(HashMap<SharedString, SmallVec<[HitboxId; 1]>>);
4048
4049impl Global for GroupHitboxes {}
4050
4051impl GroupHitboxes {
4052 pub fn get(name: &SharedString, cx: &mut App) -> Option<HitboxId> {
4053 cx.default_global::<Self>()
4054 .0
4055 .get(name)
4056 .and_then(|bounds_stack| bounds_stack.last())
4057 .cloned()
4058 }
4059
4060 pub fn push(name: SharedString, hitbox_id: HitboxId, cx: &mut App) {
4061 cx.default_global::<Self>()
4062 .0
4063 .entry(name)
4064 .or_default()
4065 .push(hitbox_id);
4066 }
4067
4068 pub fn pop(name: &SharedString, cx: &mut App) {
4069 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
4070 }
4071}
4072
4073/// A wrapper around an element that can store state, produced after assigning an ElementId.
4074pub struct Stateful<E> {
4075 pub(crate) element: E,
4076}
4077
4078impl<E> Styled for Stateful<E>
4079where
4080 E: Styled,
4081{
4082 fn style(&mut self) -> &mut StyleRefinement {
4083 self.element.style()
4084 }
4085}
4086
4087impl<E> StatefulInteractiveElement for Stateful<E>
4088where
4089 E: Element,
4090 Self: InteractiveElement,
4091{
4092}
4093
4094impl<E> InteractiveElement for Stateful<E>
4095where
4096 E: InteractiveElement,
4097{
4098 fn interactivity(&mut self) -> &mut Interactivity {
4099 self.element.interactivity()
4100 }
4101}
4102
4103impl<E> Element for Stateful<E>
4104where
4105 E: Element,
4106{
4107 type RequestLayoutState = E::RequestLayoutState;
4108 type PrepaintState = E::PrepaintState;
4109
4110 fn id(&self) -> Option<ElementId> {
4111 self.element.id()
4112 }
4113
4114 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4115 self.element.source_location()
4116 }
4117
4118 fn a11y_role(&self) -> Option<accesskit::Role> {
4119 self.element.a11y_role()
4120 }
4121
4122 fn write_a11y_info(&self, node: &mut accesskit::Node) {
4123 self.element.write_a11y_info(node);
4124 }
4125
4126 fn a11y_synthetic_children(
4127 &mut self,
4128 prepaint: &mut Self::PrepaintState,
4129 builder: &mut crate::A11ySubtreeBuilder,
4130 ) {
4131 self.element.a11y_synthetic_children(prepaint, builder);
4132 }
4133
4134 fn request_layout(
4135 &mut self,
4136 id: Option<&GlobalElementId>,
4137 inspector_id: Option<&InspectorElementId>,
4138 window: &mut Window,
4139 cx: &mut App,
4140 ) -> (LayoutId, Self::RequestLayoutState) {
4141 self.element.request_layout(id, inspector_id, window, cx)
4142 }
4143
4144 fn prepaint(
4145 &mut self,
4146 id: Option<&GlobalElementId>,
4147 inspector_id: Option<&InspectorElementId>,
4148 bounds: Bounds<Pixels>,
4149 state: &mut Self::RequestLayoutState,
4150 window: &mut Window,
4151 cx: &mut App,
4152 ) -> E::PrepaintState {
4153 self.element
4154 .prepaint(id, inspector_id, bounds, state, window, cx)
4155 }
4156
4157 fn paint(
4158 &mut self,
4159 id: Option<&GlobalElementId>,
4160 inspector_id: Option<&InspectorElementId>,
4161 bounds: Bounds<Pixels>,
4162 request_layout: &mut Self::RequestLayoutState,
4163 prepaint: &mut Self::PrepaintState,
4164 window: &mut Window,
4165 cx: &mut App,
4166 ) {
4167 self.element.paint(
4168 id,
4169 inspector_id,
4170 bounds,
4171 request_layout,
4172 prepaint,
4173 window,
4174 cx,
4175 );
4176 }
4177}
4178
4179impl<E> IntoElement for Stateful<E>
4180where
4181 E: Element,
4182{
4183 type Element = Self;
4184
4185 fn into_element(self) -> Self::Element {
4186 self
4187 }
4188}
4189
4190impl<E> ParentElement for Stateful<E>
4191where
4192 E: ParentElement,
4193{
4194 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
4195 self.element.extend(elements)
4196 }
4197}
4198
4199/// Represents an element that can be scrolled *to* in its parent element.
4200/// Contrary to [ScrollHandle::scroll_to_active_item], an anchored element does not have to be an immediate child of the parent.
4201#[derive(Clone)]
4202pub struct ScrollAnchor {
4203 handle: ScrollHandle,
4204 last_origin: Rc<RefCell<Point<Pixels>>>,
4205}
4206
4207impl ScrollAnchor {
4208 /// Creates a [ScrollAnchor] associated with a given [ScrollHandle].
4209 pub fn for_handle(handle: ScrollHandle) -> Self {
4210 Self {
4211 handle,
4212 last_origin: Default::default(),
4213 }
4214 }
4215 /// Request scroll to this item on the next frame.
4216 pub fn scroll_to(&self, window: &mut Window, _cx: &mut App) {
4217 let this = self.clone();
4218
4219 window.on_next_frame(move |_, _| {
4220 let viewport_bounds = this.handle.bounds();
4221 let self_bounds = *this.last_origin.borrow();
4222 this.handle.set_offset(viewport_bounds.origin - self_bounds);
4223 });
4224 }
4225}
4226
4227#[derive(Default, Debug)]
4228struct ScrollHandleState {
4229 offset: Rc<RefCell<Point<Pixels>>>,
4230 ongoing_scroll: Rc<RefCell<OngoingScroll>>,
4231 bounds: Bounds<Pixels>,
4232 max_offset: Point<Pixels>,
4233 child_bounds: Vec<Bounds<Pixels>>,
4234 scroll_to_bottom: bool,
4235 overflow: Point<Overflow>,
4236 active_item: Option<ScrollActiveItem>,
4237}
4238
4239#[derive(Default, Debug, Clone, Copy)]
4240struct ScrollActiveItem {
4241 index: usize,
4242 strategy: ScrollStrategy,
4243}
4244
4245#[derive(Default, Debug, Clone, Copy)]
4246enum ScrollStrategy {
4247 #[default]
4248 FirstVisible,
4249 Top,
4250}
4251
4252/// A handle to the scrollable aspects of an element.
4253/// Used for accessing scroll state, like the current scroll offset,
4254/// and for mutating the scroll state, like scrolling to a specific child.
4255#[derive(Clone, Debug)]
4256pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
4257
4258impl Default for ScrollHandle {
4259 fn default() -> Self {
4260 Self::new()
4261 }
4262}
4263
4264impl ScrollHandle {
4265 /// Construct a new scroll handle.
4266 pub fn new() -> Self {
4267 Self(Rc::default())
4268 }
4269
4270 /// Get the current scroll offset.
4271 pub fn offset(&self) -> Point<Pixels> {
4272 *self.0.borrow().offset.borrow()
4273 }
4274
4275 /// Get the maximum scroll offset.
4276 pub fn max_offset(&self) -> Point<Pixels> {
4277 self.0.borrow().max_offset
4278 }
4279
4280 /// Get the top child that's scrolled into view.
4281 pub fn top_item(&self) -> usize {
4282 let state = self.0.borrow();
4283 let top = state.bounds.top() - state.offset.borrow().y;
4284
4285 match state.child_bounds.binary_search_by(|bounds| {
4286 if top < bounds.top() {
4287 Ordering::Greater
4288 } else if top > bounds.bottom() {
4289 Ordering::Less
4290 } else {
4291 Ordering::Equal
4292 }
4293 }) {
4294 Ok(ix) => ix,
4295 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4296 }
4297 }
4298
4299 /// Get the bottom child that's scrolled into view.
4300 pub fn bottom_item(&self) -> usize {
4301 let state = self.0.borrow();
4302 let bottom = state.bounds.bottom() - state.offset.borrow().y;
4303
4304 match state.child_bounds.binary_search_by(|bounds| {
4305 if bottom < bounds.top() {
4306 Ordering::Greater
4307 } else if bottom > bounds.bottom() {
4308 Ordering::Less
4309 } else {
4310 Ordering::Equal
4311 }
4312 }) {
4313 Ok(ix) => ix,
4314 Err(ix) => ix.min(state.child_bounds.len().saturating_sub(1)),
4315 }
4316 }
4317
4318 /// Return the bounds into which this child is painted
4319 pub fn bounds(&self) -> Bounds<Pixels> {
4320 self.0.borrow().bounds
4321 }
4322
4323 /// Get the bounds for a specific child.
4324 pub fn bounds_for_item(&self, ix: usize) -> Option<Bounds<Pixels>> {
4325 self.0.borrow().child_bounds.get(ix).cloned()
4326 }
4327
4328 /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
4329 pub fn scroll_to_item(&self, ix: usize) {
4330 let mut state = self.0.borrow_mut();
4331 state.active_item = Some(ScrollActiveItem {
4332 index: ix,
4333 strategy: ScrollStrategy::default(),
4334 });
4335 }
4336
4337 /// Update [ScrollHandleState]'s active item for scrolling to in prepaint
4338 /// This scrolls the minimal amount to ensure that the child is the first visible element
4339 pub fn scroll_to_top_of_item(&self, ix: usize) {
4340 let mut state = self.0.borrow_mut();
4341 state.active_item = Some(ScrollActiveItem {
4342 index: ix,
4343 strategy: ScrollStrategy::Top,
4344 });
4345 }
4346
4347 /// Scrolls the minimal amount to either ensure that the child is
4348 /// fully visible or the top element of the view depends on the
4349 /// scroll strategy
4350 fn scroll_to_active_item(&self) {
4351 let mut state = self.0.borrow_mut();
4352
4353 let Some(active_item) = state.active_item else {
4354 return;
4355 };
4356
4357 let active_item = match state.child_bounds.get(active_item.index) {
4358 Some(bounds) => {
4359 let mut scroll_offset = state.offset.borrow_mut();
4360
4361 match active_item.strategy {
4362 ScrollStrategy::FirstVisible => {
4363 if state.overflow.y == Overflow::Scroll {
4364 let child_height = bounds.size.height;
4365 let viewport_height = state.bounds.size.height;
4366 if child_height > viewport_height {
4367 scroll_offset.y = state.bounds.top() - bounds.top();
4368 } else if bounds.top() + scroll_offset.y < state.bounds.top() {
4369 scroll_offset.y = state.bounds.top() - bounds.top();
4370 } else if bounds.bottom() + scroll_offset.y > state.bounds.bottom() {
4371 scroll_offset.y = state.bounds.bottom() - bounds.bottom();
4372 }
4373 }
4374 }
4375 ScrollStrategy::Top => {
4376 scroll_offset.y = state.bounds.top() - bounds.top();
4377 }
4378 }
4379
4380 if state.overflow.x == Overflow::Scroll {
4381 let child_width = bounds.size.width;
4382 let viewport_width = state.bounds.size.width;
4383 if child_width > viewport_width {
4384 scroll_offset.x = state.bounds.left() - bounds.left();
4385 } else if bounds.left() + scroll_offset.x < state.bounds.left() {
4386 scroll_offset.x = state.bounds.left() - bounds.left();
4387 } else if bounds.right() + scroll_offset.x > state.bounds.right() {
4388 scroll_offset.x = state.bounds.right() - bounds.right();
4389 }
4390 }
4391 None
4392 }
4393 None => Some(active_item),
4394 };
4395 state.active_item = active_item;
4396 }
4397
4398 /// Scrolls to the bottom.
4399 pub fn scroll_to_bottom(&self) {
4400 let mut state = self.0.borrow_mut();
4401 state.scroll_to_bottom = true;
4402 }
4403
4404 /// Set the offset explicitly. The offset is the distance from the top left of the
4405 /// parent container to the top left of the first child.
4406 /// As you scroll further down the offset becomes more negative.
4407 pub fn set_offset(&self, mut position: Point<Pixels>) {
4408 let state = self.0.borrow();
4409 *state.offset.borrow_mut() = position;
4410 }
4411
4412 /// Get the logical scroll top, based on a child index and a pixel offset.
4413 pub fn logical_scroll_top(&self) -> (usize, Pixels) {
4414 let ix = self.top_item();
4415 let state = self.0.borrow();
4416
4417 if let Some(child_bounds) = state.child_bounds.get(ix) {
4418 (
4419 ix,
4420 child_bounds.top() + state.offset.borrow().y - state.bounds.top(),
4421 )
4422 } else {
4423 (ix, px(0.))
4424 }
4425 }
4426
4427 /// Get the logical scroll bottom, based on a child index and a pixel offset.
4428 pub fn logical_scroll_bottom(&self) -> (usize, Pixels) {
4429 let ix = self.bottom_item();
4430 let state = self.0.borrow();
4431
4432 if let Some(child_bounds) = state.child_bounds.get(ix) {
4433 (
4434 ix,
4435 child_bounds.bottom() + state.offset.borrow().y - state.bounds.bottom(),
4436 )
4437 } else {
4438 (ix, px(0.))
4439 }
4440 }
4441
4442 /// Get the count of children for scrollable item.
4443 pub fn children_count(&self) -> usize {
4444 self.0.borrow().child_bounds.len()
4445 }
4446}
4447
4448#[cfg(test)]
4449mod tests {
4450 use super::*;
4451 use crate::{
4452 AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, Keystroke,
4453 MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas, util::FluentBuilder as _,
4454 };
4455 use std::{cell::Cell, rc::Weak};
4456
4457 struct GroupHoverTestView {
4458 render_count: Rc<Cell<usize>>,
4459 anonymous_paint_count: Rc<Cell<usize>>,
4460 stateful_width: Rc<Cell<Pixels>>,
4461 }
4462
4463 impl Render for GroupHoverTestView {
4464 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4465 self.render_count.set(self.render_count.get() + 1);
4466 let anonymous_paint_count = self.anonymous_paint_count.clone();
4467 let stateful_width = self.stateful_width.clone();
4468 div().size_full().child(
4469 div()
4470 .ml(px(20.))
4471 .mt(px(20.))
4472 .size(px(50.))
4473 .relative()
4474 .group("hover-group")
4475 .child(
4476 div()
4477 .absolute()
4478 .size_full()
4479 .invisible()
4480 .group_hover("hover-group", |style| style.visible())
4481 .child(canvas(
4482 |_, _, _| {},
4483 move |_, _, _, _| {
4484 anonymous_paint_count.set(anonymous_paint_count.get() + 1)
4485 },
4486 )),
4487 )
4488 .child(
4489 div()
4490 .id("stateful-group-hover-target")
4491 .absolute()
4492 .top_0()
4493 .left_0()
4494 .size(px(10.))
4495 .group_hover("hover-group", |style| style.size(px(20.)))
4496 .child(canvas(
4497 move |bounds, _, _| stateful_width.set(bounds.size.width),
4498 |_, _, _, _| {},
4499 )),
4500 ),
4501 )
4502 }
4503 }
4504
4505 #[gpui::test]
4506 fn group_hover_styles_update_only_on_transitions(cx: &mut TestAppContext) {
4507 let render_count = Rc::new(Cell::new(0));
4508 let anonymous_paint_count = Rc::new(Cell::new(0));
4509 let stateful_width = Rc::new(Cell::new(px(0.)));
4510 let window = cx.add_window({
4511 let render_count = render_count.clone();
4512 let anonymous_paint_count = anonymous_paint_count.clone();
4513 let stateful_width = stateful_width.clone();
4514 move |_, _| GroupHoverTestView {
4515 render_count,
4516 anonymous_paint_count,
4517 stateful_width,
4518 }
4519 });
4520 let window = AnyWindowHandle::from(window);
4521
4522 cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
4523 .unwrap();
4524 assert_eq!(anonymous_paint_count.get(), 0);
4525 assert_eq!(stateful_width.get(), px(10.));
4526
4527 let move_mouse = |cx: &mut TestAppContext, position| {
4528 cx.update_window(window, |_, window, cx| {
4529 window.simulate_mouse_move(position, cx)
4530 })
4531 .unwrap();
4532 };
4533
4534 let initial_render_count = render_count.get();
4535 move_mouse(cx, point(px(25.), px(25.)));
4536 assert_eq!(render_count.get(), initial_render_count + 1);
4537 assert_eq!(anonymous_paint_count.get(), 1);
4538 assert_eq!(stateful_width.get(), px(20.));
4539
4540 move_mouse(cx, point(px(30.), px(30.)));
4541 assert_eq!(render_count.get(), initial_render_count + 1);
4542 assert_eq!(anonymous_paint_count.get(), 1);
4543 assert_eq!(stateful_width.get(), px(20.));
4544
4545 move_mouse(cx, point(px(5.), px(5.)));
4546 assert_eq!(render_count.get(), initial_render_count + 2);
4547 assert_eq!(anonymous_paint_count.get(), 1);
4548 assert_eq!(stateful_width.get(), px(10.));
4549
4550 move_mouse(cx, point(px(10.), px(10.)));
4551 assert_eq!(render_count.get(), initial_render_count + 2);
4552 assert_eq!(anonymous_paint_count.get(), 1);
4553 assert_eq!(stateful_width.get(), px(10.));
4554 }
4555
4556 struct HoverListenerLayoutTestView {
4557 target_left: Pixels,
4558 hover_transitions: Rc<RefCell<Vec<bool>>>,
4559 }
4560
4561 impl Render for HoverListenerLayoutTestView {
4562 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4563 let hover_transitions = self.hover_transitions.clone();
4564 div().relative().size_full().child(
4565 div()
4566 .id("hover-target")
4567 .absolute()
4568 .left(self.target_left)
4569 .top_0()
4570 .size(px(20.))
4571 .on_click(|_, _, _| {})
4572 .on_hover(move |is_hovered, _, _| {
4573 hover_transitions.borrow_mut().push(*is_hovered);
4574 }),
4575 )
4576 }
4577 }
4578
4579 #[gpui::test]
4580 fn default_hover_listener_updates_when_layout_changes_under_stationary_mouse(
4581 cx: &mut TestAppContext,
4582 ) {
4583 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4584 let window = cx.add_window({
4585 let hover_transitions = hover_transitions.clone();
4586 move |_, _| HoverListenerLayoutTestView {
4587 target_left: px(40.),
4588 hover_transitions,
4589 }
4590 });
4591 let any_window = AnyWindowHandle::from(window);
4592
4593 cx.update_window(any_window, |_, window, cx| {
4594 window.draw(cx).clear(cx);
4595 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4596 })
4597 .unwrap();
4598 assert!(hover_transitions.borrow().is_empty());
4599
4600 window
4601 .update(cx, |view, _, cx| {
4602 view.target_left = px(0.);
4603 cx.notify();
4604 })
4605 .unwrap();
4606 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4607 .unwrap();
4608 assert_eq!(*hover_transitions.borrow(), [true]);
4609
4610 window
4611 .update(cx, |view, _, cx| {
4612 view.target_left = px(40.);
4613 cx.notify();
4614 })
4615 .unwrap();
4616 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4617 .unwrap();
4618 assert_eq!(*hover_transitions.borrow(), [true, false]);
4619 }
4620
4621 #[gpui::test]
4622 fn default_hover_listener_ends_after_key_press(cx: &mut TestAppContext) {
4623 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4624 let window = cx.add_window({
4625 let hover_transitions = hover_transitions.clone();
4626 move |_, _| HoverListenerLayoutTestView {
4627 target_left: px(0.),
4628 hover_transitions,
4629 }
4630 });
4631 let any_window = AnyWindowHandle::from(window);
4632
4633 cx.update_window(any_window, |_, window, cx| {
4634 window.draw(cx).clear(cx);
4635 window.simulate_mouse_move(point(px(10.), px(10.)), cx);
4636 })
4637 .unwrap();
4638 assert_eq!(*hover_transitions.borrow(), [true]);
4639
4640 key_down(cx, any_window, "a");
4641 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4642 .unwrap();
4643 assert_eq!(*hover_transitions.borrow(), [true, false]);
4644 }
4645
4646 struct HoverListenerModeLayoutTestView {
4647 target_left: Pixels,
4648 hover_transitions: Rc<RefCell<Vec<bool>>>,
4649 }
4650
4651 impl Render for HoverListenerModeLayoutTestView {
4652 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4653 let hover_transitions = self.hover_transitions.clone();
4654 div().relative().size_full().child(
4655 div()
4656 .id("hover-target")
4657 .absolute()
4658 .left(self.target_left)
4659 .top_0()
4660 .size(px(20.))
4661 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
4662 .on_hover(move |is_hovered, _, _| {
4663 hover_transitions.borrow_mut().push(*is_hovered);
4664 }),
4665 )
4666 }
4667 }
4668
4669 #[gpui::test]
4670 fn input_modality_independent_hover_listener_updates_after_key_press(cx: &mut TestAppContext) {
4671 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4672 let window = cx.add_window({
4673 let hover_transitions = hover_transitions.clone();
4674 move |_, _| HoverListenerModeLayoutTestView {
4675 target_left: px(40.),
4676 hover_transitions,
4677 }
4678 });
4679 let any_window = AnyWindowHandle::from(window);
4680 let pointer_position = point(px(10.), px(10.));
4681
4682 cx.update_window(any_window, |_, window, cx| {
4683 window.draw(cx).clear(cx);
4684 window.simulate_mouse_move(pointer_position, cx);
4685 })
4686 .unwrap();
4687 assert!(hover_transitions.borrow().is_empty());
4688
4689 key_down(cx, any_window, "a");
4690 window
4691 .update(cx, |view, _, cx| {
4692 view.target_left = px(0.);
4693 cx.notify();
4694 })
4695 .unwrap();
4696 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4697 .unwrap();
4698 assert_eq!(*hover_transitions.borrow(), [true]);
4699
4700 key_down(cx, any_window, "b");
4701 cx.update_window(any_window, |_, window, cx| window.draw(cx).clear(cx))
4702 .unwrap();
4703 assert_eq!(*hover_transitions.borrow(), [true]);
4704
4705 cx.update_window(any_window, |_, window, cx| {
4706 window.simulate_mouse_move(point(px(30.), px(10.)), cx);
4707 })
4708 .unwrap();
4709 assert_eq!(*hover_transitions.borrow(), [true, false]);
4710
4711 cx.update_window(any_window, |_, window, cx| {
4712 window.simulate_mouse_move(pointer_position, cx);
4713 window.dispatch_event(
4714 MouseExitEvent {
4715 position: pointer_position,
4716 ..Default::default()
4717 }
4718 .to_platform_input(),
4719 cx,
4720 );
4721 })
4722 .unwrap();
4723 assert_eq!(*hover_transitions.borrow(), [true, false, true, false]);
4724 }
4725
4726 #[gpui::test]
4727 fn default_hover_listener_remains_hovered_during_stationary_mouse_press(
4728 cx: &mut TestAppContext,
4729 ) {
4730 let hover_transitions = Rc::new(RefCell::new(Vec::new()));
4731 let window = cx.add_window({
4732 let hover_transitions = hover_transitions.clone();
4733 move |_, _| HoverListenerLayoutTestView {
4734 target_left: px(0.),
4735 hover_transitions,
4736 }
4737 });
4738 let any_window = AnyWindowHandle::from(window);
4739 let mouse_position = point(px(10.), px(10.));
4740
4741 cx.update_window(any_window, |_, window, cx| {
4742 window.draw(cx).clear(cx);
4743 window.simulate_mouse_move(mouse_position, cx);
4744 })
4745 .unwrap();
4746 assert_eq!(*hover_transitions.borrow(), [true]);
4747
4748 cx.update_window(any_window, |_, window, cx| {
4749 window.dispatch_event(
4750 MouseDownEvent {
4751 position: mouse_position,
4752 button: MouseButton::Left,
4753 modifiers: Default::default(),
4754 click_count: 1,
4755 first_mouse: false,
4756 }
4757 .to_platform_input(),
4758 cx,
4759 );
4760 window.draw(cx).clear(cx);
4761 })
4762 .unwrap();
4763 assert_eq!(*hover_transitions.borrow(), [true]);
4764
4765 cx.update_window(any_window, |_, window, cx| {
4766 window.dispatch_event(
4767 MouseUpEvent {
4768 position: mouse_position,
4769 button: MouseButton::Left,
4770 modifiers: Default::default(),
4771 click_count: 1,
4772 }
4773 .to_platform_input(),
4774 cx,
4775 );
4776 window.draw(cx).clear(cx);
4777 })
4778 .unwrap();
4779 assert_eq!(*hover_transitions.borrow(), [true]);
4780 }
4781
4782 struct TestTooltipView;
4783
4784 impl Render for TestTooltipView {
4785 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4786 div().w(px(20.)).h(px(20.)).child("tooltip")
4787 }
4788 }
4789
4790 type CapturedActiveTooltip = Rc<RefCell<Option<Weak<RefCell<Option<ActiveTooltip>>>>>>;
4791
4792 struct TooltipCaptureElement {
4793 child: AnyElement,
4794 captured_active_tooltip: CapturedActiveTooltip,
4795 }
4796
4797 impl IntoElement for TooltipCaptureElement {
4798 type Element = Self;
4799
4800 fn into_element(self) -> Self::Element {
4801 self
4802 }
4803 }
4804
4805 impl Element for TooltipCaptureElement {
4806 type RequestLayoutState = ();
4807 type PrepaintState = ();
4808
4809 fn id(&self) -> Option<ElementId> {
4810 None
4811 }
4812
4813 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
4814 None
4815 }
4816
4817 fn request_layout(
4818 &mut self,
4819 _id: Option<&GlobalElementId>,
4820 _inspector_id: Option<&InspectorElementId>,
4821 window: &mut Window,
4822 cx: &mut App,
4823 ) -> (LayoutId, Self::RequestLayoutState) {
4824 (self.child.request_layout(window, cx), ())
4825 }
4826
4827 fn prepaint(
4828 &mut self,
4829 _id: Option<&GlobalElementId>,
4830 _inspector_id: Option<&InspectorElementId>,
4831 _bounds: Bounds<Pixels>,
4832 _request_layout: &mut Self::RequestLayoutState,
4833 window: &mut Window,
4834 cx: &mut App,
4835 ) -> Self::PrepaintState {
4836 self.child.prepaint(window, cx);
4837 }
4838
4839 fn paint(
4840 &mut self,
4841 _id: Option<&GlobalElementId>,
4842 _inspector_id: Option<&InspectorElementId>,
4843 _bounds: Bounds<Pixels>,
4844 _request_layout: &mut Self::RequestLayoutState,
4845 _prepaint: &mut Self::PrepaintState,
4846 window: &mut Window,
4847 cx: &mut App,
4848 ) {
4849 self.child.paint(window, cx);
4850 window.with_global_id("target".into(), |global_id, window| {
4851 window.with_element_state::<InteractiveElementState, _>(
4852 global_id,
4853 |state, _window| {
4854 let state = state.unwrap();
4855 *self.captured_active_tooltip.borrow_mut() =
4856 state.active_tooltip.as_ref().map(Rc::downgrade);
4857 ((), state)
4858 },
4859 )
4860 });
4861 }
4862 }
4863
4864 struct TooltipOwner {
4865 captured_active_tooltip: CapturedActiveTooltip,
4866 show_delay_override: Option<Duration>,
4867 }
4868
4869 impl Render for TooltipOwner {
4870 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4871 TooltipCaptureElement {
4872 child: div()
4873 .size_full()
4874 .child(
4875 div()
4876 .id("target")
4877 .w(px(50.))
4878 .h(px(50.))
4879 .tooltip(|_, cx| cx.new(|_| TestTooltipView).into())
4880 .when_some(self.show_delay_override, |this, delay| {
4881 this.tooltip_show_delay(delay)
4882 }),
4883 )
4884 .into_any_element(),
4885 captured_active_tooltip: self.captured_active_tooltip.clone(),
4886 }
4887 }
4888 }
4889
4890 #[test]
4891 fn scroll_handle_aligns_wide_children_to_left_edge() {
4892 let handle = ScrollHandle::new();
4893 {
4894 let mut state = handle.0.borrow_mut();
4895 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(80.), px(20.)));
4896 state.child_bounds = vec![Bounds::new(point(px(25.), px(0.)), size(px(200.), px(20.)))];
4897 state.overflow.x = Overflow::Scroll;
4898 state.active_item = Some(ScrollActiveItem {
4899 index: 0,
4900 strategy: ScrollStrategy::default(),
4901 });
4902 }
4903
4904 handle.scroll_to_active_item();
4905
4906 assert_eq!(handle.offset().x, px(-25.));
4907 }
4908
4909 #[test]
4910 fn scroll_handle_aligns_tall_children_to_top_edge() {
4911 let handle = ScrollHandle::new();
4912 {
4913 let mut state = handle.0.borrow_mut();
4914 state.bounds = Bounds::new(point(px(0.), px(0.)), size(px(20.), px(80.)));
4915 state.child_bounds = vec![Bounds::new(point(px(0.), px(25.)), size(px(20.), px(200.)))];
4916 state.overflow.y = Overflow::Scroll;
4917 state.active_item = Some(ScrollActiveItem {
4918 index: 0,
4919 strategy: ScrollStrategy::default(),
4920 });
4921 }
4922
4923 handle.scroll_to_active_item();
4924
4925 assert_eq!(handle.offset().y, px(-25.));
4926 }
4927
4928 #[test]
4929 fn long_press_shows_tooltip_until_touch_ends() {
4930 let (mut test_app, any_window, captured_active_tooltip) = create_tooltip_owner_test(None);
4931 let active_tooltip = captured_active_tooltip
4932 .borrow()
4933 .clone()
4934 .unwrap()
4935 .upgrade()
4936 .unwrap();
4937 let touch_id = TouchId(1);
4938 let touch_position = point(px(49.), px(10.));
4939
4940 test_app
4941 .update_window(any_window, |_, window, cx| {
4942 window.dispatch_event(
4943 TouchEvent {
4944 id: touch_id,
4945 phase:
4946… afgekapt